本文整理汇总了Python中numpy.void方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.void方法的具体用法?Python numpy.void怎么用?Python numpy.void使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.void方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_datatype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def test_datatype(self):
ehdr = self.header_class()
codes = self.header_class._data_type_codes
for code in codes.value_set():
npt = codes.type[code]
if npt is np.void:
assert_raises(
HeaderDataError,
ehdr.set_data_dtype,
code)
continue
dt = codes.dtype[code]
ehdr.set_data_dtype(npt)
assert_true(ehdr['datatype'] == code)
assert_true(ehdr['bitpix'] == dt.itemsize*8)
ehdr.set_data_dtype(code)
assert_true(ehdr['datatype'] == code)
ehdr.set_data_dtype(dt)
assert_true(ehdr['datatype'] == code)
示例2: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def __init__(self, array, ptr=None):
self._arr = array
if ctypes:
self._ctypes = ctypes
# get a void pointer to the buffer, which keeps the array alive
self._data = _get_void_ptr(array)
assert self._data.value == ptr
else:
# fake a pointer-like object that holds onto the reference
self._ctypes = _missing_ctypes()
self._data = self._ctypes.c_void_p(ptr)
self._data._objects = array
if self._arr.ndim == 0:
self._zerod = True
else:
self._zerod = False
示例3: _name_get
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def _name_get(dtype):
# provides dtype.name.__get__
if dtype.isbuiltin == 2:
# user dtypes don't promise to do anything special
return dtype.type.__name__
# Builtin classes are documented as returning a "bit name"
name = dtype.type.__name__
# handle bool_, str_, etc
if name[-1] == '_':
name = name[:-1]
# append bit counts to str, unicode, and void
if np.issubdtype(dtype, np.flexible) and not _isunsized(dtype):
name += "{}".format(dtype.itemsize * 8)
# append metadata to datetimes
elif dtype.type in (np.datetime64, np.timedelta64):
name += _datetime_metadata_str(dtype)
return name
示例4: test_void_scalar_structured_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def test_void_scalar_structured_data(self):
dt = np.dtype([('name', np.unicode_, 16), ('grades', np.float64, (2,))])
x = np.array(('ndarray_scalar', (1.2, 3.0)), dtype=dt)[()]
assert_(isinstance(x, np.void))
mv_x = memoryview(x)
expected_size = 16 * np.dtype((np.unicode_, 1)).itemsize
expected_size += 2 * np.dtype((np.float64, 1)).itemsize
assert_equal(mv_x.itemsize, expected_size)
assert_equal(mv_x.ndim, 0)
assert_equal(mv_x.shape, ())
assert_equal(mv_x.strides, ())
assert_equal(mv_x.suboffsets, ())
# check scalar format string against ndarray format string
a = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
assert_(isinstance(a, np.ndarray))
mv_a = memoryview(a)
assert_equal(mv_x.itemsize, mv_a.itemsize)
assert_equal(mv_x.format, mv_a.format)
示例5: test_void_scalar_constructor
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def test_void_scalar_constructor(self):
#Issue #1550
#Create test string data, construct void scalar from data and assert
#that void scalar contains original data.
test_string = np.array("test")
test_string_void_scalar = np.core.multiarray.scalar(
np.dtype(("V", test_string.dtype.itemsize)), test_string.tobytes())
assert_(test_string_void_scalar.view(test_string.dtype) == test_string)
#Create record scalar, construct from data and assert that
#reconstructed scalar is correct.
test_record = np.ones((), "i,i")
test_record_void_scalar = np.core.multiarray.scalar(
test_record.dtype, test_record.tobytes())
assert_(test_record_void_scalar == test_record)
# Test pickle and unpickle of void and record scalars
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
assert_(pickle.loads(
pickle.dumps(test_string, protocol=proto)) == test_string)
assert_(pickle.loads(
pickle.dumps(test_record, protocol=proto)) == test_record)
示例6: iteratorFn
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def iteratorFn(self, data):
## Return 1) a function that will provide an iterator for data and 2) a list of header strings
if isinstance(data, list) or isinstance(data, tuple):
return lambda d: d.__iter__(), None
elif isinstance(data, dict):
return lambda d: iter(d.values()), list(map(asUnicode, data.keys()))
elif (hasattr(data, 'implements') and data.implements('MetaArray')):
if data.axisHasColumns(0):
header = [asUnicode(data.columnName(0, i)) for i in range(data.shape[0])]
elif data.axisHasValues(0):
header = list(map(asUnicode, data.xvals(0)))
else:
header = None
return self.iterFirstAxis, header
elif isinstance(data, np.ndarray):
return self.iterFirstAxis, None
elif isinstance(data, np.void):
return self.iterate, list(map(asUnicode, data.dtype.names))
elif data is None:
return (None,None)
else:
msg = "Don't know how to iterate over data type: {!s}".format(type(data))
raise TypeError(msg)
示例7: test_void_scalar_constructor
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def test_void_scalar_constructor(self):
#Issue #1550
#Create test string data, construct void scalar from data and assert
#that void scalar contains original data.
test_string = np.array("test")
test_string_void_scalar = np.core.multiarray.scalar(
np.dtype(("V", test_string.dtype.itemsize)), test_string.tobytes())
assert_(test_string_void_scalar.view(test_string.dtype) == test_string)
#Create record scalar, construct from data and assert that
#reconstructed scalar is correct.
test_record = np.ones((), "i,i")
test_record_void_scalar = np.core.multiarray.scalar(
test_record.dtype, test_record.tobytes())
assert_(test_record_void_scalar == test_record)
#Test pickle and unpickle of void and record scalars
assert_(pickle.loads(pickle.dumps(test_string)) == test_string)
assert_(pickle.loads(pickle.dumps(test_record)) == test_record)
示例8: attributes_encoder
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def attributes_encoder(attr):
"""Custom encoder for copying file attributes in Python 3"""
if isinstance(attr, (bytes, bytearray)):
return attr.decode('utf-8')
if isinstance(attr, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32,
np.int64, np.uint8, np.uint16, np.uint32, np.uint64)):
return int(attr)
elif isinstance(attr, (np.float_, np.float16, np.float32, np.float64)):
return float(attr)
elif isinstance(attr, (np.ndarray)):
if not isinstance(attr[0], (object)):
return attr.tolist()
elif isinstance(attr, (np.bool_)):
return bool(attr)
elif isinstance(attr, (np.void)):
return None
else:
return attr
#-- PURPOSE: help module to describe the optional input parameters
示例9: enlarge_space
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def enlarge_space(myci, civec, h1, eri, jk, eri_sorted, jk_sorted, norb, nelec):
if not isinstance(civec, (tuple, list)):
civec = [civec]
strs = civec[0]._strs
nroots = len(civec)
cidx = abs(civec[0]) > myci.ci_coeff_cutoff
for p in range(1,nroots):
cidx += abs(civec[p]) > myci.ci_coeff_cutoff
strs = strs[cidx]
ci_coeff = [as_SCIvector(c[cidx], strs) for c in civec]
strs_new = strs.copy()
for p in range(nroots):
str_add = select_strs_ctypes(myci, ci_coeff[p], h1, eri, jk, eri_sorted, jk_sorted, norb, nelec)
strs_new = numpy.vstack((strs, str_add))
# Add strings together and remove duplicate strings
tmp = numpy.ascontiguousarray(strs_new).view(numpy.dtype((numpy.void, strs_new.dtype.itemsize * strs_new.shape[1])))
_, tmpidx = numpy.unique(tmp, return_index=True)
new_ci = []
for p in range(nroots):
c = numpy.zeros(strs_new.shape[0])
c[:ci_coeff[p].shape[0]] = ci_coeff[p]
new_ci.append(c[tmpidx])
strs_new = strs_new[tmpidx]
return [as_SCIvector(ci, strs_new) for ci in new_ci]
示例10: save
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def save(self, filename):
assert filename.endswith('.h5')
with h5py.File(filename, 'w') as f:
for v in self.all_variables:
f[v.name] = v.eval()
# TODO: it would be nice to avoid pickle, but it's convenient to pass Python objects to _initialize
# (like Gym spaces or numpy arrays)
f.attrs['name'] = type(self).__name__
f.attrs['args_and_kwargs'] = np.void(pickle.dumps((self.args, self.kwargs), protocol=-1))
示例11: test_dataarray
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def test_dataarray():
for dt_code in data_type_codes.value_set():
data_type = data_type_codes.type[dt_code]
if data_type is np.void: # not supported
continue
arr = np.zeros((10,3), dtype=data_type)
da = GiftiDataArray.from_array(arr, 'triangle')
assert_equal(da.datatype, data_type_codes[arr.dtype])
bs_arr = arr.byteswap().newbyteorder()
da = GiftiDataArray.from_array(bs_arr, 'triangle')
assert_equal(da.datatype, data_type_codes[arr.dtype])
示例12: set_data_dtype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def set_data_dtype(self, datatype):
''' Set numpy dtype for data from code or dtype or type
Examples
--------
>>> hdr = AnalyzeHeader()
>>> hdr.set_data_dtype(np.uint8)
>>> hdr.get_data_dtype()
dtype('uint8')
>>> hdr.set_data_dtype(np.dtype(np.uint8))
>>> hdr.get_data_dtype()
dtype('uint8')
>>> hdr.set_data_dtype('implausible') #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
HeaderDataError: data dtype "implausible" not recognized
>>> hdr.set_data_dtype('none') #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
HeaderDataError: data dtype "none" known but not supported
>>> hdr.set_data_dtype(np.void) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
HeaderDataError: data dtype "<type 'numpy.void'>" known but not supported
'''
try:
code = self._data_type_codes[datatype]
except KeyError:
raise HeaderDataError(
'data dtype "%s" not recognized' % datatype)
dtype = self._data_type_codes.dtype[code]
# test for void, being careful of user-defined types
if dtype.type is np.void and not dtype.fields:
raise HeaderDataError(
'data dtype "%s" known but not supported' % datatype)
self._structarr['datatype'] = code
self._structarr['bitpix'] = dtype.itemsize * 8
示例13: test_data_dtype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def test_data_dtype(self):
# check getting and setting of data type
# codes / types supported by all binary headers
supported_types = ((2, np.uint8),
(4, np.int16),
(8, np.int32),
(16, np.float32),
(32, np.complex64),
(64, np.float64),
(128, np.dtype([('R','u1'),
('G', 'u1'),
('B', 'u1')])))
# and unsupported - here using some labels instead
unsupported_types = (np.void, 'none', 'all', 0)
hdr = self.header_class()
for code, npt in supported_types:
# Can set with code value, or numpy dtype, both return the
# dtype as output on get
hdr.set_data_dtype(code)
assert_equal(hdr.get_data_dtype(), npt)
hdr.set_data_dtype(npt)
assert_equal(hdr.get_data_dtype(), npt)
for inp in unsupported_types:
assert_raises(HeaderDataError,
hdr.set_data_dtype,
inp)
示例14: test_datatypes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def test_datatypes():
hdr = Nifti1Header()
for code in data_type_codes.value_set():
dt = data_type_codes.type[code]
if dt == np.void:
continue
hdr.set_data_dtype(code)
(assert_equal,
hdr.get_data_dtype(),
data_type_codes.dtype[code])
# Check that checks also see new datatypes
hdr.set_data_dtype(np.complex128)
hdr.check_fix()
示例15: _resize_with_dtype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import void [as 别名]
def _resize_with_dtype(arr, dtype):
"""
This function will transform arr into an array with the same type as dtype. It will do this by
filling new columns with zeros (or NaNs, if it is a float column). Also, columns that are not
in the new dtype will be dropped.
"""
structured_arrays = dtype.names is not None and arr.dtype.names is not None
old_columns = arr.dtype.names or []
new_columns = dtype.names or []
# In numpy 1.9 the ndarray.astype method used to handle changes in number of fields. The code below
# should replicate the same behaviour the old astype used to have.
#
# One may be tempted to use np.lib.recfunctions.stack_arrays to implement both this step and the
# concatenate that follows but it 2x slower and it requires providing your own default values (instead
# of np.zeros).
#
# Numpy 1.14 supports doing new_arr[old_columns] = arr[old_columns], which is faster than the code below
# (in benchmarks it seems to be even slightly faster than using the old astype). However, that is not
# supported by numpy 1.9.2.
if structured_arrays and (old_columns != new_columns):
old_columns = set(old_columns)
new_columns = set(new_columns)
new_arr = np.zeros(arr.shape, dtype)
for c in old_columns & new_columns:
new_arr[c] = arr[c]
# missing float columns should default to nan rather than zero
_is_float_type = lambda _dtype: _dtype.type in (np.float32, np.float64)
_is_void_float_type = lambda _dtype: _dtype.type == np.void and _is_float_type(_dtype.subdtype[0])
_is_float_or_void_float_type = lambda _dtype: _is_float_type(_dtype) or _is_void_float_type(_dtype)
_is_float = lambda column: _is_float_or_void_float_type(dtype.fields[column][0])
for new_column in filter(_is_float, new_columns - old_columns):
new_arr[new_column] = np.nan
return new_arr.astype(dtype)
else:
return arr.astype(dtype)