我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numba.jit()。
def _ecdf_dots(data): """ Compute `x` and `y` values for plotting an ECDF. Parameters ---------- data : array_like One-dimensional array of data to be plotted as an ECDF. Returns ------- x : array `x` values for plotting y : array `y` values for plotting """ return np.sort(data), np.arange(1, len(data)+1) / len(data) # @numba.jit(nopython=True)
def swap_random(a, b): """ Randomly swap entries in two arrays. Parameters ---------- a : array_like 1D array of entries to be swapped. b : array_like 1D array of entries to be swapped. Must have the same lengths as `a`. Returns ------- a_out : ndarray, dtype float Array with random entries swapped. b_out : ndarray, dtype float Array with random entries swapped. """ a, b = _convert_two_data(a, b) return _swap_random(a, b) # @numba.jit(nopython=True)
def _allequal(x, rtol=1e-5, atol=1e-14): """ Determine if all entries in an array are equal. Parameters ---------- x : ndarray Array to test. Returns ------- output : bool True is all entries in the array are equal, False otherwise. """ if len(x) == 1: return True for a in x[1:]: if np.abs(a-x[0]) > (atol + rtol * np.abs(a)): return False return True # @numba.jit(nopython=True)
def _make_one_arg_numba_func(func): """ Make a Numba'd version of a function that takes one positional argument. Parameters ---------- func : function Function with call signature `func(x, *args)`. Returns ------- output : Numba'd function A Numba'd version of the functon Notes ----- .. If the function is Numba'able in nopython mode, it will compile in that way. Otherwise, falls back to object mode. """ # @numba.jit def f(x, args=()): return func(x, *args) return f
def _make_two_arg_numba_func(func): """ Make a Numba'd version of a function that takes two positional arguments. Parameters ---------- func : function Function with call signature `func(x, y, *args)`. Returns ------- output : Numba'd function A Numba'd version of the functon Notes ----- .. If the function is Numba'able in nopython mode, it will compile in that way. Otherwise, falls back to object mode. """ # @numba.jit def f(x, y, args=()): return func(x, y, *args) return f
def _make_one_arg_numba_func(func): """ Make a Numba'd version of a function that takes one positional argument. Parameters ---------- func : function Function with call signature `func(x, *args)`. Returns ------- output : Numba'd function A Numba'd version of the functon Notes ----- .. If the function is Numba'able in nopython mode, it will compile in that way. Otherwise, falls back to object mode. """ @numba.jit def f(x, args=()): return func(x, *args) return f
def _make_two_arg_numba_func(func): """ Make a Numba'd version of a function that takes two positional arguments. Parameters ---------- func : function Function with call signature `func(x, y, *args)`. Returns ------- output : Numba'd function A Numba'd version of the functon Notes ----- .. If the function is Numba'able in nopython mode, it will compile in that way. Otherwise, falls back to object mode. """ @numba.jit def f(x, y, args=()): return func(x, y, *args) return f
def _make_rng_numba_func(func): """ Make a Numba'd version of a function to draw random numbers. Parameters ---------- func : function Function with call signature `func(*args, size=1)`. Returns ------- output : Numba'd function A Numba'd version of the functon Notes ----- .. If the function is Numba'able in nopython mode, it will compile in that way. Otherwise, falls back to object mode. """ @numba.jit def f(args, size=1): all_args = args + (size,) return func(*all_args) return f
def azimuth(_lAz_data): _inc = _lAz_data[0] _lat = _lAz_data[1] velocity_eq = _lAz_data[2] @jit(nopython=True) def _az_calc(): inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1)) _VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat)) _VYRot = _lAz_data[3] * np.cos(inert_az) return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi))) _az = _az_calc() if _lAz_data[4] == "Ascending": return _az if _lAz_data[4] == "Descending": if _az <= 90: return 180 - _az elif _az >= 270: return 540 - _az
def insertion_pitch(self): _circ_dv = self.circ_dv() _t_ap_dv = self.target_apoapsis_speed_dv() _m = np.rad2deg(self.mean_anomaly()) _burn_time = self.maneuver_burn_time(self.circ_dv()) @jit(nopython=True) def pitch_calcs_low(): return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12))) @jit(nopython=True) def pitch_calcs_high(): return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180) if self.parking_orbit_alt <= 300000: return pitch_calcs_low() else: return pitch_calcs_high()
def insertion_pitch(self): _circ_dv = self.circ_dv() _t_ap_dv = self.target_apoapsis_speed_dv() _m = np.rad2deg(self.mean_anomaly()) _burn_time = self.maneuver_burn_time(self.circ_dv()) @jit(nopython=True) def pitch_calcs_low(): return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12))) @jit(nopython=True) def pitch_calcs_high(): return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180) if self.target_orbit_alt <= 250000: return pitch_calcs_low() else: return pitch_calcs_high()
def test_jit(self): a = numpy.arange(16, dtype=numpy.float32) b = numpy.arange(16, dtype=numpy.float32) p = profile.Profile() cfunc = jit(nopython=True)(dot) p.enable() cfunc(a, b) p.disable() stats = pstats.Stats(p).strip_dirs() shp = str(a.shape) expected = ('test_profiler.py', 6, 'dot(a:ndarray(dtype=float32, shape={s}), '.format(s=shp)+ 'b:ndarray(dtype=float32, shape={s}))'.format(s=shp) ) assert expected in stats.stats
def encode_jit(self, nr_samples, lengths, out, positions): """ out[samples, reads, bin_nodes+tria_nodes] Need to use this function to call the jit compiled function, as class support via numba is disabled sice 0.12""" if self.double_range: encode_double_triangles_jit(n_binary_bits=np.int64(self.n_binary_bits), n_inputnodes=np.int64(self.data_nodes), tria_nodes_end=self.data_nodes-self.n_binary_bits-1, #this is the last tria index -> nr nodes - 1 node_range=np.float64(self.node_range), nr_samples=np.int64(nr_samples), lengths=np.uint32(lengths), out=np.float32(out), positions=np.uint32(positions)) else: encode_triangles_jit(n_binary_bits=np.int64(self.n_binary_bits), n_inputnodes=np.int64(self.data_nodes), node_range=np.float64(self.node_range), nr_samples=np.int64(nr_samples), lengths=np.uint32(lengths), out=np.float32(out), positions=np.uint32(positions))
def euclidean(bb_test_, bb_gt_): """ Computes similarity using euclidean distance between two bboxes in the form [x, y, z, s, r, yaw] using 1/ (1 + euclidean_dist) """ x1, y1, z1, s1, r1, yaw1 = get_bbox(bb_test_) x2, y2, z2, s2, r2, yaw2 = get_bbox(bb_gt_) # o = (np.sum(squared_diff(i,j) for (i,j) in [(x1, x2), (y1, y2), (yaw1, yaw2)])) # this is not jit compatible. resort to using for loop: output = 0. for (i, j) in [(x1, x2), (y1, y2), (z1, z2), (yaw1, yaw2), (s1, s2), (r1, r2)]: output += squared_diff(i, j) output = 1./(1. + (output ** (1 / 2.))) # print('distance {}'.format(o)) return(output)
def convolve_laplacien2_gu(image, index, out_image): nx, ny = image.shape for j in range(1,ny-1): out_image[j-1] = np.abs(4*image[index[0],j]-image[index[0]-1,j]-image[index[0]+1,j] -image[index[0],j-1]-image[index[0],j+1]) #@numba.guvectorize(['(float64[:,:], int64[:], int64[:], float64[:])'], '(nx, ny),(),()->()', target='parallel', nopython=True) #def convolve_laplacien2_gu(image, i, j, out_image): # nx, ny = image.shape # out_image[0] = np.abs(4*image[i[0],j[0]]-image[i[0]-1,j[0]]-image[i[0]+1,j[0]] # -image[i[0],j[0]-1]-image[i[0],j[0]+1]) #@numba.jit #def convolve_laplacien2(image): # height, width = image.shape # out_image = np.empty((height-2,width-2)) # i = np.arange(1, height-1)[:, np.newaxis] # j = np.arange(1, width-1)[np.newaxis, :] # convolve_laplacien2_gu(image, i, j, out_image) # # On renormalise l'image : # valmax = np.max(out_image) # valmax = max(1.,valmax)+1.E-9 # out_image *= 1./valmax # return out_image
def compileToNative(loopFunction, inputs): numbaSizeType = numba.from_dtype(numpy.dtype(sizeType))[:] sig = [] for param in loopFunction.parameters: if isinstance(param, Countdown): sig.append(numbaSizeType) elif isinstance(param, (SizeArray, OutSizeArray)): sig.append(numbaSizeType) elif isinstance(param, (DataArray, OutDataArray)): sig.append(numba.from_dtype(numpy.dtype(param.dataType))[:]) else: assert False, "unexpected type: {0}".format(param) sig = tuple(sig) return numba.jit([sig], nopython=True)(loopFunction.fcn)
def _draw_bs_reps_mean(data, size=1): """ Generate bootstrap replicates of the mean out of `data`. Parameters ---------- data : array_like One-dimensional array of data. size : int, default 1 Number of bootstrap replicates to generate. Returns ------- output : float Bootstrap replicates of the mean computed from `data`. """ # Set up output array bs_reps = np.empty(size) # Draw replicates n = len(data) for i in range(size): bs_reps[i] = np.mean(np.random.choice(data, size=n)) return bs_reps # @numba.jit(nopython=True)
def draw_bs_pairs_linreg(x, y, size=1): """ Perform pairs bootstrap for linear regression. Parameters ---------- x : array_like x-values of data. y : array_like y-values of data. size : int, default 1 Number of pairs bootstrap replicates to draw. Returns ------- slope_reps : ndarray Pairs bootstrap replicates of the slope. intercept_reps : ndarray Pairs bootstrap replicates of the intercept. Notes ----- .. Entries where either `x` or `y` has a nan are ignored. .. It is possible that a pairs bootstrap sample has the same pair over and over again. In this case, a linear regression cannot be computed. The pairs bootstrap replicate in this instance is NaN. """ x, y = _convert_two_data(x, y, inf_ok=False, min_len=2) if np.isclose(x, y).all(): raise RuntimeError('All x and y values are equal, cannot do regression') return _draw_bs_pairs_linreg(x, y, size=size) # @numba.jit(nopython=True)
def permutation_sample(data_1, data_2): """ Generate a permutation sample from two data sets. Specifically, concatenate `data_1` and `data_2`, scramble the order of the concatenated array, and then return the first len(data_1) entries and the last len(data_2) entries. Parameters ---------- data_1 : array_like One-dimensional array of data. data_2 : array_like One-dimensional array of data. Returns ------- out_1 : ndarray, same shape as `data_1` Permutation sample corresponding to `data_1`. out_2 : ndarray, same shape as `data_2` Permutation sample corresponding to `data_2`. """ data_1 = _convert_data(data_1) data_2 = _convert_data(data_2) return _permutation_sample(data_1, data_2) # @numba.jit(nopython=True)
def _draw_perm_reps_diff_of_means(data_1, data_2, size=1): """ Generate permutation replicates of difference of means from `data_1` and `data_2` Parameters ---------- data_1 : array_like One-dimensional array of data. data_2 : array_like One-dimensional array of data. size : int, default 1 Number of pairs bootstrap replicates to draw. Returns ------- output : ndarray Permutation replicates. """ n1 = len(data_1) x = np.concatenate((data_1, data_2)) perm_reps = np.empty(size) for i in range(size): np.random.shuffle(x) perm_reps[i] = _diff_of_means(x[:n1], x[n1:]) return perm_reps # @numba.jit(nopython=True)
def studentized_diff_of_means(data_1, data_2): """ Studentized difference in means of two arrays. Parameters ---------- data_1 : array_like One-dimensional array of data. data_2 : array_like One-dimensional array of data. Returns ------- output : float Studentized difference of means. Notes ----- .. If the variance of both `data_1` and `data_2` is zero, returns np.nan. """ data_1 = _convert_data(data_1) data_2 = _convert_data(data_2) return _studentized_diff_of_means(data_1, data_2) # @numba.jit(nopython=True)
def pearson_r(data_1, data_2): """ Compute the Pearson correlation coefficient between two samples. Parameters ---------- data_1 : array_like One-dimensional array of data. data_2 : array_like One-dimensional array of data. Returns ------- output : float The Pearson correlation coefficient between `data_1` and `data_2`. Notes ----- .. Only entries where both `data_1` and `data_2` are not NaN are used. .. If the variance of `data_1` or `data_2` is zero, return NaN. """ x, y = _convert_two_data(data_1, data_2, inf_ok=False, min_len=2) return _pearson_r(x, y) # @numba.jit(nopython=True)
def _make_rng_numba_func(func): """ Make a Numba'd version of a function to draw random numbers. Parameters ---------- func : function Function with call signature `func(*args, size=1)`. Returns ------- output : Numba'd function A Numba'd version of the functon Notes ----- .. If the function is Numba'able in nopython mode, it will compile in that way. Otherwise, falls back to object mode. """ # @numba.jit def f(args, size=1): all_args = args + (size,) return func(*all_args) return f # @numba.jit(nopython=True)
def jit(signature_or_function=None, locals={}, target='cpu', cache=False, **options): if signature_or_function is None: def _jit(function): return function return _jit else: return signature_or_function
def histogram(x, xmin, xmax, histogram_out): nbins = histogram_out.shape[0] bin_width = (xmax - xmin) / nbins start = cuda.grid(1) stride = cuda.gridsize(1) for i in range(start, x.shape[0], stride): # note that calling a numba.jit function from CUDA automatically # compiles an equivalent CUDA device function! bin_number = compute_bin(x[i], nbins, xmin, xmax) if bin_number >= 0 and bin_number < histogram_out.shape[0]: cuda.atomic.add(histogram_out, bin_number, 1)
def gravity_pitch(self): _t_ap_dv = self.target_apoapsis_speed_dv() _speed = self.vessel_sur_speed() _circ_dv = self.circ_dv() @jit(nopython=True) def pitch_calcs(): _pitch = (90 - ((1 + (_circ_dv / 7400)) * np.sqrt(_speed))) + (_t_ap_dv / (2 - (_circ_dv / 7400))) return _pitch return pitch_calcs()
def insertion_pitch(self): _circ_dv = self.circ_dv() _t_ap_dv = self.target_apoapsis_speed_dv() _m = np.rad2deg(self.mean_anomaly()) _burn_time = self.maneuver_burn_time(self.circ_dv()) @jit(nopython=True) def pitch_calcs_low(): return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 6))) @jit(nopython=True) def pitch_calcs_high(): return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180) # if self.parking_orbit_alt <= 250000: return pitch_calcs_low() # else: return pitch_calcs_high() return pitch_calcs_high()
def gravity_pitch(self): _t_ap_dv = self.target_apoapsis_speed_dv() _speed = self.vessel_sur_speed() @jit(nopython=True) def pitch_calcs(): _pitch = (85 - (1.45 * np.sqrt(_speed))) + (_t_ap_dv / 2) return _pitch return pitch_calcs()
def jit(signature_or_function=None, **kwargs): if signature_or_function is None: return lambda x: x else: return signature_or_function
def jit(f): def inner(f, *args): return f(*args) return lambda *args: inner(f, *args)
def jit(signature_or_function=None, **options): from .compiler import add_hpat_stages # set nopython by default if 'nopython' not in options: options['nopython'] = True #options['parallel'] = True options['parallel'] = { 'comprehension': True, 'setitem': False, # FIXME: support parallel setitem 'reduction': True, 'numpy': True, 'stencil': True, 'fusion': True, } return numba.jit(signature_or_function, user_pipeline_funcs=[add_hpat_stages], **options)
def mult_abs_numpy(x, y): return np.abs(x*y) # @jit????????????
def render(self, path_to_frame): """This renders the frame at path_to_frame It will time only the rendering (no I/O), log the time, and write the output image to disk. """ input_img = util.read_img(path_to_frame) output_img = np.zeros(input_img.shape) # load module sys.path.append("../../apps/blur_one_stage") import blur_one_stage sys.path.remove("../../apps/blur_one_stage") # this is equivalent to using the @jit function decorator: jitted_func = numba.jit(blur_one_stage.gaussian_blur) t1 = time.time() jitted_func(input_img, output_img) t2 = time.time() print("Elapsed time: %f" % (t2 - t1)) output_filename = path_to_frame.split(os.sep)[-1] util.write_img(output_img, os.path.join(self.output_directory, output_filename)) # append timing data to log file: with open(self.log_filename, "a") as f: f.write("%s, %f, %f\n" % ( os.path.join(self.output_directory, output_filename), t2 - t1, 1./(t2 - t1)))
def rescale_image(X): """rescales the RGB values back to 0-255 in the image (useful after especially applying audio filters)""" I = X.copy() if (I.min() < 0 or I.max() > 255): I = (I - I.min()) * (255 / (I.max() - I.min())) I = I.round() return I.astype(np.uint8) # TODO: speed up with jit?
def encode_inplace_jit(self, nr_samples, lengths, out): """ Need to use this function to call the jit compiled function, as class support via numba is disabled sice 0.12""" encode_triangles_inplace_jit(n_binary_bits=self.n_binary_bits, ticker_steps=self.ticker_steps, n_inputnodes=self.n_inputnodes, node_range=self.node_range, nr_samples=nr_samples, lengths=lengths, out=out, out_uint=out.view(np.uint32))
def encode_inplace_jit(self, nr_samples, lengths, out): """ Need to use this function to call the jit compiled function, as class support via numba is disabled sice 0.12""" encode_overlapping_binary_inplace_jit(ticker_steps=self.ticker_steps, n_inputnodes=self.n_inputnodes, nr_samples=nr_samples, lengths=lengths, out=out, out_uint=out.view(np.uint32))
def encode_jit(self, nr_samples, lengths, out, positions): """ Need to use this function to call the jit compiled function, as class support via numba is disabled sice 0.12""" encode_overlapping_binary_jit(n_inputnodes=self.data_nodes, nr_samples=nr_samples, lengths=lengths, out=out, positions=np.uint32(positions))
def any(iterable): for element in iterable: return True return False # @jit(BoardState.class_type.instance_type(BoardState.class_type.instance_type), nopython=True)
def make_thunk(self, node, storage_map, compute_map, no_recycling): in1_type = getattr(numba, node.inputs[0].dtype) in2_type = getattr(numba, node.inputs[1].dtype) out_type = getattr(numba, node.outputs[0].dtype) self.numba_fct = numba.jit(out_type[:, :](in1_type[:, :], in2_type[:, :]))(convolve1d_2D_numpy) # self.numba_fct = convolve1d_2D_numpy return super(Convolve1d, self).make_thunk( node, storage_map, compute_map, no_recycling)
def make_thunk(self, node, storage_map, compute_map, no_recycling): in1_type = getattr(numba, node.inputs[0].dtype) in2_type = getattr(numba, node.inputs[1].dtype) out_type = getattr(numba, node.outputs[0].dtype) self.numba_fct = numba.jit(out_type[:,:,:,:](in1_type[:,:,:,:], in2_type[:,:,:,:]))(convolve1d_4D_numpy) # self.numba_fct = convolve1d_4D_numpy return super(Convolve1d_4D, self).make_thunk( node, storage_map, compute_map, no_recycling)
def convolve_mean3_gu(image, index, out_image): nx, ny, nk = image.shape for j in range(1,ny-1): for k in range(3): out_image[j-1, k] = 0.25*(image[index[0]-1,j,k]+image[index[0]+1,j,k]+image[index[0],j-1,k]+image[index[0],j+1,k]) #@numba.jit #def convolve_mean2(image): # height, width = image.shape # out_image = np.empty((height-2, width-2)) # i = np.arange(1, height-1) # j = np.arange(1, width-1) # convolve_mean2_gu(image, i[:, np.newaxis], j[np.newaxis, :], out_image) # return out_image