def symmetry_normalised_sites(self, scaled_positions,
map_to_unitcell=True):
"""Returns an array of same size as *scaled_positions*,
containing the corresponding symmetry-equivalent sites of
lowest indices.
If *map_to_unitcell* is true, the returned positions are all
mapped into the unit cell, i.e. lattice translations are
included as symmetry operator.
Example:
>>> from ase.lattice.spacegroup import Spacegroup
>>> sg = Spacegroup(225) # fcc
>>> sg.symmetry_normalised_sites([[0.0, 0.5, 0.5], [1.0, 1.0, 0.0]])
array([[ 0., 0., 0.],
[ 0., 0., 0.]])
"""
scaled = np.array(scaled_positions, ndmin=2)
normalised = np.empty(scaled.shape, np.float)
rot, trans = self.get_op()
for i, pos in enumerate(scaled):
sympos = np.dot(rot, pos) + trans
if map_to_unitcell:
# Must be done twice, see the scaled_positions.py test
sympos %= 1.0
sympos %= 1.0
j = np.lexsort(sympos.T)[0]
normalised[i,:] = sympos[j]
return normalised
python类lexsort()的实例源码
def unique_sites(self, scaled_positions, symprec=1e-3, output_mask=False,
map_to_unitcell=True):
"""Returns a subset of *scaled_positions* containing only the
symmetry-unique positions. If *output_mask* is True, a boolean
array masking the subset is also returned.
If *map_to_unitcell* is true, all sites are first mapped into
the unit cell making e.g. [0, 0, 0] and [1, 0, 0] equivalent.
Example:
>>> from ase.lattice.spacegroup import Spacegroup
>>> sg = Spacegroup(225) # fcc
>>> sg.unique_sites([[0.0, 0.0, 0.0],
... [0.5, 0.5, 0.0],
... [1.0, 0.0, 0.0],
... [0.5, 0.0, 0.0]])
array([[ 0. , 0. , 0. ],
[ 0.5, 0. , 0. ]])
"""
scaled = np.array(scaled_positions, ndmin=2)
symnorm = self.symmetry_normalised_sites(scaled, map_to_unitcell)
perm = np.lexsort(symnorm.T)
iperm = perm.argsort()
xmask = np.abs(np.diff(symnorm[perm], axis=0)).max(axis=1) > symprec
mask = np.concatenate(([True], xmask))
imask = mask[iperm]
if output_mask:
return scaled[imask], imask
else:
return scaled[imask]
def test_lexsort_zero_dim(self, xp):
a = testing.shaped_random((), xp)
return xp.lexsort(a)
def test_lexsort_one_dim(self, xp):
a = testing.shaped_random((2,), xp)
return xp.lexsort(a)
def test_lexsort_two_dim(self, xp):
a = xp.array([[9, 4, 0, 4, 0, 2, 1],
[1, 5, 1, 4, 3, 4, 4]]) # from numpy.lexsort example
return xp.lexsort(a)
def test_lexsort_three_or_more_dim(self):
a = testing.shaped_random((2, 10, 10), cupy)
with self.assertRaises(NotImplementedError):
return cupy.lexsort(a)
# Test dtypes
def test_lexsort_unsupported_dtype(self, dtype):
a = testing.shaped_random((2, 10), cupy, dtype)
with self.assertRaises(TypeError):
return cupy.lexsort(a)
def _get_id_seq(pos, arr_num):
# from fractions import Fraction
# transfer the atom position into >=0 and <=1
pos = np.around(pos, decimals=10)
func_tofrac = np.vectorize(lambda x: round((x % 1), 3))
o_pos = func_tofrac(pos)
# round_o_pos = np.around(o_pos, decimals=3)
# z, y, x = round_o_pos[:, 2], round_o_pos[:, 1], round_o_pos[:, 0]
z, y, x = o_pos[:, 2], o_pos[:, 1], o_pos[:, 0]
ind_sort = np.lexsort((z, y, x))
id_seq = str(arr_num[ind_sort])
return id_seq
def sort_edges(self): # can slow down rendering
self.isorted_edges = numpy.lexsort((self.edge_original_order.argsort(), self.edge_orders))
self.invalidated += 1
def _sort(self, expfact):
# keep unique vertices only by creating a set and sort first on x then on y coordinate
# using rather slow python sort but couldn;t wrap my head around np.lexsort
verts = sorted(list({ tuple(t) for t in self.center[::] }))
x = set(c[0] for c in verts)
y = set(c[1] for c in verts)
nx = len(x)
ny = len(y)
self.minx = min(x)
self.maxx = max(x)
self.miny = min(y)
self.maxy = max(y)
xscale = (self.maxx-self.minx)/(nx-1)
yscale = (self.maxy-self.miny)/(ny-1)
# note: a purely flat plane cannot be scaled
if (yscale != 0.0) and (abs(xscale/yscale) - 1.0 > 1e-3):
raise ValueError("Mesh spacing not square %d x %d %.4f x %4.f"%(nx,ny,xscale,yscale))
self.zscale = 1.0
if abs(yscale) > 1e-6 :
self.zscale = 1.0/yscale
# keep just the z-values and null any ofsset
# we might catch a reshape error that will occur if nx*ny != # of vertices (if we are not dealing with a heightfield but with a mesh with duplicate x,y coords, like an axis aligned cube
self.center = np.array([c[2] for c in verts],dtype=np.single).reshape(nx,ny)
self.center = (self.center-np.amin(self.center))*self.zscale
if self.rainmap is not None:
rmscale = np.max(self.center)
self.rainmap = expfact + (1-expfact)*(self.center/rmscale)
def load_targets(shapefile, targetfield):
"""
Loads the shapefile onto node 0 then distributes it across all
available nodes
"""
if mpiops.chunk_index == 0:
lonlat, vals, othervals = load_shapefile(shapefile, targetfield)
# sort by y then x
ordind = np.lexsort(lonlat.T)
vals = vals[ordind]
lonlat = lonlat[ordind]
for k, v in othervals.items():
othervals[k] = v[ordind]
lonlat = np.array_split(lonlat, mpiops.chunks)
vals = np.array_split(vals, mpiops.chunks)
split_othervals = {k: np.array_split(v, mpiops.chunks)
for k, v in othervals.items()}
othervals = [{k: v[i] for k, v in split_othervals.items()}
for i in range(mpiops.chunks)]
else:
lonlat, vals, othervals = None, None, None
lonlat = mpiops.comm.scatter(lonlat, root=0)
vals = mpiops.comm.scatter(vals, root=0)
othervals = mpiops.comm.scatter(othervals, root=0)
log.info("Node {} has been assigned {} targets".format(mpiops.chunk_index,
lonlat.shape[0]))
targets = Targets(lonlat, vals, othervals=othervals)
return targets
def sort_rows_by_icol1(self,inarray):
idex=np.lexsort([inarray[:,0],inarray[:,1]])
a_sort=inarray[idex,:]
return a_sort
def _sort_contours(self, index, times, freqs, salience):
"""Sort contours by index and time.
Parameters
----------
index : np.array
array of contour numbers
times : np.array
array of contour times
freqs : np.array
array of contour frequencies
salience : np.array
array of contour salience values
Returns
-------
index_sorted : np.array
Pruned array of contour numbers
times_sorted : np.array
Pruned array of contour times
freqs_sorted : np.array
Pruned array of contour frequencies
salience_sorted : np.array
Pruned array of contour salience values
"""
sort_idx = np.lexsort((times, index))
return (
index[sort_idx], times[sort_idx], freqs[sort_idx],
salience[sort_idx]
)
###############################################################################
def polynomial(context, n_degrees=2):
# From sklearn.preprocessing.PolynomialFeatures
# Find permutations/combinations which add to degree or less
context = np.asarray(context)
n_features = context.shape[0]
powers = itertools.product(*(range(n_degrees + 1)
for i in range(n_features)))
powers = np.array([c for c in powers if 0 <= np.sum(c) <= n_degrees])
# Sort so that the order of the powers makes sense
i = np.lexsort(np.vstack([powers.T, powers.sum(axis=1)]))
powers = powers[i][::-1]
return (context ** powers).prod(-1)
def prepare_sparse_cost(shape, cc, ii, jj, cost_limit):
'''
Transform the given sparse matrix extending it to a square sparse matrix.
Parameters
==========
shape: tuple
- cost matrix shape
(cc, ii, jj): tuple of floats, ints, ints)
- cost matrix in COO format, see [1]
cost_limit: float
Returns
=======
cc, ii, kk
- extended square cost matrix in CSR format
1. https://en.wikipedia.org/wiki/Sparse_matrix
'''
assert cost_limit < np.inf
n, m = shape
cc_ = np.r_[cc, [cost_limit] * n,
[cost_limit] * m, [0] * len(cc)]
ii_ = np.r_[ii, np.arange(0, n, dtype=np.uint32),
np.arange(n, n + m, dtype=np.uint32), n + jj]
jj_ = np.r_[jj, np.arange(m, n + m, dtype=np.uint32),
np.arange(0, m, dtype=np.uint32), m + ii]
order = np.lexsort((jj_, ii_))
cc_ = cc_[order]
kk_ = jj_[order]
ii_ = ii_.astype(np.intp)
ii_ = np.bincount(ii_, minlength=shape[0]-1)
ii_ = np.r_[[0], np.cumsum(ii_)]
ii_ = ii_.astype(np.uint32)
assert ii_[-1] == 2 * len(cc) + n + m
return cc_, ii_, kk_
def test_lexsort(self,level=rlevel):
# Lexsort memory error
v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
assert_equal(np.lexsort(v), 0)
def test_lexsort_invalid_sequence(self):
# Issue gh-4123
class BuggySequence(object):
def __len__(self):
return 4
def __getitem__(self, key):
raise KeyError
assert_raises(KeyError, np.lexsort, BuggySequence())
def test_mem_lexsort_strings(self, level=rlevel):
# Ticket #298
lst = ['abc', 'cde', 'fgh']
np.lexsort((lst,))
def test_lexsort_buffer_length(self):
# Ticket #1217, don't segfault.
a = np.ones(100, dtype=np.int8)
b = np.ones(100, dtype=np.int32)
i = np.lexsort((a[::-1], b))
assert_equal(i, np.arange(100, dtype=np.int))