本文整理匯總了Python中numpy.asanyarray方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.asanyarray方法的具體用法?Python numpy.asanyarray怎麽用?Python numpy.asanyarray使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.asanyarray方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: format_mask
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def format_mask(x):
"""
Formats a mask into a readable string.
Args:
x (ndarray): an array with the mask;
Returns:
A readable string with the mask.
"""
x = numpy.asanyarray(x)
if len(x) == 0:
return "(empty)"
if x.dtype == bool:
x = numpy.argwhere(x)[:, 0]
grps = tuple(list(g) for _, g in groupby(x, lambda n, c=count(): n-next(c)))
return ",".join("{:d}-{:d}".format(i[0], i[-1]) if len(i) > 1 else "{:d}".format(i[0]) for i in grps)
示例2: image_copy
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def image_copy(img, dataobj=Ellipsis, affine=Ellipsis, image_type=None):
'''
image_copy(image) copies the given image and returns the new object; the affine, header, and
dataobj members are duplicated so that changes will not change the original image.
The following optional arguments may be given to overwrites part of the new image; in each case,
the default value (Ellipsis) specifies that no update should be made.
* dataobj (default: Ellipsis) may overwrite the new image's dataobj object.
* affine (default: Ellipsis) may overwrite the new image's affine transformation matrix.
'''
dataobj = np.array(img.dataobj) if dataobj is Ellipsis else np.asanyarray(dataobj)
imspec = to_image_spec(img)
imtype = to_image_type(img if image_type is None else image_type)
affine = imspec['affine'] if affine is Ellipsis else affine
imspec['affine'] = affine
return imtype.create(dataobj, imspec)
示例3: apply_affine
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def apply_affine(aff, coords):
'''
apply_affine(affine, coords) yields the result of applying the given affine transformation to
the given coordinate or coordinates.
This function expects coords to be a (dims X n) matrix but if the first dimension is neither 2
nor 3, coords.T is used; i.e.:
apply_affine(affine3x3, coords2xN) ==> newcoords2xN
apply_affine(affine4x4, coords3xN) ==> newcoords3xN
apply_affine(affine3x3, coordsNx2) ==> newcoordsNx2 (for N != 2)
apply_affine(affine4x4, coordsNx3) ==> newcoordsNx3 (for N != 3)
'''
if aff is None: return coords
(coords,tr) = (np.asanyarray(coords), False)
if len(coords.shape) == 1: return np.squeeze(apply_affine(np.reshape(coords, (-1,1)), aff))
elif len(coords.shape) > 2: raise ValueError('cannot apply affine to ND-array for N > 2')
if len(coords) == 2: aff = to_affine(aff, 2)
elif len(coords) == 3: aff = to_affine(aff, 3)
else: (coords,aff,tr) = (coords.T, to_affine(aff, coords.shape[1]), True)
r = np.dot(aff, np.vstack([coords, np.ones([1,coords.shape[1]])]))[:-1]
return r.T if tr else r
示例4: supercell_space_required
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def supercell_space_required(transform_oo, transform_vv, final_space):
"""
For a given orbital transformation and a given `ov` mask in the transformed space, calculates a minimal `ov` mask
in the original space required to achieve this transform.
Args:
transform_oo (ndarray): the transformation in the occupied space;
transform_vv (ndarray): the transformation in the virtual space;
final_space (ndarray): the final `ov` space. Basis order: [k_o, o, k_v, v];
Returns:
The initial active space. Basis order: [k_o, o, k_v, v].
"""
final_space = numpy.asanyarray(final_space)
final_space = final_space.reshape(final_space.shape[:-1] + (transform_oo.shape[1], transform_vv.shape[1]))
result = einsum(
"ao,bv,...ov->...ab",
(transform_oo.toarray() != 0).astype(int),
(transform_vv.toarray() != 0).astype(int),
final_space.astype(int),
) != 0
return result.reshape(result.shape[:-2] + (-1,))
示例5: orb2ov
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def orb2ov(space, nocc, nmo):
"""
Converts orbital active space specification into ov-pairs space spec.
Args:
space (ndarray): the obital space. Basis order: [k, orb=o+v];
nocc (Iterable): the numbers of occupied orbitals per k-point;
nmo (Iterable): the total numbers of orbitals per k-point;
Returns:
The ov space specification. Basis order: [k_o, o, k_v, v].
"""
space = numpy.asanyarray(space)
m = ko_mask(nocc, nmo) # [k, orb=o+v]
o = space[..., m] # [k, o]
v = space[..., ~m] # [k, v]
return (o[..., numpy.newaxis] * v[..., numpy.newaxis, :]).reshape(space.shape[:-1] + (-1,)) # [k_o, o, k_v, v]
示例6: vector_to_amplitudes
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def vector_to_amplitudes(vectors, nocc, nmo):
"""
Transforms (reshapes) and normalizes vectors into amplitudes.
Args:
vectors (numpy.ndarray): raw eigenvectors to transform;
nocc (tuple): numbers of occupied orbitals;
nmo (int): the total number of orbitals per k-point;
Returns:
Amplitudes with the following shape: (# of roots, 2 (x or y), # of kpts, # of occupied orbitals,
# of virtual orbitals).
"""
if not all(i == nocc[0] for i in nocc):
raise NotImplementedError("Varying occupation numbers are not implemented yet")
nk = len(nocc)
nocc = nocc[0]
if not all(i == nmo[0] for i in nmo):
raise NotImplementedError("Varying AO spaces are not implemented yet")
nmo = nmo[0]
vectors = numpy.asanyarray(vectors)
vectors = vectors.reshape(2, nk, nocc, nmo-nocc, vectors.shape[1])
norm = (abs(vectors) ** 2).sum(axis=(1, 2, 3))
norm = 2 * (norm[0] - norm[1])
vectors /= norm ** .5
return vectors.transpose(4, 0, 1, 2, 3)
示例7: vector_to_amplitudes
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def vector_to_amplitudes(vectors, nocc, nmo):
"""
Transforms (reshapes) and normalizes vectors into amplitudes.
Args:
vectors (numpy.ndarray): raw eigenvectors to transform;
nocc (tuple): numbers of occupied orbitals;
nmo (tuple): the total numbers of AOs per k-point;
Returns:
Amplitudes with the following shape: (# of roots, 2 (x or y), # of kpts, # of kpts, # of occupied orbitals,
# of virtual orbitals).
"""
if not all(i == nocc[0] for i in nocc):
raise NotImplementedError("Varying occupation numbers are not implemented yet")
nk = len(nocc)
nocc = nocc[0]
if not all(i == nmo[0] for i in nmo):
raise NotImplementedError("Varying AO spaces are not implemented yet")
nmo = nmo[0]
vectors = numpy.asanyarray(vectors)
vectors = vectors.reshape(2, nk, nk, nocc, nmo-nocc, vectors.shape[1])
norm = (abs(vectors) ** 2).sum(axis=(1, 2, 3, 4))
norm = 2 * (norm[0] - norm[1])
vectors /= norm ** .5
return vectors.transpose(5, 0, 1, 2, 3, 4)
示例8: vector_to_amplitudes
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def vector_to_amplitudes(vectors, nocc, nmo):
"""
Transforms (reshapes) and normalizes vectors into amplitudes.
Args:
vectors (numpy.ndarray): raw eigenvectors to transform;
nocc (int): number of occupied orbitals;
nmo (int): the total number of orbitals;
Returns:
Amplitudes with the following shape: (# of roots, 2 (x or y), # of occupied orbitals, # of virtual orbitals).
"""
vectors = numpy.asanyarray(vectors)
vectors = vectors.reshape(2, nocc, nmo-nocc, vectors.shape[1])
norm = (abs(vectors) ** 2).sum(axis=(1, 2))
norm = 2 * (norm[0] - norm[1])
vectors /= norm ** .5
return vectors.transpose(3, 0, 1, 2)
示例9: nside_to_pixel_area
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def nside_to_pixel_area(nside):
"""
Find the area of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
pixel_area : :class:`~astropy.units.Quantity`
The area of the HEALPix pixels
"""
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
npix = 12 * nside * nside
pixel_area = 4 * math.pi / npix * u.sr
return pixel_area
示例10: nside_to_pixel_resolution
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def nside_to_pixel_resolution(nside):
"""
Find the resolution of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
resolution : :class:`~astropy.units.Quantity`
The resolution of the HEALPix pixels
See also
--------
pixel_resolution_to_nside
"""
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
return (nside_to_pixel_area(nside) ** 0.5).to(u.arcmin)
示例11: nside_to_npix
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def nside_to_npix(nside):
"""
Find the number of pixels corresponding to a HEALPix resolution.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
npix : int
The number of pixels in the HEALPix map.
"""
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
return 12 * nside ** 2
示例12: take
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def take(self, indexer, axis=1, verify=True, convert=True):
"""
Take items along any axis.
"""
self._consolidate_inplace()
indexer = (np.arange(indexer.start, indexer.stop, indexer.step,
dtype='int64')
if isinstance(indexer, slice)
else np.asanyarray(indexer, dtype='int64'))
n = self.shape[axis]
if convert:
indexer = maybe_convert_indices(indexer, n)
if verify:
if ((indexer == -1) | (indexer >= n)).any():
raise Exception('Indices must be nonzero and less than '
'the axis length')
new_labels = self.axes[axis].take(indexer)
return self.reindex_indexer(new_axis=new_labels, indexer=indexer,
axis=axis, allow_dups=True)
示例13: apply_lut
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def apply_lut(in_dseg, lut, newpath=None):
"""Map the input discrete segmentation to a new label set (lookup table, LUT)."""
import numpy as np
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
if newpath is None:
from os import getcwd
newpath = getcwd()
out_file = fname_presuffix(in_dseg, suffix='_dseg', newpath=newpath)
lut = np.array(lut, dtype='int16')
segm = nb.load(in_dseg)
hdr = segm.header.copy()
hdr.set_data_dtype('int16')
segm.__class__(lut[np.asanyarray(segm.dataobj, dtype=int)].astype('int16'),
segm.affine, hdr).to_filename(out_file)
return out_file
示例14: _call_series
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def _call_series(self, a, inputs):
if isinstance(self._q, TENSOR_TYPE):
q_val = self._q
index_val = pd.Index([], dtype=q_val.dtype)
store_index_value = False
else:
q_val = np.asanyarray(self._q)
index_val = pd.Index(q_val)
store_index_value = True
# get dtype by tensor
a_t = astensor(a)
self._dtype = dtype = tensor_quantile(
a_t, self._q, interpolation=self._interpolation,
handle_non_numeric=not self._numeric_only).dtype
if q_val.ndim == 0:
return self.new_scalar(inputs, dtype=dtype)
else:
return self.new_series(
inputs, shape=q_val.shape, dtype=dtype,
index_value=parse_index(index_val, a, q_val, self._interpolation,
type(self).__name__, store_data=store_index_value),
name=a.name)
示例15: cifti_split
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import asanyarray [as 別名]
def cifti_split(cii, label=('lh', 'rh', 'rest'), subject=None, hemi=None, null=np.nan):
'''
cifti_split(cii, label) yields the rows or columns of the given cifti file that correspond to
the given label (see below).
cifti_split(cii) is equivalent to cifti_split(cii, ('lh', 'rh', 'rest')).
The label argument may be any of the following:
* a valid CIFTI label name such as 'CIFTI_STRUCTURE_CEREBELLUM' or
'CIFTI_STRUCTURE_CORTEX_LEFT';
* an abbreviated name such as 'cerebellum' for 'CIFTI_STRUCTURE_CEREBELLUM'.
* the abbreviations 'lh' and 'rh' which stand for 'CIFTI_STRUCTURE_CORTEX_LEFT' and
'CIFTI_STRUCTURE_CORTEX_RIGHT';
* the special keyword 'rest', which represents all the rows/columns not collected by any other
instruction ('rest', by itself, results in the whole matrix being returned); or
* A tuple of the above, indicating that each of the items listed should be returned
sequentially in a tuple.
The following optional arguments may be given:
* subject (default: None) may specify the subject
* hemi (default: None) can specify the hemisphere object that
'''
dat = np.asanyarray(cii.dataobj if is_image(cii) else cii)
n = dat.shape[-1]
atlas = cifti_split._size_data.get(n, None)
if atlas is None: raise ValueError('cannot split cifti with size %d' % n)
if atlas not in cifti_split._atlas_cache:
patt = os.path.join('data', 'fs_LR', '%s.atlasroi.%dk_fs_LR.shape.gii')
lgii = nib.load(os.path.join(library_path(), patt % ('lh', atlas)))
rgii = nib.load(os.path.join(library_path(), patt % ('rh', atlas)))
cifti_split._atlas_cache[atlas] = tuple([pimms.imm_array(gii.darrays[0].data.astype('bool'))
for gii in (lgii, rgii)])
(lroi,rroi) = cifti_split._atlas_cache[atlas]
(ln,lN) = (np.sum(lroi), len(lroi))
(rn,rN) = (np.sum(rroi), len(rroi))
(ldat,rdat,sdat) = [np.full(dat.shape[:-1] + (k,), null) for k in [lN, rN, n - ln - rn]]
ldat[..., lroi] = dat[..., :ln]
rdat[..., rroi] = dat[..., ln:(ln+rn)]
sdat[...] = dat[..., (ln+rn):]
if ln + rn >= n: sdat = None
return (ldat, rdat, sdat)