def video_flow_FB(): cam = cv2.VideoCapture(0) ret, frame1 = cam.read() prvs = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) while 1: ret, frame2 = cam.read() next = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) flow = cv2.calcOpticalFlowFarneback(prvs, next, 0.5, 3, 15, 3, 5, 1.2, 0) imFilter = cv2.GaussianBlur(next, (5, 5), 1.5) bg_numba = autojit(get_background) bg = bg_numba(imFilter, flow) edge_numba = autojit(get_edge) lap = edge_numba(bg) lap = get_edge_sobel(bg) cv2.imshow("flow", bg) k = cv2.waitKey(30) & 0xFF if k == 27: cam.release() cv2.destroyAllWindows() break prvs = next
def pseudoECG(self, x, y, z, key='vmem'): vmem = self.data[key] L,M,N = vmem.shape def pixelwise_distance(x,y,z): dist = np.zeros((M, N)) for i in range(M): for j in range(N): dist[i, j] = np.sqrt( z**2 + (y - i)**2 + (x - j)**2 ) return dist im_dist = autojit(pixelwise_distance)(x,y,z) R_y, R_x = np.gradient(1/im_dist) def framewise_ecg(): ecg = np.zeros((L)) for f in range(L): V_y, V_x = np.gradient(vmem[f]) ecg[f] = -np.sum( R_x*V_x + R_y*V_y ) return ecg ecg = autojit(framewise_ecg)() return ecg
def pseudoECG(self, i, j): eta = np.ones((3,3), dtype=np.float64) k = np.ones((3,3), dtype=np.float64) k[1,1] = -8. k = k*eta phie = self.data['phie'] L,M,N = phie.shape def pixelwise_distance(pos_y, pos_x, pos_z = 0.): dist = np.zeros((M, N)) for i_ in range(M): for j_ in range(N): dist[i_, j_] = np.sqrt( pos_z**2 + (pos_y - i_)**2 + (pos_x - j_)**2 ) return dist im_dist = autojit(pixelwise_distance)(i, j) im_dist[i, j] = 1.0 ## to avoid zero division def framewise_ecg(): ecg = np.zeros((L)) for f in range(L): im_conv = convolve(phie[f,:,:], k, mode='constant', cval=0.) im_mul = im_conv/im_dist im_mul[i, j] = 0.0 ecg[f] = np.sum(im_mul) return ecg ecg = autojit(framewise_ecg)() return ecg
def __init__(self, vmem, width, f_event = f_pixel_diff_thre, **kwargs): super(PhaseMapEvent, self).__init__(vmem, width) v = vmem.data[:,::self.shrink,::self.shrink] def f_pixelwise(v): L,H,W = v.shape for i in range(H): for j in range(W): ts = v[:,i,j] t_event = f_event(ts, kwargs) for n in range(1,len(t_event)): t_start = t_event[n-1] t_end = t_event[n] dpdt = 2 * np.pi / float(t_end - t_start) ts_p = dpdt * np.arange(L-t_start).astype(np.float64) - np.pi self.data[t_start:, i, j] = ts_p autojit(f_pixelwise)(v) self.data = phaseComplement(self.data) if 'afterLast' in kwargs.keys(): if kwargs['afterLast'] is 'continue': while( np.sum(( self.data > 2*np.pi )*1) + np.sum(( self.data < -2*np.pi )*1) > 0 ): self.data = phaseComplement(self.data)
def run_optimisation(): #set initialvalues to pass to simulator dt = 0.05 file = "C:\\Users\\mattr\\OneDrive\\Documents\\Stromolo Job\\test_otherheaters.log" constants = default_constants() #import pdb; pdb.set_trace() simulate_numba = autojit(simulate) temps, heaters, ambient = read_data(file, dt) constants[15] = ambient[0, 0] import matplotlib.pyplot as plt out = simulate_numba(constants, temps, heaters, ambient, dt, True) plt.plot(out[0, :]) # plt.plot(out[1,:]) #plt.plot(out[2,:]) plt.plot(temps[0, :]) #plt.plot(temps[1,:]) #plt.plot(temps[2,:]) plt.show() import pdb pdb.set_trace() result = least_squares(simulate_numba, constants, args=(temps, heaters, ambient, dt, False), bounds=([0] * 30, [np.inf] * 30)) #x, cov = leastsq(simulate_numba, constants, args=(temps, heaters, ambient, dt, False), maxfev = 1000000000) import pdb pdb.set_trace()
def _extrapolation(self, enable_numba=True, **kwargs): """ Override the primary execution method from the extrapolation class. The process is to extrapolate the potential (scalar) field (phi) and then use numerical differentiation (gradient) to find the vector field (Bxyz). """ if enable_numba: # Test that numba and the numba'ed extrpolator can be imported try: import numba from potential_field_extrapolator_numba import phi_extrapolation_numba except ImportError: enable_numba = False phi = self._extrapolate_phi(enable_numba, **kwargs) if enable_numba: from numba.decorators import autojit determine_vec = autojit(self._determine_vec) else: determine_vec = self._determine_vec npmVecSpace = np.zeros(list(phi.shape)+[3]) # in Order XYZC (C = component directions) Bxyz = determine_vec(phi, 1, npmVecSpace) return Map3D(Bxyz, self.meta, xrange=self.xrange, yrange=self.yrange, zrange=self.zrange)
def video_flow_FB_getpeople(): cam = cv2.VideoCapture(0) ret, frame1 = cam.read() prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY) while(1): ret, frame2 = cam.read() next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY) flow = cv2.calcOpticalFlowFarneback(prvs,next, 0.5, 3, 15, 3, 5, 1.2, 0) imFilter = cv2.GaussianBlur(next,(5,5),1.5) bg_numba = autojit(get_background) bg = bg_numba(imFilter,flow) (cnts, _) = cv2.findContours(bg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in cnts: if cv2.contourArea(c) < 8000: continue (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame2, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow('flow', frame2) k = cv2.waitKey(30) & 0xff if k == 27: cam.release() cv2.destroyAllWindows() break prvs = next
def _extrapolation(self, enable_numba=True, **kwargs): """ Override the primary execution method from the extrapolation class. The process is to extrapolate the potential (scalar) field (phi) and then use numerical differentiation (gradient) to find the vector field (Bxyz). """ if enable_numba: # Test that numba and the numba'ed extrpolator can be imported try: import numba from potential_field_extrapolator_numba import phi_extrapolation_numba except ImportError: enable_numba = False phi = self._extrapolate_phi(enable_numba, **kwargs) if enable_numba: from numba.decorators import autojit determine_vec = autojit(self._determine_vec) else: determine_vec = self._determine_vec npmVecSpace = np.zeros(list(phi.shape) + [3]) # in Order XYZC (C = component directions) Bxyz = determine_vec(phi, 1, npmVecSpace) return Map3D(Bxyz, self.meta, xrange=self.xrange, yrange=self.yrange, zrange=self.zrange)
def hysteresis(src,upper,low): src -= (src==255).astype(np.uint8) s = src.shape hysterConnect_numba = autojit(hysterConnect) for x in range(1,s[0]): for y in range(1,s[1]): if src[x,y] >= upper and src[x,y] != 255: src[x,y] = 255 hysterConnect_numba(src,s,x,y,low) # return src return src*(src==255)
def getNormalized(self): ret = ElecpySession (self.path) def pixelwise_normalize(X): L, M, N = X.shape ret = np.zeros_like(X) for i in range(M): for j in range(N): ts = X[:,i,j] ret[:, i, j] = (ts-ts.min())/(abs(ts.max() - ts.min())+1.0e-30) return ret _func = autojit(pixelwise_normalize) for key in self.data.keys(): ret.data[key] = _func(self.data[key]) return ret
def getNormalized(self): ret = Loader (self.path) def pixelwise_normalize(X): L, M, N = X.shape ret = np.zeros_like(X) for i in range(M): for j in range(N): ts = X[:,i,j] ret[:, i, j] = (ts-ts.min())/(abs(ts.max() - ts.min())+1.0e-30) return ret _func = autojit(pixelwise_normalize) for key in self.data.keys(): ret.data[key] = _func(self.data[key]) return ret
def wrapper_sim(xdata, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29): constants = [0] * 30 constants[0] = c0 constants[1] = c1 constants[2] = c2 constants[3] = c3 constants[4] = c4 constants[5] = c5 constants[6] = c6 constants[7] = c7 constants[8] = c8 constants[9] = c9 constants[10] = c10 constants[11] = c11 constants[12] = c12 constants[13] = c13 constants[14] = c14 constants[15] = c15 constants[16] = c16 constants[17] = c17 constants[18] = c18 constants[19] = c19 constants[20] = c20 constants[21] = c21 constants[22] = c22 constants[23] = c23 constants[24] = c24 constants[25] = c25 constants[26] = c26 constants[27] = c27 constants[28] = c28 constants[29] = c29 dt = 0.35 #constants[30] = c30 #constants[31] = c31 temps = xdata[0:3, :] heaters = xdata[3:9, :] ambient = xdata[9:24, :] simulate_numba = autojit(simulate) return simulate_numba(constants, temps, heaters, ambient, dt, True)
def nms(src,x_,y_,threshold=50): # direct = sc.arctan(x_/y_) s = src.shape get_coordinates_numba = autojit(get_coordinates) for x in range(1,s[0]-1): for y in range(1,s[1]-1): if src[x,y] <= threshold: continue if y_[x,y] == 0: if x_[x,y] == 0: angle = -math.pi/2.0 else: angle = math.pi/2.0 else: angle = math.atan(x_[x,y]/y_[x,y]) coords = get_coordinates_numba(angle) M1 = y_[x,y]*src[x+coords[0],y+coords[1]] + (x_[x,y]-y_[x,y])*src[x+coords[2],y+coords[3]] coords = get_coordinates_numba(angle+math.pi) M2 = y_[x,y]*src[x+coords[0],y+coords[1]] + (x_[x,y]-y_[x,y])*src[x+coords[2],y+coords[3]] M = src[x,y]*x_[x,y] if not ((M >= M1 and M >= M2) or (M <= M1 and M <= M2)): src[x,y] = 0 return src
numba_apply(split_by_pattern, dataset) def cos_sim_matrix(arr): N = arr.shape[0] dist = np.zeros((N, N)) for i, row in enumerate(arr): for j, col in enumerate(arr): dot_product = np.dot(row, col) norm_a = np.linalg.norm(row) norm_b = np.linalg.norm(col) dist[i][j] = dot_product / (norm_a * norm_b) return dist cos_sim_matrix_numba = autojit(cos_sim_matrix) def matrix_multiplication(m1, m2): return m1 * m2 matrix_multiplication_numba = autojit(matrix_multiplication) def matrix_multiplication_loops(m1, m2): M = len(m1) N = len(m1[0]) Q = len(m2[0]) res = np.zeros((M, Q)) sum = 0
entropy -= -dec / block_size * np.log2(dec / block_size) if dec > 1: entropy += -(dec - 1) / block_size * \ np.log2((dec - 1) / block_size) if inc > 0: entropy -= -inc / block_size * np.log2(inc / block_size) entropy += - (inc + 1) / block_size * np.log2((inc + 1) / block_size) if i % step == 0: ent[i / step] = (entropy) H_numba = autojit(H1, nopython=True) def get_entropy_features(byte_data): corr = {str(key): key for key in range(10)} corrl = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, '?': 16} corr.update(corrl) block_size = 10000 step = 100 text = byte_data #name = filename.split('/')[-1].split('.')[0] #with gzip.open(filename, 'r') as f: # text = f.read()
import os import numpy as np from scipy import stats from copy import deepcopy import matplotlib.pyplot as plt plt.style.use( os.path.join( os.path.dirname(os.path.realpath(__file__)), '../mpl_styles/spykes.mplstyle') ) from . import utils from numba.decorators import autojit slow_exp = autojit(utils.slow_exp_python) grad_slow_exp = autojit(utils.grad_slow_exp_python) class NeuroPop(object): """ This class implements several conveniences for plotting, fitting and decoding from population tuning curves We allow the fitting of two classes of parametric tuning curves. Parameters ---------- tunemodel: str, can be either 'gvm' or 'glm' tunemodel = 'gvm' Generalized von Mises model Amirikan & Georgopulos (2000):
import numpy import numpy as np import logging logging.basicConfig(level=logging.DEBUG) # ______________________________________________________________________ def _simple_func(arg): if arg > 0.: result = 22. else: result = 42. return result simple_func = decorators.autojit(backend='ast')(_simple_func) def _for_loop(start, stop, inc): acc = 0 for value in range(start, stop, inc): acc += value print(value) return acc for_loop = decorators.autojit(backend='ast')(_for_loop) def arange(): a = numpy.arange(10) b = numpy.arange(10, dtype=numpy.double) return a, b
def binary_search(a, x): lo = 0 hi = a.shape[0] while lo < hi: mid = (lo + hi) // 2 midval = a[mid] if midval < x: lo = mid + 1 elif midval > x: hi = mid else: return mid return -1 binary_search_numba = autojit(binary_search, nopython=True) def extract(all_elems_codes, out, askii_list): MAX_STR = out.shape[0] cur_num_str = 0 i = all_elems_codes.shape[0] - 1 state = 0 cur_end = -1 min_length = 4 count_one = 0 count_two = 0
def ridge_sgd_vectorized(X, y, w, alpha, perm): for t, i in enumerate(perm): i = perm[t] gamma = 1. / (1 + alpha * t) # regularization step w *= (1. - gamma * alpha) # loss step z = np.dot(w, X[i, :]) w += gamma * X[i, :] * (z - y[i]) ridge_sgd_numba = autojit(ridge_sgd_naive) def create_data(N=10000, D=1000): X = np.random.randn(N, D) w_true = np.sin(2 * np.pi * np.linspace(0, 1, D)) y = np.dot(X, w_true) return X, y, w_true def run_benchmark(): X, y, w_true = create_data()
value = calcuBasis2Haar(image, has_trans, x, y, w, h) elif haar_type == 1: value = calcuGap3Haar(image, has_trans, x, y, w, h) else: value = calcuSquare4Haar(image, x, y, w, h) # print "%d %d %d %d %d %d %f %d %d" %(haar_type, has_trans, x, y, w, h, a, thre, best_p) # print "%d" %value if best_p: if value <= thre: res_ = res_ + a else: if value > thre: res_ = res_ + a # print "!%f %f" %(res_, a_sum) if res_ < 0.5*a_sum*fade_param: return False return True fastCheckByCascade = autojit(fastCheckByCascade) def covertCascade(cascade): new_cascade = [] for layer in cascade: new_layer = [] for ada in layer[0]: (haar_type, has_trans, x, y, w, h) = haar_map[ada[2]] new_layer.append((haar_type, has_trans, x, y, w, h, ada[0], ada[1], ada[3])) new_cascade.append((new_layer, layer[1])) return new_cascade def scaledCascade(cascade, scale_factor): new_cascade = [] for layer in cascade: new_layer = []
@author: Avinash """ import numpy as np from numpy import * import numpy from math import * import ev_charge_schedule as ev #import ev_charge_schedule.static as func1 #import ev_charge_schedule.dynamic as func2 import time #from numba import double from numba.decorators import autojit func1=ev.dynamic func=autojit(func1) mode=0 runs=0 maxiter=500 F=0.8 # Mutation Factor between 0 to 2 CR=0.9 # Probability 1. Put 0.9 if parameters are dependent while 0.2 if parameters are independent(seperable) N=40 D=24 N_veh=50 value=numpy.zeros(shape=(6,N_veh)) counterk1=0 for k1 in [8.8]: d=numpy.zeros(shape=(N_veh,24)) p_sol=numpy.zeros(shape=(N_veh,24))
for value_1 in range(stop): acc += value_0 * value_1 return acc # ______________________________________________________________________ def _for_loop_fn_3 (stop): acc = 0 for i in range(stop): for j in range(stop): for k in range(stop): for l in range(stop): acc += 1 return acc for_loop_fn_0 = autojit(backend='ast')(_for_loop_fn_0) for_loop_fn_1 = autojit(backend='ast')(_for_loop_fn_1) for_loop_fn_2 = autojit(backend='ast')(_for_loop_fn_2) for_loop_fn_3 = autojit(backend='ast')(_for_loop_fn_3) # ______________________________________________________________________ class TestForLoop(unittest.TestCase): # @unittest.skipUnless(__debug__, "Requires implementation of iteration " # "over arrays.") def test_compiled_for_loop_fn_0(self): for dtype in (np.float32, np.float64, np.int32, np.int64): test_data = np.arange(10, dtype=dtype) result = for_loop_fn_0(test_data) self.assertEqual(result, 45) self.assertEqual(result, _for_loop_fn_0(test_data))
# zeroCross(image) # print "=> Gaussian without numba spent: %s s" % t.secs # with Timer() as t: # zeroCross_numba(image) # print "=> Gaussian with numba spent: %s s" % t.secs return #inputfile='nevermore.png' inputfile='lena_std.png' plt.gray() image = readImage(inputfile) gt = createGaussianTemplate(11,2) imageFilter_numba = autojit(imageFilter) zeroCross_numba = autojit(zeroCross) demoNumbaSpeedup(image) #print 'comparison' #compareDifferentTypes(image) #compareParametersOfloG(image) #print 'shape of template of LoG in frequency domain' #show3DforloG() #demoImageFourierForm(image,71,True) #demoLowHighpassFilter(image) #print 'process of fourier for LoG' #demoProcessOfFourier(image,createLoGTemplate(11,2)) #demoSimpleButtonProblem()
from numba.decorators import autojit import numpy as np def _matmulcore(A, B, C): m, n = A.shape n, p = B.shape for i in range(m): for j in range(p): C[i, j] = 0 for k in range(n): C[i, j] += A[i, k] * B[k, j] matmulcore = autojit(backend="ast")(_matmulcore) class TestASTArrays(unittest.TestCase): def test_numba(self): A = np.arange(16, dtype=np.float32).reshape(4, 4) B = np.arange(16, dtype=np.float32).reshape(4, 4) C = np.zeros(16, dtype=np.float32).reshape(4, 4) Gold = C.copy() _matmulcore(A, B, Gold) # oracle matmulcore(A, B, C) self.assertTrue(np.all(C == Gold))
from numba.decorators import jit, autojit def find_index(string, char): index = -1 for count in range(len(string)): if string[count] == char: index = count break return index find_index = autojit(find_index) def string_split(string, key): i = find_index(string, key) return string[:i], string[i + 1:] string_split = autojit(string_split) def to_time(string): m, s = string_split(string, ':') return float(m) * 60 + float(s) to_time = autojit(to_time) def parse_sentence(line): line = str(line) # print(line) end_p = find_index(line, ']') if end_p == -1: return '' time = line[find_index(line, '[') + 1:end_p] start, end = string_split(time, ' ') start_time = to_time(start)
def getHaarFeatureNum((minwidth, minheight, stepwidth, stepheight, stridex, stridey), window_size): num = 0 window_size_l = window_size+1 for w in range(minwidth,window_size_l,stepwidth): for h in range(minheight,window_size_l,stepheight): for x in range(w,window_size_l,stridex): for y in range(h,window_size_l,stridey): num = num+1 return num def calcuRectangle(ii, x_end, y_end, w, h): return ii[x_end,y_end] + ii[x_end-w,y_end-h] - ii[x_end-w,y_end] - ii[x_end,y_end-h] calcuRectangle = autojit(calcuRectangle) def calcuHaarFeature(ii, list_haars, window_size): list_ = [] window_size_l = window_size+1 for i in range(len(list_haars)): # haar = list_haars[i] # minwidth = haar.minwidth # minheight = haar.minheight # stepwidth = haar.stepwidth # stepheight = haar.stepheight # stridex = haar.stridex # stridey = haar.stridey minwidth = list_haars[i][0] minheight = list_haars[i][1]
#This is python code def f_python(n): s = 0 for i in range( n): s += i/2.0 return s #This is numba version from numba import double from numba.decorators import jit, autojit #from numba.decorators import autojit f_numba = autojit(f_python)
# ______________________________________________________________________ def _for_loop_fn_3(stop): acc = 0 for i in range(stop): for j in range(stop): for k in range(stop): for l in range(stop): acc += 1 return acc for_loop_fn_0 = autojit(backend='ast')(_for_loop_fn_0) for_loop_fn_1 = autojit(backend='ast')(_for_loop_fn_1) for_loop_fn_2 = autojit(backend='ast')(_for_loop_fn_2) for_loop_fn_3 = autojit(backend='ast')(_for_loop_fn_3) # ______________________________________________________________________ class TestForLoop(unittest.TestCase): # @unittest.skipUnless(__debug__, "Requires implementation of iteration " # "over arrays.") def test_compiled_for_loop_fn_0(self): for dtype in (np.float32, np.float64, np.int32, np.int64): test_data = np.arange(10, dtype=dtype) result = for_loop_fn_0(test_data) self.assertEqual(result, 45)
class ASTTestCase(unittest.TestCase): jit = staticmethod( lambda *args, **kw: jit_(*args, **dict(kw, backend='ast'))) backend = 'ast' autojit = staticmethod(autojit(backend=backend))
def _get_ndarray_shape(ndarr): return ndarr.shape def _get_ndarray_data(ndarr): return ndarr.data def _get_ndarray_2_shape_unpack_0(ndarr): dim0, _ = ndarr.shape return dim0 def _get_ndarray_2_shape_unpack_1(ndarr): _, dim1 = ndarr.shape return dim1 get_ndarray_ndim = autojit(backend='ast')(_get_ndarray_ndim) get_ndarray_shape = autojit(backend='ast')(_get_ndarray_shape) get_ndarray_data = autojit(backend='ast')(_get_ndarray_data) get_ndarray_2_shape_unpack_0 = autojit(backend='ast')(_get_ndarray_2_shape_unpack_0) get_ndarray_2_shape_unpack_1 = autojit(backend='ast')(_get_ndarray_2_shape_unpack_1) # ______________________________________________________________________ class TestGetattr(unittest.TestCase): def test_getattr_ndim(self): args = [ np.empty((2,)), np.empty((2, 2)), ] for arg in args:
from numba import * from numba.decorators import autojit import numpy as np def _matmulcore(A, B, C): m, n = A.shape n, p = B.shape for i in range(m): for j in range(p): C[i, j] = 0 for k in range(n): C[i, j] += A[i, k] * B[k, j] matmulcore = autojit(backend='ast')(_matmulcore) class TestASTArrays(unittest.TestCase): def test_numba(self): A = np.arange(16, dtype=np.float32).reshape(4, 4) B = np.arange(16, dtype=np.float32).reshape(4, 4) C = np.zeros(16, dtype=np.float32).reshape(4, 4) Gold = C.copy() _matmulcore(A, B, Gold) # oracle matmulcore(A, B, C) self.assertTrue(np.all(C == Gold)) if __name__ == '__main__':
time = 0; cell1 = HCVHepatocyte(1, None, 'Virus', time, 'Latent') #Create function to randomly select one cell to infect def CreateLatent(cellHandle, newID, state_idx, simTime): if state_idx in [0,1]: newLatent = cellHandle.InfectCell(newID, simTime, 'Latent') return newLatent elif state_idx in [2,3]: newLatent = cellHandle.InfectCell(newID, simTime, 'LatentL') return newLatent else: print("Error: State is not an infecting transition") CreateLatentNumba = autojit(CreateLatent) #Create function to Kill Infected cell def KillInfected(cellHandle, time): cellHandle.tDead = time if cellHandle.cellType == 'Infected': cellHandle.cellType = 'Dead' elif cellHandle.cellType == 'InfectedL': cellHandle.cellType = 'DeadL' else: print("Error: Cannot kill uninfected cell") return cellHandle KillInfected = autojit(KillInfected) #Create function to move latent to infectious def LatentInfectious(cellHandle, time): cellHandle.tInf = time if cellHandle.cellType == 'Latent':
entropy -= -dec / block_size * np.log2(dec / block_size) if dec > 1: entropy += -(dec - 1) / block_size * \ np.log2((dec - 1) / block_size) if inc > 0: entropy -= -inc / block_size * np.log2(inc / block_size) entropy += - (inc + 1) / block_size * np.log2((inc + 1) / block_size) if i % step == 0: ent[i // step] = (entropy) H_numba = autojit(H1, nopython=True) def get_entropy_features(byte_data): corr = {str(key): key for key in range(10)} corrl = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, '?': 16} corr.update(corrl) block_size = 10000 step = 100 text = byte_data #name = filename.split('/')[-1].split('.')[0] #with gzip.open(filename, 'r') as f: # text = f.read()
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) # <codecell> %%px0anaconda from numba import double from numba.decorators import jit, autojit pairwise_numba = autojit(pairwise_python) %timeit pairwise_numba(X) # <codecell> import cinefile_datatypes # <codecell> # size of image of 10 bit pixels in bytes imagesize = 512 * 512 * 10 / 8 print imagesize # <codecell>
class ByteCodeTestCase(unittest.TestCase): jit = staticmethod(jit_) backend = 'bytecode' autojit = staticmethod(autojit(backend=backend))
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 pairwise_numba = autojit(pairwise_python) #python start = time.time() pairwise_python(X) end = time.time() print(start - end) #numpy start = time.time() pairwise_numpy(X)
def _get_ndarray_data(ndarr): return ndarr.data def _get_ndarray_2_shape_unpack_0(ndarr): dim0, _ = ndarr.shape return dim0 def _get_ndarray_2_shape_unpack_1(ndarr): _, dim1 = ndarr.shape return dim1 get_ndarray_ndim = autojit(backend='ast')(_get_ndarray_ndim) get_ndarray_shape = autojit(backend='ast')(_get_ndarray_shape) get_ndarray_data = autojit(backend='ast')(_get_ndarray_data) get_ndarray_2_shape_unpack_0 = autojit( backend='ast')(_get_ndarray_2_shape_unpack_0) get_ndarray_2_shape_unpack_1 = autojit( backend='ast')(_get_ndarray_2_shape_unpack_1) # ______________________________________________________________________ class TestGetattr(unittest.TestCase): def test_getattr_ndim(self): args = [ np.empty((2, )), np.empty((2, 2)),
t3 = '%.2fs' % t.secs with Timer() as t: N4,V4 = flowCorrZNCC_speedup_numba(im1,im2,d,w) t4 = '%.2fs' % t.secs drawFigures(['CC '+t1,np.sqrt(N1**2+V1**2),'NCC '+t2,np.sqrt(N2**2+V2**2),\ 'ZNCC '+t3,np.sqrt(N3**2+V3**2),'ZNCC (speedup) '+t4,np.sqrt(N4**2+V4**2)]) return def demoOpencvOpticalFlow(im1, im2): flow = cv2.calcOpticalFlowFarneback(im1, im2, 0.5, 3, 11, 3, 5, 1.2, 0) N = flow[:,:,0] V = flow[:,:,1] return N,V plt.gray() flowCorrSAD_numba = autojit(flowCorrSAD) flowCorrZSAD_numba = autojit(flowCorrZSAD) flowCorrSSD_numba = autojit(flowCorrSSD) flowCorrZSSD_numba = autojit(flowCorrZSSD) flowCorrCC_numba = autojit(flowCorrCC) flowCorrNCC_numba = autojit(flowCorrNCC) flowCorrZNCC_numba = autojit(flowCorrZNCC) flowCorrZNCC_speedup_numba = autojit(flowCorrZNCC_speedup) #simpleDemo() im1,image1 = readImage('ffa.png') im2,image2 = readImage('ffb.png') sigma = 1.5
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 pairwise_numba = autojit(pairwise_python) #python start = time.time() pairwise_python(X) end = time.time() print(start-end) #numpy start = time.time()
show = cv2.applyColorMap(imgTransToGrayscale_numba(show), cv2.COLORMAP_HOT) cv2.imshow("Heat FLow", show) scale_factor = 3 lambo1 = 1.0 # regional statistics, interior lambo2 = 1.0 # regional statistics, exterior k = 0.2 q = 100000000 # iter_max = 2000 iter_step = 30 free_threshold = 4 template = -createLaplacianTemplate(3, False) imgTransToGrayscale_numba = autojit(imgTransToGrayscale) posList = [] def output_raw(img, posList): color_ = (0, 0, 0) shape = (gray.shape[1] * scale_factor, gray.shape[0] * scale_factor) show = cv2.resize(img, shape, interpolation=cv2.INTER_CUBIC) for pos in posList: cv2.circle(show, (pos[1] * scale_factor, pos[0] * scale_factor), 5, color_, -1) cv2.imshow("Heat FLow", show) # mouse callback function def heat_injection(event, x, y, flags, param):
def binary_search(a, x): lo = 0 hi = a.shape[0] while lo < hi: mid = (lo + hi) // 2 midval = a[mid] if midval < x: lo = mid + 1 elif midval > x: hi = mid else: return mid return -1 binary_search_numba = autojit(binary_search, nopython=True) def extract(all_elems_codes, out, ascii_list): MAX_STR = out.shape[0] cur_num_str = 0 i = all_elems_codes.shape[0] - 1 state = 0 cur_end = -1 min_length = 4 count_one = 0 count_two = 0
import unittest import numpy import logging logging.basicConfig(level=logging.DEBUG) # ______________________________________________________________________ def _simple_func(arg): if arg > 0.: result = 22. else: result = 42. return result simple_func = decorators.autojit(backend='ast')(_simple_func) def _for_loop(start, stop, inc): acc = 0 for value in range(start, stop, inc): acc += value return acc for_loop = decorators.autojit(backend='ast')(_for_loop) def arange(): a = numpy.arange(10) b = numpy.arange(10, dtype=numpy.double) return a, b def empty_like(a):
test = image # draw(test) test,y_,x_ = sobel(test) # for (x,y),n in np.ndenumerate(direct): # direct[x,y] = math.atan(direct[x,y]) draw(test) # draw(nms(test,direct)) # draw(hysteresis_numba(test,120,100)) return test plt.gray() anisotropic_numba = autojit(anisotropic) imageFourierFilter_numba = autojit(imageFourierFilter) nms_numba = autojit(nms) hysteresis_numba = autojit(hysteresis) heatflow_numba = autojit(heatflow) #test = basic_test_demo() #image = readImage('ball0.png') #test,x_,y_ = sobel(image) #draw(test) #direct = sc.arctan(x_/y_) #test = nms_numba(test.copy(),direct,x_,y_) #draw(test) #test = hysteresis_numba(test.copy(),100,40) #draw(test)