Here are the examples of the python api numpy.void taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
22 Examples
5
Example 1
Project: f2py Source File: test_py_support.py
def check_numpy_scalar_argument_return_void(self):
f = PyCFunction('foo')
f += Variable('a1', numpy.void, 'in, out')
f += Variable('a2', numpy.void, 'in, out')
foo = f.build()
args = ('he', 4)
results = (numpy.void('he'), numpy.void(4))
assert_equal(foo(*args), results)
3
Example 2
Project: zipline Source File: labelarray.py
@classmethod
def _from_codes_and_metadata(cls,
codes,
categories,
reverse_categories,
missing_value):
"""
View codes as a LabelArray and set LabelArray metadata on the result.
"""
ret = codes.view(type=cls, dtype=np.void)
ret._categories = categories
ret._reverse_categories = reverse_categories
ret._missing_value = missing_value
return ret
3
Example 3
Project: betty-cropper Source File: dssim.py
def unique_colors(img):
# For RGB, we need to get unique "rows" basically, as the color dimesion is an array.
# This is taken from: http://stackoverflow.com/a/16973510
color_view = np.ascontiguousarray(img).view(np.dtype((np.void,
img.dtype.itemsize * img.shape[2])))
unique = np.unique(color_view)
return unique.size
3
Example 4
Project: WASP Source File: find_intersecting_snps.py
def get_unique_haplotypes(haplotypes, snp_idx):
"""returns list of vectors of unique haplotypes for this set of SNPs"""
haps = haplotypes[snp_idx,:].T
# create view of data that joins all elements of column
# into single void datatype
h = np.ascontiguousarray(haps).view(np.dtype((np.void, haps.dtype.itemsize * haps.shape[1])))
# get index of unique columns
_, idx = np.unique(h, return_index=True)
return haps[idx,:]
3
Example 5
def test_ip_types(self):
unchecked_types = [str, unicode, np.void, object]
x = np.random.random(1000)*100
mask = x < 40
for val in [-100,0,15]:
for types in np.sctypes.itervalues():
for T in types:
if T not in unchecked_types:
yield self.tst_basic,x.copy().astype(T),T,mask,val
3
Example 6
def test_ip_types(self):
unchecked_types = [str, unicode, np.void, object]
x = np.random.random(24)*100
x.shape = 2,3,4
for types in np.sctypes.itervalues():
for T in types:
if T not in unchecked_types:
yield self.tst_basic,x.copy().astype(T)
3
Example 7
def format_entry(x):
"""
Formats floats to 5 decimal points and returns a string.
If `x` is a tuple, all elements in the tuple are formatted.
:param x: Float to be truncated to 5 decimal points.
:type x: float or tuple
:returns: `x` as a string.
"""
# np.void is the type of the tuples that appear in numpy
# structured arrays
if isinstance(x, np.void):
return ', '.join([format_entry(i) for i in x.tolist()])
if isfloat(x):
return '{0:.5f}'.format(x)
return str(x)
3
Example 8
def analyze(self):
plt.plot([1, 2, 0, 3, 4])
f = io.BytesIO()
plt.savefig(f, format="PNG")
f.seek(0)
self.set_dataset("thumbnail", np.void(f.read()))
3
Example 9
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: recfunctions.py
def _izip_fields_flat(iterable):
"""
Returns an iterator of concatenated fields from a sequence of arrays,
collapsing any nested structure.
"""
for element in iterable:
if isinstance(element, np.void):
for f in _izip_fields_flat(tuple(element)):
yield f
else:
yield element
3
Example 10
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: recfunctions.py
def _izip_fields(iterable):
"""
Returns an iterator of concatenated fields from a sequence of arrays.
"""
for element in iterable:
if (hasattr(element, '__iter__') and
not isinstance(element, basestring)):
for f in _izip_fields(element):
yield f
elif isinstance(element, np.void) and len(tuple(element)) == 1:
for f in _izip_fields(element):
yield f
else:
yield element
3
Example 11
Project: numba Source File: devicearray.py
def auto_device(obj, stream=0, copy=True):
"""
Create a DeviceRecord or DeviceArray like obj and optionally copy data from
host to device. If obj already represents device memory, it is returned and
no copy is made.
"""
if _driver.is_device_memory(obj):
return obj, False
else:
sentry_contiguous(obj)
if isinstance(obj, np.void):
devobj = from_record_like(obj, stream=stream)
else:
devobj = from_array_like(obj, stream=stream)
if copy:
devobj.copy_to_device(obj, stream=stream)
return devobj, True
3
Example 12
Project: numba Source File: driver.py
def host_pointer(obj):
"""
NOTE: The underlying data pointer from the host data buffer is used and
it should not be changed until the operation which can be asynchronous
completes.
"""
if isinstance(obj, (int, long)):
return obj
forcewritable = isinstance(obj, np.void)
return mviewbuf.memoryview_get_buffer(obj, forcewritable)
0
Example 13
def _check_level(label, expected, actual):
""" Check one level of a potentially nested array """
if SP.issparse(expected): # allow different types of sparse matrices
assert_(SP.issparse(actual))
assert_array_almost_equal(actual.todense(),
expected.todense(),
err_msg=label,
decimal=5)
return
# Check types are as expected
assert_(types_compatible(expected, actual),
"Expected type %s, got %s at %s" %
(type(expected), type(actual), label))
# A field in a record array may not be an ndarray
# A scalar from a record array will be type np.void
if not isinstance(expected,
(np.void, np.ndarray, MatlabObject)):
assert_equal(expected, actual)
return
# This is an ndarray-like thing
assert_(expected.shape == actual.shape,
msg='Expected shape %s, got %s at %s' % (expected.shape,
actual.shape,
label))
ex_dtype = expected.dtype
if ex_dtype.hasobject: # array of objects
if isinstance(expected, MatlabObject):
assert_equal(expected.classname, actual.classname)
for i, ev in enumerate(expected):
level_label = "%s, [%d], " % (label, i)
_check_level(level_label, ev, actual[i])
return
if ex_dtype.fields: # probably recarray
for fn in ex_dtype.fields:
level_label = "%s, field %s, " % (label, fn)
_check_level(level_label,
expected[fn], actual[fn])
return
if ex_dtype.type in (text_type, # string or bool
np.unicode_,
np.bool_):
assert_equal(actual, expected, err_msg=label)
return
# Something numeric
assert_array_almost_equal(actual, expected, err_msg=label, decimal=5)
0
Example 14
Project: Uranium Source File: MeshData.py
def uniqueVertices(vertices):
vertex_byte_view = numpy.ascontiguousarray(vertices).view(
numpy.dtype((numpy.void, vertices.dtype.itemsize * vertices.shape[1])))
_, idx = numpy.unique(vertex_byte_view, return_index=True)
return vertices[idx] # Select the unique rows by index.
0
Example 15
Project: datajoint-python Source File: relational_operand.py
@property
def where_clause(self):
"""
convert self.restrictions to the SQL WHERE clause
"""
def make_condition(arg, _negate=False):
if isinstance(arg, str):
return arg, _negate
elif isinstance(arg, AndList):
return '(' + ' AND '.join([make_condition(element)[0] for element in arg]) + ')', _negate
# semijoin or antijoin
elif isinstance(arg, RelationalOperand):
common_attributes = [q for q in self.heading.names if q in arg.heading.names]
if not common_attributes:
condition = 'FALSE' if _negate else 'TRUE'
else:
common_attributes = '`' + '`,`'.join(common_attributes) + '`'
condition = '({fields}) {not_}in ({subquery})'.format(
fields=common_attributes,
not_="not " if _negate else "",
subquery=arg.make_sql(common_attributes))
return condition, False # _negate is cleared
# mappings are turned into ANDed equality conditions
elif isinstance(arg, collections.abc.Mapping):
condition = ['`%s`=%r' %
(k, v if not isinstance(v, (datetime.date, datetime.datetime, datetime.time)) else str(v))
for k, v in arg.items() if k in self.heading]
elif isinstance(arg, np.void):
# element of a record array
condition = ['`%s`=%r' % (k, arg[k]) for k in arg.dtype.fields if k in self.heading]
else:
raise DataJointError('Invalid restriction type')
return ' AND '.join(condition) if condition else 'TRUE', _negate
if not self.is_restricted:
return ''
# An empty or-list in the restrictions immediately causes an empty result
if restricts_to_empty(self.restrictions):
return ' WHERE FALSE'
conditions = []
for item in self.restrictions:
negate = isinstance(item, Not)
if negate:
item = item.restriction # NOT is added below
if isinstance(item, (list, tuple, set, np.ndarray)):
item = '(' + ') OR ('.join(
[make_condition(q)[0] for q in item if q is not restricts_to_empty(q)]) + ')'
else:
item, negate = make_condition(item, negate)
conditions.append(('NOT (%s)' if negate else '(%s)') % item)
return ' WHERE ' + ' AND '.join(conditions)
0
Example 16
Project: gwpy Source File: utils.py
def get_row_value(row, attr):
"""Get the attribute value of a given LIGO_LW row.
Parameters
----------
row : `object`
a row of a LIGO_LW `Table`.
attr : `str`
the name of the column attribute to retrieve.
See Also
--------
get_table_column : for details on the column-name logic
"""
# shortcut from recarray
if isinstance(row, numpy.void) and attr == 'time':
return get_rec_time(row)
if isinstance(row, numpy.void):
return row[attr]
# presume ligolw row instance
attr = str(attr).lower()
cname = type(row).__name__
if hasattr(row, 'get_%s' % attr):
return getattr(row, 'get_%s' % attr)()
elif attr == 'time':
if re.match('(Sngl|Multi)Inspiral', cname, re.I):
return row.get_end()
elif re.match('(Sngl|Multi)Burst', cname, re.I):
return row.get_peak()
elif re.match('(Sngl|Multi)Ring', cname, re.I):
return row.get_start()
else:
return getattr(row, attr)
0
Example 17
Project: hyperspy Source File: mrc.py
def get_std_dtype_list(endianess='<'):
end = endianess
dtype_list = \
[
('NX', end + 'u4'),
('NY', end + 'u4'),
('NZ', end + 'u4'),
('MODE', end + 'u4'),
('NXSTART', end + 'u4'),
('NYSTART', end + 'u4'),
('NZSTART', end + 'u4'),
('MX', end + 'u4'),
('MY', end + 'u4'),
('MZ', end + 'u4'),
('Xlen', end + 'f4'),
('Ylen', end + 'f4'),
('Zlen', end + 'f4'),
('ALPHA', end + 'f4'),
('BETA', end + 'f4'),
('GAMMA', end + 'f4'),
('MAPC', end + 'u4'),
('MAPR', end + 'u4'),
('MAPS', end + 'u4'),
('AMIN', end + 'f4'),
('AMAX', end + 'f4'),
('AMEAN', end + 'f4'),
('ISPG', end + 'u2'),
('NSYMBT', end + 'u2'),
('NEXT', end + 'u4'),
('CREATID', end + 'u2'),
('EXTRA', (np.void, 30)),
('NINT', end + 'u2'),
('NREAL', end + 'u2'),
('EXTRA2', (np.void, 28)),
('IDTYPE', end + 'u2'),
('LENS', end + 'u2'),
('ND1', end + 'u2'),
('ND2', end + 'u2'),
('VD1', end + 'u2'),
('VD2', end + 'u2'),
('TILTANGLES', (np.float32, 6)),
('XORIGIN', end + 'f4'),
('YORIGIN', end + 'f4'),
('ZORIGIN', end + 'f4'),
('CMAP', (bytes, 4)),
('STAMP', (bytes, 4)),
('RMS', end + 'f4'),
('NLABL', end + 'u4'),
('LABELS', (bytes, 800)),
]
return dtype_list
0
Example 18
Project: hyperspy Source File: mrc.py
def get_fei_dtype_list(endianess='<'):
end = endianess
dtype_list = [
('a_tilt', end + 'f4'), # Alpha tilt (deg)
('b_tilt', end + 'f4'), # Beta tilt (deg)
# Stage x position (Unit=m. But if value>1, unit=???m)
('x_stage', end + 'f4'),
# Stage y position (Unit=m. But if value>1, unit=???m)
('y_stage', end + 'f4'),
# Stage z position (Unit=m. But if value>1, unit=???m)
('z_stage', end + 'f4'),
# Signal2D shift x (Unit=m. But if value>1, unit=???m)
('x_shift', end + 'f4'),
# Signal2D shift y (Unit=m. But if value>1, unit=???m)
('y_shift', end + 'f4'),
('defocus', end + 'f4'), # Defocus Unit=m. But if value>1, unit=???m)
('exp_time', end + 'f4'), # Exposure time (s)
('mean_int', end + 'f4'), # Mean value of image
('tilt_axis', end + 'f4'), # Tilt axis (deg)
('pixel_size', end + 'f4'), # Pixel size of image (m)
('magnification', end + 'f4'), # Magnification used
# Not used (filling up to 128 bytes)
('empty', (np.void, 128 - 13 * 4)),
]
return dtype_list
0
Example 19
@classmethod
def groupby(cls, dataset, dimensions, container_type, group_type, **kwargs):
data = dataset.data
# Get dimension objects, labels, indexes and data
dimensions = [dataset.get_dimension(d) for d in dimensions]
dim_idxs = [dataset.get_dimension_index(d) for d in dimensions]
ndims = len(dimensions)
kdims = [kdim for kdim in dataset.kdims
if kdim not in dimensions]
vdims = dataset.vdims
# Find unique entries along supplied dimensions
# by creating a view that treats the selected
# groupby keys as a single object.
indices = data[:, dim_idxs].copy()
group_shape = indices.dtype.itemsize * indices.shape[1]
view = indices.view(np.dtype((np.void, group_shape)))
_, idx = np.unique(view, return_index=True)
idx.sort()
unique_indices = indices[idx]
# Get group
group_kwargs = {}
if group_type != 'raw' and issubclass(group_type, Element):
group_kwargs.update(util.get_param_values(dataset))
group_kwargs['kdims'] = kdims
group_kwargs.update(kwargs)
# Iterate over the unique entries building masks
# to apply the group selection
grouped_data = []
for group in unique_indices:
mask = np.logical_and.reduce([data[:, d_idx] == group[i]
for i, d_idx in enumerate(dim_idxs)])
group_data = data[mask, ndims:]
if not group_type == 'raw':
if issubclass(group_type, dict):
group_data = {d.name: group_data[:, i] for i, d in
enumerate(kdims+vdims)}
else:
group_data = group_type(group_data, **group_kwargs)
grouped_data.append((tuple(group), group_data))
if issubclass(container_type, NdMapping):
with item_check(False):
return container_type(grouped_data, kdims=dimensions)
else:
return container_type(grouped_data)
0
Example 20
Project: trimesh Source File: grouping.py
def hashable_rows(data, digits=None):
'''
We turn our array into integers, based on the precision
given by digits, and then put them in a hashable format.
Arguments
---------
data: (n,m) input array
digits: how many digits to add to hash, if data is floating point
If none, TOL_MERGE will be turned into a digit count and used.
Returns
---------
hashable: (n) length array of custom data which can be sorted
or used as hash keys
'''
as_int = float_to_int(data, digits)
dtype = np.dtype((np.void, as_int.dtype.itemsize * as_int.shape[1]))
hashable = np.ascontiguousarray(as_int).view(dtype).reshape(-1)
return hashable
0
Example 21
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: test_dtype.py
def base_metadata_copied(self):
d = np.dtype((np.void, np.dtype('i4,i4', metadata={'datum': 1})))
assert_equal(d.metadata, {'datum': 1})
0
Example 22
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: test_dtype.py
def test_name_dtype_subclass(self):
# Ticket #4357
class user_def_subcls(np.void):
pass
assert_equal(np.dtype(user_def_subcls).name, 'user_def_subcls')