本文整理匯總了Python中numpy.indices方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.indices方法的具體用法?Python numpy.indices怎麽用?Python numpy.indices使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.indices方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_to_common_frame
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def get_to_common_frame(obs, frame_wcs):
""" Matches an `Observation`'s coordinates to a `Frame`'s wcs
Parameters
----------
obs: `Observation`
An observation instance for which we want to know the coordinates in the frame of `frame_wcs`
frame_wcs: `WCS`
a wcs that gives the mapping between pixel coordinates and sky coordinates for a given frame
Returns
-------
coord_obs_frame: `tuple`
Coordinates of the observations's pixels in the frame of the provided wcs
"""
c, ny, nx = obs.frame.shape
#Positions of the observation's pixels
y, x = np.indices((ny, nx))
y = y.flatten()
x = x.flatten()
# Positions of Observation's pixel in the frame of the wcs
Y,X = convert_coordinates((y,x), obs.frame.wcs, frame_wcs)
coord = (Y,X)
return coord
示例2: coefficients_to_polynomial
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def coefficients_to_polynomial(coefficients, variables):
"""Converts array of lists of coefficients to a polynomial."""
coefficients = np.asarray(coefficients)
shape = coefficients.shape
indices = list(zip(*np.indices(shape).reshape([len(shape), -1])))
monomials = []
for power in indices:
coeffs = coefficients.item(power)
if (number.is_integer_or_rational(coeffs)
or isinstance(coeffs, sympy.Symbol)):
coeffs = [coeffs]
elif not isinstance(coeffs, list):
raise ValueError('Unrecognized coeffs={} type={}'
.format(coeffs, type(coeffs)))
for coeff in coeffs:
monomials.append(monomial(coeff, variables, power))
random.shuffle(monomials)
return ops.Add(*monomials)
示例3: trim
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def trim(coefficients):
"""Makes non-zero entry in the final slice along each axis."""
coefficients = np.asarray(coefficients)
non_zero = np.not_equal(coefficients, 0)
ndim = coefficients.ndim
for axis in range(ndim):
length = coefficients.shape[axis]
axis_complement = list(range(0, axis)) + list(range(axis + 1, ndim))
non_zero_along_axis = np.any(non_zero, axis=tuple(axis_complement))
slice_to = 0
for index in range(length - 1, -1, -1):
if non_zero_along_axis[index]:
slice_to = index + 1
break
if slice_to < length:
coefficients = coefficients.take(axis=axis, indices=list(range(slice_to)))
return coefficients
示例4: position
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def position(self, lat_idx):
"""return 'space' position of one or multiple sites.
Parameters
----------
lat_idx : ndarray, ``(... , dim+1)``
Lattice indices.
Returns
-------
pos : ndarray, ``(..., dim)``
The position of the lattice sites specified by `lat_idx` in real-space.
"""
idx = self._asvalid_latidx(lat_idx)
res = np.take(self.unit_cell_positions, idx[..., -1], axis=0)
for i in range(self.dim):
res += idx[..., i, np.newaxis] * self.basis[i]
return res
示例5: mps2lat_idx
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def mps2lat_idx(self, i):
"""Translate MPS index `i` to lattice indices ``(x_0, ..., x_{dim-1}, u)``.
Parameters
----------
i : int | array_like of int
MPS index/indices.
Returns
-------
lat_idx : array
First dimensions like `i`, last dimension has len `dim`+1 and contains the lattice
indices ``(x_0, ..., x_{dim-1}, u)`` corresponding to `i`.
For `i` accross the MPS unit cell and "infinite" `bc_MPS`, we shift `x_0` accordingly.
"""
if self.bc_MPS == 'infinite':
# allow `i` outsit of MPS unit cell for bc_MPS infinite
i0 = i
i = np.mod(i, self.N_sites)
if np.any(i0 != i):
lat = self.order[i].copy()
lat[..., 0] += (i0 - i) * self.N_rings // self.N_sites
# N_sites_per_ring might not be set for IrregularLattice
return lat
return self.order[i].copy()
示例6: mps_lat_idx_fix_u
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def mps_lat_idx_fix_u(self, u=None):
"""Similar as :meth:`mps_idx_fix_u`, but return also the corresponding lattice indices.
Parameters
----------
u : None | int
Selects a site of the unit cell. ``None`` (default) means all sites.
Returns
-------
mps_idx : array
MPS indices `i` for which ``self.site(i) is self.unit_cell[u]``.
lat_idx : 2D array
The row `j` contains the lattice index (without `u`) corresponding to ``mps_idx[j]``.
"""
mps_idx = self.mps_idx_fix_u(u)
return mps_idx, self.order[mps_idx, :-1]
示例7: idrop_labels
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def idrop_labels(self, old_labels=None):
"""Remove leg labels from self; in place.
Parameters
----------
old_labels : list of str|int
The leg labels/indices for which the label should be removed.
By default (None), remove all labels.
"""
if old_labels is None:
self._labels = [None] * self.rank
return self
old_inds = self.get_leg_indices(old_labels)
labels = self._labels[:]
for i in old_inds:
labels[i] = None
self._labels = labels
return self
# string output ===========================================================
示例8: as_completely_blocked
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def as_completely_blocked(self):
"""Gives a version of self which is completely blocked by charges.
Functions like :func:`svd` or :func:`eigh` require a complete blocking by charges.
This can be achieved by encapsulating each leg which is not completely blocked into a
:class:`LegPipe` (containing only that single leg). The LegPipe will then contain all
necessary information to revert the blocking.
Returns
-------
encapsulated_axes : list of int
The leg indices which have been encapsulated into Pipes.
blocked_self : :class:`Array`
Self (if ``len(encapsulated_axes) = 0``) or a copy of self,
which is completely blocked.
"""
enc_axes = [a for a, l in enumerate(self.legs) if not l.is_blocked()]
if len(enc_axes) == 0:
return enc_axes, self
qconj = [self.legs[a].qconj for a in enc_axes]
return enc_axes, self.combine_legs([[a] for a in enc_axes], qconj=qconj)
示例9: _iter_common_sorted
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def _iter_common_sorted(a, b):
"""Yield indices ``i, j`` for which ``a[i] == b[j]``.
*Assumes* that ``a[i_start:i_stop]`` and ``b[j_start:j_stop]`` are strictly ascending.
Given that, it is equivalent to (but faster than)
``[(i, j) for j, i in itertools.product(range(len(a)), range(len(b)) if a[i] == b[j]]``
"""
l_a = len(a)
l_b = len(b)
i, j = 0, 0
res = []
while i < l_a and j < l_b:
if a[i] < b[j]:
i += 1
elif b[j] < a[i]:
j += 1
else:
res.append((i, j))
i += 1
j += 1
return res
示例10: bunch
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def bunch(self):
"""Return a copy with bunched self.charges: form blocks for contiguous equal charges.
Returns
-------
idx : 1D array
``idx[:-1]`` are the indices of the old qind which are kept,
``idx[-1] = old_block_number``.
cp : :class:`LegCharge`
A new LegCharge with the same charges at given indices of the leg,
but (possibly) shorter ``self.charges`` and ``self.slices``.
See also
--------
sort : sorts by charges, thus enforcing complete blocking in combination with bunch.
"""
if self.bunched: # nothing to do
return np.arange(self.block_number + 1, dtype=np.intp), self
cp = self.copy()
idx = _find_row_differences(self.charges)
cp._set_charges(cp.charges[idx[:-1]]) # avanced indexing -> copy
cp._set_slices(cp.slices[idx])
cp.bunched = True
return idx, cp
示例11: _find_row_differences
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def _find_row_differences(qflat):
"""Return indices where the rows of the 2D array `qflat` change.
Parameters
----------
qflat : 2D array
The rows of this array are compared.
Returns
-------
diffs: 1D array
The indices where rows change, including the first and last. Equivalent to:
``[0]+[i for i in range(1, len(qflat)) if np.any(qflat[i-1] != qflat[i])] + [len(qflat)]``
"""
if qflat.shape[1] == 0:
return np.array([0, qflat.shape[0]], dtype=np.intp)
diff = np.ones(qflat.shape[0] + 1, dtype=np.bool_)
diff[1:-1] = np.any(qflat[1:] != qflat[:-1], axis=1)
return np.nonzero(diff)[0] # get the indices of True-values
示例12: collate_fn_base
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def collate_fn_base(
self, attributes_and_types: Dict[str, type], batch: Union[List[int], np.ndarray]
) -> Tuple[torch.Tensor, ...]:
"""Given indices and attributes to batch, returns a full batch of ``Torch.Tensor``
"""
indices = np.asarray(batch)
data_numpy = [
getattr(self, attr)[indices].astype(dtype)
if isinstance(getattr(self, attr), np.ndarray)
else getattr(self, attr)[indices].toarray().astype(dtype)
for attr, dtype in attributes_and_types.items()
]
data_torch = tuple(torch.from_numpy(d) for d in data_numpy)
return data_torch
#############################
# #
# GENE FILTERING #
# #
#############################
示例13: subsample_cells
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def subsample_cells(self, size: Union[int, float] = 1.0):
"""Wrapper around ``update_cells`` allowing for automatic (based on sum of counts) subsampling.
If size is a:
* (0,1) float: subsample 100*``size`` % of the cells
* int: subsample ``size`` cells
"""
new_n_cells = (
int(size * self.nb_cells)
if not isinstance(size, (int, np.integer))
else size
)
indices = np.argsort(np.squeeze(np.asarray(self.X.sum(axis=1))))[::-1][
:new_n_cells
]
self.update_cells(indices)
示例14: filter_cell_types
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def filter_cell_types(self, cell_types: Union[List[str], List[int], np.ndarray]):
"""Performs in-place filtering of cells by keeping cell types in ``cell_types``.
Parameters
----------
cell_types
numpy array of type np.int (indices) or np.str (cell-types names)
"""
cell_types = np.asarray(cell_types)
if isinstance(cell_types[0], str):
labels_to_keep = self.cell_types_to_labels(cell_types)
elif isinstance(cell_types[0], (int, np.integer)):
labels_to_keep = cell_types
else:
raise ValueError(
"Wrong dtype for cell_types. Should be either str or int (labels)."
)
subset_cells = self._get_cells_filter_mask_by_attribute(
attribute_name="labels",
attribute_values_to_keep=labels_to_keep,
return_data=False,
)
self.update_cells(subset_cells)
示例15: _indices
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import indices [as 別名]
def _indices(self, slice_index=None):
# get a int-array containing all indices in the first axis.
if slice_index is None:
slice_index = self._current_slice_
#try:
indices = np.indices(self._realshape_, dtype=int)
indices = indices[(slice(None),)+slice_index]
indices = np.rollaxis(indices, 0, indices.ndim).reshape(-1,self._realndim_)
#print indices_
#if not np.all(indices==indices__):
# import ipdb; ipdb.set_trace()
#except:
# indices = np.indices(self._realshape_, dtype=int)
# indices = indices[(slice(None),)+slice_index]
# indices = np.rollaxis(indices, 0, indices.ndim)
return indices