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)
python类jit()的实例源码
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.parking_orbit_alt <= 300000: return pitch_calcs_low()
else: return pitch_calcs_high()
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.target_orbit_alt <= 250000: 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.parking_orbit_alt <= 300000: return pitch_calcs_low()
else: return pitch_calcs_high()
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 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
input_encoders_numba.py 文件源码
项目:LSTM-and-maxlayer-for-SNV-based-phenotype-prediction
作者: widmi
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
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()