import numba import cmath from numba import jit @jit def sum(x, y): return x + y %timeit sum(2,2) @jit('f8(f8,f8)') def sum(x, y): return x + y %timeit sum(2,2) import numpy as np a=np.random.randn(100) %timeit a.sum() @jit('f8(f8[:])') def sum1d(array): sum = 0.0 for i in range(array.shape[0]): sum += array[i] return sum %timeit sum1d(a) import numpy as np X = np.random.random((1000, 3)) def pairwise_numpy(X): return np.sqrt(((X[:, None, :] - X) ** 2).sum(-1)) %timeit pairwise_numpy(X) def pairwise_python(X): M = X.shape[0] N = X.shape[1] D = np.empty((M, M), dtype=np.float) for i in range(M): for j in range(M): d = 0.0 for k in range(N): tmp = X[i, k] - X[j, k] d += tmp * tmp D[i, j] = np.sqrt(d) return D %timeit pairwise_python(X) from scipy.spatial.distance import cdist %timeit cdist(X, X) from sklearn.metrics import euclidean_distances %timeit euclidean_distances(X, X) from numba import double from numba.decorators import jit, autojit pairwise_numba = jit(pairwise_python) %timeit pairwise_numba(X) %load_ext cythonmagic %%cython import numpy as np cimport cython from libc.math cimport sqrt @cython.boundscheck(False) @cython.wraparound(False) def pairwise_cython(double[:, ::1] X): cdef int M = X.shape[0] cdef int N = X.shape[1] cdef double tmp, d cdef double[:, ::1] D = np.empty((M, M), dtype=np.float64) for i in range(M): for j in range(M): d = 0.0 for k in range(N): tmp = X[i, k] - X[j, k] d += tmp * tmp D[i, j] = sqrt(d) return np.asarray(D) %timeit pairwise_cython(X) def bubblesort(X): N = len(X) for end in range(N, 1, -1): for i in range(end - 1): cur = X[i] if cur > X[i + 1]: tmp = X[i] X[i] = X[i + 1] X[i + 1] = tmp import numpy as np original = np.arange(0.0, 10.0, 0.01, dtype='f4') shuffled = original.copy() np.random.shuffle(shuffled) #Check if it works! sorted = shuffled.copy() bubblesort(sorted) print(np.array_equal(sorted, original)) #Check execution time sorted[:] = shuffled[:] %timeit sorted[:] = shuffled[:]; bubblesort(sorted) @jit("void(f4[:])") def bubblesort_jit(X): N = len(X) for end in range(N, 1, -1): for i in range(end - 1): cur = X[i] if cur > X[i + 1]: tmp = X[i] X[i] = X[i + 1] X[i + 1] = tmp sorted[:] = shuffled[:] # reset to shuffled before sorting bubblesort_jit(sorted) print(np.array_equal(sorted, original)) %timeit sorted[:] = shuffled[:]; bubblesort_jit(sorted) @jit(locals=dict(array=double[:, :], scalar1=double)) def func(array): scalar1 = array[0, 0] # scalar is declared double scalar2 = double(array[0, 0]) numba.typeof(1.0) numba.typeof(cmath.sqrt(-1)) @jit def variable_ressign(arg): arg = 1.0 arg = "hello" arg = object() var = arg var = "world" @jit def incompatible_types(arg): if arg > 10: x = "hello" else: x = arg return x incompatible_types(5) @jit def sum(x, y): array = np.arange(x * y).reshape(x, y) sum = 0 for i in range(x): for j in range(y): sum += array[i, j] return sum %timeit sum(100,100) # force compilation in nopython mode @jit(nopython=True) def jitted_loop(array, x, y): sum = 0 for i in range(x): for j in range(y): sum += array[i, j] return sum import numpy as np arr=np.random.randn(100,100) %timeit jitted_loop(arr,100,100) # compiled in object mode @jit def sum(x, y): array = np.arange(x * y).reshape(x, y) return jitted_loop(array, x, y) %timeit sum(100,100) import math from numba import vectorize @vectorize(['float64(float64, float64)']) def my_ufunc(x, y): return x+y+math.sqrt(x*y) a = np.arange(1.0, 10.0) b = np.arange(1.0, 10.0) # Calls compiled version of my_ufunc for each element of a and b print(my_ufunc(a, b)) import numpy def filter2d(image, filt): M, N = image.shape Mf, Nf = filt.shape Mf2 = Mf // 2 Nf2 = Nf // 2 result = numpy.zeros_like(image) for i in range(Mf2, M - Mf2): for j in range(Nf2, N - Nf2): num = 0.0 for ii in range(Mf): for jj in range(Nf): num += (filt[Mf-1-ii, Nf-1-jj] * image[i-Mf2+ii, j-Nf2+jj]) result[i, j] = num return result # This kind of quadruply-nested for-loop is going to be quite slow. # Using Numba we can compile this code to LLVM which then gets # compiled to machine code: from numba import double, jit fastfilter_2d = jit(double[:,:](double[:,:], double[:,:]))(filter2d) # Now fastfilter_2d runs at speeds as if you had first translated # it to C, compiled the code and wrapped it with Python image = numpy.random.random((100, 100)) filt = numpy.random.random((10, 10)) plt.figure(1) plt.imshow(image) plt.gcf().set_size_inches(6, 6) %timeit result1=filter2d(image,filt) %timeit result2=fastfilter_2d(image,filt) result1=filter2d(image,filt) plt.subplot(221) plt.imshow(result1) plt.title('Filter') result2=fastfilter_2d(image,filt) plt.subplot(222) plt.imshow(result2) plt.title('Fast Filter') plt.gcf().set_size_inches(6, 6) from __future__ import division import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.pyplot as plt #IPython magic command for inline plotting %matplotlib inline #a better plot shape for IPython mpl.rcParams['figure.figsize']=[15,3] def mandelbrot(minR, maxR, minI, maxI, samples=51, iters=25): """ Generate the Mandelbrot set within the boundaries of the limits maxR, minR, minI, maxI with samples and a maximum iteration of iters. """ # Generate a mesh for the set. setR = np.linspace(minR, maxR, samples) setI = np.linspace(minI, maxI, samples) # Calculate the values at each point of the mesh by the escape-time # fractal algorithm. pts = np.zeros([samples, samples]) for ii in range(1, len(setR)): for jj in range(1, len(setI)): it = 0 x = 0.0 y = 0.0 xx = setR[ii] yy = setI[jj] # Look for escape---i.e., does the value settle down in a few # iterations or does it keep going? while(x * x + y * y < 4 and it < iters): xtmp = x * x - y * y + xx y = 2 * x * y + yy x = xtmp it += 1 pts[ii, jj] = it return setR, setI, pts # Plot boundaries minR = -2.25 maxR = 0.75 minI = -1.5 maxI = 1.5 samples = 201 iters = 20 x, y, z = mandelbrot(minR, maxR, minI, maxI, samples, iters) z = z.transpose() mpl.rcParams['figure.figsize']=[8,8] plt.imshow(z, interpolation='nearest') plt.show() %timeit mandelbrot(minR, maxR, minI, maxI, samples, iters) mandelbrot_jit=jit(mandelbrot) %timeit mandelbrot_jit(minR, maxR, minI, maxI, samples, iters)