def set_and_check_flag(self, flag, dtype, arr):
if dtype is None:
dtype = arr.dtype
b = np.require(arr, dtype, [flag])
assert_(b.flags[flag])
assert_(b.dtype == dtype)
# a further call to np.require ought to return the same array
# unless OWNDATA is specified.
c = np.require(b, None, [flag])
if flag[0] != 'O':
assert_(c is b)
else:
assert_(c.flags[flag])
python类require()的实例源码
def test_unknown_requirement(self):
a = self.generate_all_false('f8')
assert_raises(KeyError, np.require, a, None, 'Q')
def test_non_array_input(self):
a = np.require([1, 2, 3, 4], 'i4', ['C', 'A', 'O'])
assert_(a.flags['O'])
assert_(a.flags['C'])
assert_(a.flags['A'])
assert_(a.dtype == 'i4')
assert_equal(a, [1, 2, 3, 4])
def test_C_and_F_simul(self):
a = self.generate_all_false('f8')
assert_raises(ValueError, np.require, a, None, ['C', 'F'])
def test_ensure_array(self):
class ArraySubclass(np.ndarray):
pass
a = ArraySubclass((2, 2))
b = np.require(a, None, ['E'])
assert_(type(b) is np.ndarray)
def _gt_propagate_boxes(boxes, annot_proto, frame_id, window, overlap_thres):
pred_boxes = []
annots = []
for annot in annot_proto['annotations']:
for idx, box in enumerate(annot['track']):
if box['frame'] == frame_id:
gt1 = box['bbox']
deltas = []
deltas.append(gt1)
for offset in xrange(1, window):
try:
gt2 = annot['track'][idx+offset]['bbox']
except IndexError:
gt2 = gt1
delta = bbox_transform(np.asarray([gt1]), np.asarray([gt2]))
deltas.append(delta)
annots.append(deltas)
gt1s = [annot[0] for annot in annots]
if not gt1s:
# no grount-truth, boxes remain still
return np.tile(np.asarray(boxes)[:,np.newaxis,:], [1,window-1,1])
overlaps = bbox_overlaps(np.require(boxes, dtype=np.float),
np.require(gt1s, dtype=np.float))
assert len(overlaps) == len(boxes)
for gt_overlaps, box in zip(overlaps, boxes):
max_overlap = np.max(gt_overlaps)
max_gt = np.argmax(gt_overlaps)
sequence_box = []
if max_overlap < overlap_thres:
for offset in xrange(1, window):
sequence_box.append(box)
else:
for offset in xrange(1, window):
delta = annots[max_gt][offset]
sequence_box.append(
bbox_transform_inv(np.asarray([box]), delta)[0].tolist())
pred_boxes.append((sequence_box))
return np.asarray(pred_boxes)
def _setup_arrays(x,v,m,omega=None):
sindx= numpy.argsort(x)
# Keep track of amount of mass above and below and compute acceleration
mass_below= numpy.cumsum(m[sindx])
mass_below[-1]= 0.
mass_below= numpy.roll(mass_below,1)
mass_above= numpy.cumsum(m[sindx][::-1])[::-1]
mass_above[0]= 0.
mass_above= numpy.roll(mass_above,-1)
a= (mass_above-mass_below)[numpy.argsort(sindx)]
# Solve for all collisions, using C code for consistency
tcoll= []
for xi,vi,ai,xii,vii,aii in zip(x[sindx][:-1],v[sindx][:-1],a[sindx][:-1],
x[sindx][1:],v[sindx][1:],a[sindx][1:]):
if omega is None:
tcoll.append(_wendy_solve_coll_quad_func(xi-xii,vi-vii,(ai-aii)/2.))
else:
tcoll.append(_wendy_solve_coll_harm_func(xi-xii,vi-vii,ai-aii,omega))
tcoll= numpy.array(tcoll)
cindx= ctypes.c_int(numpy.argmin(tcoll))
next_tcoll= ctypes.c_double(tcoll[cindx])
# Prepare for C
err= ctypes.c_int(0)
#Array requirements
x= numpy.require(x,dtype=numpy.float64,requirements=['C','W'])
v= numpy.require(v,dtype=numpy.float64,requirements=['C','W'])
a= numpy.require(a,dtype=numpy.float64,requirements=['C','W'])
m= numpy.require(m,dtype=numpy.float64,requirements=['C','W'])
sindx= numpy.require(sindx,dtype=numpy.int32,requirements=['C','W'])
tcoll= numpy.require(tcoll,dtype=numpy.float64,requirements=['C','W'])
return (x,v,m,a,sindx,cindx,next_tcoll,tcoll,err)
def calculate(self, parameters_dict):
"""Calculate DKI statistics like the mean, axial and radial kurtosis.
The Mean Kurtosis (MK) is calculated by averaging the Kurtosis over orientations on the unit sphere.
The Axial Kurtosis (AK) is obtained using the principal direction of diffusion (fe; first eigenvec)
from the Tensor as its direction and then averaging the Kurtosis over +fe and -fe.
Finally, the Radial Kurtosis (RK) is calculated by averaging the Kurtosis over a circle of directions around
the first eigenvec.
Args:
parameters_dict (dict): the fitted Kurtosis parameters, this requires a dictionary with at least
the elements:
'd', 'dperp0', 'dperp1', 'theta', 'phi', 'psi', 'W_0000', 'W_1000', 'W_1100', 'W_1110',
'W_1111', 'W_2000', 'W_2100', 'W_2110', 'W_2111', 'W_2200', 'W_2210', 'W_2211',
'W_2220', 'W_2221', 'W_2222'.
Returns:
dict: maps for the Mean Kurtosis (MK), Axial Kurtosis (AK) and Radial Kurtosis (RK).
"""
if parameters_dict['d'].dtype == np.float32:
np_dtype = np.float32
mot_float_type = SimpleCLDataType.from_string('float')
double_precision = False
else:
np_dtype = np.float64
mot_float_type = SimpleCLDataType.from_string('double')
double_precision = True
param_names = ['d', 'dperp0', 'dperp1', 'theta', 'phi', 'psi', 'W_0000', 'W_1000', 'W_1100', 'W_1110',
'W_1111', 'W_2000', 'W_2100', 'W_2110', 'W_2111', 'W_2200', 'W_2210', 'W_2211',
'W_2220', 'W_2221', 'W_2222']
parameters = np.require(np.column_stack([parameters_dict[n] for n in param_names]),
np_dtype, requirements=['C', 'A', 'O'])
directions = convert_data_to_dtype(self._get_spherical_samples(), 'mot_float_type4', mot_float_type)
return self._calculate(parameters, param_names, directions, double_precision)
def required(ob):
"""Return an object that meets Shapely requirements for self-owned
C-continguous data, copying if necessary, or just return the original
object."""
if has_numpy and hasattr(ob, '__array_interface__'):
return numpy.require(ob, numpy.float64, ["C", "OWNDATA"])
else:
return ob
def set_and_check_flag(self, flag, dtype, arr):
if dtype is None:
dtype = arr.dtype
b = np.require(arr, dtype, [flag])
assert_(b.flags[flag])
assert_(b.dtype == dtype)
# a further call to np.require ought to return the same array
# unless OWNDATA is specified.
c = np.require(b, None, [flag])
if flag[0] != 'O':
assert_(c is b)
else:
assert_(c.flags[flag])
def test_unknown_requirement(self):
a = self.generate_all_false('f8')
assert_raises(KeyError, np.require, a, None, 'Q')
def test_non_array_input(self):
a = np.require([1, 2, 3, 4], 'i4', ['C', 'A', 'O'])
assert_(a.flags['O'])
assert_(a.flags['C'])
assert_(a.flags['A'])
assert_(a.dtype == 'i4')
assert_equal(a, [1, 2, 3, 4])
def test_C_and_F_simul(self):
a = self.generate_all_false('f8')
assert_raises(ValueError, np.require, a, None, ['C', 'F'])
def test_ensure_array(self):
class ArraySubclass(np.ndarray):
pass
a = ArraySubclass((2, 2))
b = np.require(a, None, ['E'])
assert_(type(b) is np.ndarray)
def slidingWindow(s, span, stride=None, axis=0):
"""Sliding window.
"""
#s = np.ascontiguousarray(s)
s = np.require(s, requirements=['C', 'O'])
if stride is None:
stride = span
# catch some bad values since this is a common place for
# bugs to crop up in other routines
if span > s.shape[axis]:
raise ValueError('Span of %d exceeds input length of %d.' % (span, s.shape[axis]))
if span < 0:
raise ValueError('Negative span of %d is invalid.' % span)
if stride < 1:
raise ValueError('Stride of %d is not positive.' % stride)
nWin = int(np.ceil((s.shape[axis]-span+1) / float(stride)))
shape = list(s.shape)
shape[axis] = span
shape.insert(axis, nWin)
strides = list(s.strides)
strides.insert(axis, stride*strides[axis])
return npst.as_strided(s, shape=shape, strides=strides)
def train(self, x, g, optimFunc, **kwargs):
x = util.segmat(x)
x = np.require(x, requirements=['O', 'C'])
g = util.segmat(g)
g = np.require(g, requirements=['O', 'C'])
self.trainResult = optimFunc(self, x=x, g=g, **kwargs)
def train(self, classData, optimFunc, **kwargs):
x, g = label.indicatorsFromList(classData)
x = np.require(x, requirements=['O', 'C'])
self.trainResult = optimFunc(self, x=x, g=g, **kwargs)
def train(self, classData, optimFunc, **kwargs):
x, g = label.indicatorsFromList(classData)
x = np.require(x, requirements=['O', 'C'])
self.trainResult = optimFunc(self, x=x, g=g, **kwargs)
#dv = self.discrim(x, accum='mult')
#self.normSoftmaxMean = dv.mean()
#self.normSoftmaxStd = dv.std()
#self.normSoftmaxMin = dv.min()
#self.normSoftmaxMax = (dv-self.normSoftmaxMin).max()
def _bad_tt2000(*args, **kwargs):
"""Convenience function for complaining that TT2000 not supported"""
raise NotImplementedError(
'TT2000 functions require CDF library 3.4.0 or later')
def convert_input_array(self, buffer):
"""Converts a buffer of raw data from this slice
EPOCH(16) variables always need to be converted.
CHAR need converted to Unicode if py3k
Parameters
==========
buffer : numpy.array
data as read from the CDF file
Returns
=======
out : numpy.array
converted data
"""
result = self._flip_array(buffer)
#Convert to derived types
cdftype = self.zvar.type()
if not self.zvar._raw:
if cdftype in (const.CDF_CHAR.value, const.CDF_UCHAR.value) and \
str != bytes:
dt = numpy.dtype('U{0}'.format(result.dtype.itemsize))
result = numpy.require(numpy.char.array(result).decode(),
dtype=dt)
elif cdftype == const.CDF_EPOCH.value:
result = lib.v_epoch_to_datetime(result)
elif cdftype == const.CDF_EPOCH16.value:
result = lib.v_epoch16_to_datetime(result)
elif cdftype == const.CDF_TIME_TT2000.value:
result = lib.v_tt2000_to_datetime(result)
return result