index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
21,104 | tfields.core | cleaned |
Args:
stale (bool): remove stale vertices
duplicates (bool): replace duplicate vertices by originals
Examples:
>>> import numpy as np
>>> import tfields
>>> mp1 = tfields.TensorFields([[0, 1, 2], [3, 4, 5]],
... *zip([1,2,3,4,5], [6,7,8,9,0]))
>>> mp2 = tfields.TensorFields([[0], [3]])
>>> tm = tfields.TensorMaps([[0,0,0], [1,1,1], [2,2,2], [0,0,0],
... [3,3,3], [4,4,4], [5,6,7]],
... maps=[mp1, mp2])
>>> c = tm.cleaned()
>>> assert c.equal([[0., 0., 0.],
... [1., 1., 1.],
... [2., 2., 2.],
... [3., 3., 3.],
... [4., 4., 4.]])
>>> assert np.array_equal(c.maps[3], [[0, 1, 2], [0, 3, 4]])
>>> assert np.array_equal(c.maps[1], [[0], [0]])
Returns:
copy of self without stale vertices and duplicat points (depending
on arguments)
| def cleaned(self, stale=True, duplicates=True):
"""
Args:
stale (bool): remove stale vertices
duplicates (bool): replace duplicate vertices by originals
Examples:
>>> import numpy as np
>>> import tfields
>>> mp1 = tfields.TensorFields([[0, 1, 2], [3, 4, 5]],
... *zip([1,2,3,4,5], [6,7,8,9,0]))
>>> mp2 = tfields.TensorFields([[0], [3]])
>>> tm = tfields.TensorMaps([[0,0,0], [1,1,1], [2,2,2], [0,0,0],
... [3,3,3], [4,4,4], [5,6,7]],
... maps=[mp1, mp2])
>>> c = tm.cleaned()
>>> assert c.equal([[0., 0., 0.],
... [1., 1., 1.],
... [2., 2., 2.],
... [3., 3., 3.],
... [4., 4., 4.]])
>>> assert np.array_equal(c.maps[3], [[0, 1, 2], [0, 3, 4]])
>>> assert np.array_equal(c.maps[1], [[0], [0]])
Returns:
copy of self without stale vertices and duplicat points (depending
on arguments)
"""
if not stale and not duplicates:
inst = self.copy()
if stale:
# remove stale vertices i.e. those that are not referred by any
# map
remove_mask = self.stale()
inst = self.removed(remove_mask)
if duplicates: # pylint: disable=too-many-nested-blocks
# remove duplicates in order to not have any artificial separations
if not stale:
# we have not yet made a copy but want to work on inst
inst = self.copy()
remove_mask = np.full(inst.shape[0], False, dtype=bool)
duplicates = tfields.lib.util.duplicates(inst, axis=0)
tensor_indices = np.arange(inst.shape[0])
duplicates_mask = duplicates != tensor_indices
if duplicates_mask.any():
# redirect maps. Note: work on inst.maps instead of
# self.maps in case stale vertices where removed
keys = tensor_indices[duplicates_mask]
values = duplicates[duplicates_mask]
for map_dim in inst.maps:
tfields.lib.sets.remap(
inst.maps[map_dim], keys, values, inplace=True
)
# mark duplicates for removal
remove_mask[keys] = True
if remove_mask.any():
# prevent another copy
inst = inst.removed(remove_mask)
return inst
| (self, stale=True, duplicates=True) |
21,105 | tfields.core | closest |
Args:
other (Tensors): closest points to what? -> other
**kwargs: forwarded to scipy.spatial.cKDTree.query
Returns:
array shape(len(self)): Indices of other points that are closest to
own points
Examples:
>>> import tfields
>>> m = tfields.Tensors([[1,0,0], [0,1,0], [1,1,0], [0,0,1],
... [1,0,1]])
>>> p = tfields.Tensors([[1.1,1,0], [0,0.1,1], [1,0,1.1]])
>>> p.closest(m)
array([2, 3, 4])
| def closest(self, other, **kwargs):
"""
Args:
other (Tensors): closest points to what? -> other
**kwargs: forwarded to scipy.spatial.cKDTree.query
Returns:
array shape(len(self)): Indices of other points that are closest to
own points
Examples:
>>> import tfields
>>> m = tfields.Tensors([[1,0,0], [0,1,0], [1,1,0], [0,0,1],
... [1,0,1]])
>>> p = tfields.Tensors([[1.1,1,0], [0,0.1,1], [1,0,1.1]])
>>> p.closest(m)
array([2, 3, 4])
"""
with other.tmp_transform(self.coord_sys):
# balanced_tree option gives huge speedup!
kd_tree = scipy.spatial.cKDTree( # noqa: E501 pylint: disable=no-member
other, 1000, balanced_tree=False
)
res = kd_tree.query(self, **kwargs)
array = res[1]
return array
| (self, other, **kwargs) |
21,106 | tfields.core | contains |
Inspired by a speed argument @
stackoverflow.com/questions/14766194/testing-whether-a-numpy-array-contains-a-given-row
Examples:
>>> import tfields
>>> p = tfields.Tensors([[1,2,3], [4,5,6], [6,7,8]])
>>> p.contains([4,5,6])
True
| def contains(self, other):
"""
Inspired by a speed argument @
stackoverflow.com/questions/14766194/testing-whether-a-numpy-array-contains-a-given-row
Examples:
>>> import tfields
>>> p = tfields.Tensors([[1,2,3], [4,5,6], [6,7,8]])
>>> p.contains([4,5,6])
True
"""
return any(self.equal(other, return_bool=False).all(1))
| (self, other) |
21,107 | tfields.core | copy |
The standard ndarray copy does not copy slots. Correct for this.
Examples:
>>> import tfields
>>> m = tfields.TensorMaps(
... [[1,2,3], [3,3,3], [0,0,0], [5,6,7]],
... [[1], [3], [0], [5]],
... maps=[
... ([[0, 1, 2], [1, 2, 3]], [21, 42]),
... [[1]],
... [[0, 1, 2, 3]]
... ])
>>> mc = m.copy()
>>> mc.equal(m)
True
>>> mc is m
False
>>> mc.fields is m.fields
False
>>> mc.fields[0] is m.fields[0]
False
>>> mc.maps[3].fields[0] is m.maps[3].fields[0]
False
| def copy(self, **kwargs): # pylint: disable=arguments-differ
"""
The standard ndarray copy does not copy slots. Correct for this.
Examples:
>>> import tfields
>>> m = tfields.TensorMaps(
... [[1,2,3], [3,3,3], [0,0,0], [5,6,7]],
... [[1], [3], [0], [5]],
... maps=[
... ([[0, 1, 2], [1, 2, 3]], [21, 42]),
... [[1]],
... [[0, 1, 2, 3]]
... ])
>>> mc = m.copy()
>>> mc.equal(m)
True
>>> mc is m
False
>>> mc.fields is m.fields
False
>>> mc.fields[0] is m.fields[0]
False
>>> mc.maps[3].fields[0] is m.maps[3].fields[0]
False
"""
if kwargs:
raise NotImplementedError(
"Copying with arguments {kwargs} not yet supported"
)
# works with __reduce__ / __setstate__
return deepcopy(self)
| (self, **kwargs) |
21,108 | tfields.core | cov_eig |
Calculate the covariance eigenvectors with lenghts of eigenvalues
Args:
weights (np.array | int | None): index to scalars to weight with
| def cov_eig(self, weights=None):
"""
Calculate the covariance eigenvectors with lenghts of eigenvalues
Args:
weights (np.array | int | None): index to scalars to weight with
"""
# weights = self.getNormedWeightedAreas(weights=weights)
weights = self._weights(weights)
cov = np.cov(self.T, ddof=0, aweights=weights)
# calculate eigenvalues and eigenvectors of covariance
evalfs, evecs = np.linalg.eigh(cov)
idx = evalfs.argsort()[::-1]
evalfs = evalfs[idx]
evecs = evecs[:, idx]
res = np.concatenate((evecs, evalfs.reshape(1, 3)))
return res.T.reshape(
12,
)
| (self, weights=None) |
21,109 | tfields.mesh_3d | cut |
cut method for Mesh3D.
Args:
expression (sympy logical expression | Mesh3D):
sympy locical expression: Sympy expression that defines planes
in 3D
Mesh3D: A mesh3D will be interpreted as a template, i.e. a
fast instruction of how to cut the triangles.
It is the second part of the tuple, returned by a previous
cut with a sympy locial expression with 'return_template=True'.
We use the vertices and maps of the Mesh as the skelleton of
the returned mesh. The fields are mapped according to
indices in the template.maps[i].fields.
coord_sys (coordinate system to cut in):
at_intersection (str): instruction on what to do, when a cut will intersect a triangle.
Options: 'remove' (Default) - remove the faces that are on the edge
'keep' - keep the faces that are on the edge
'split' - Create new triangles that make up the old one.
return_template (bool): If True: return the template
to redo the same cut fast
Examples:
define the cut
>>> import numpy as np
>>> import tfields
>>> from sympy.abc import x,y,z
>>> cut_expr = x > 1.5
>>> m = tfields.Mesh3D.grid((0, 3, 4),
... (0, 3, 4),
... (0, 0, 1))
>>> m.fields.append(tfields.Tensors(np.linspace(0, len(m) - 1,
... len(m))))
>>> m.maps[3].fields.append(
... tfields.Tensors(np.linspace(0,
... len(m.maps[3]) - 1,
... len(m.maps[3]))))
>>> mNew = m.cut(cut_expr)
>>> len(mNew)
8
>>> mNew.nfaces()
6
>>> float(mNew[:, 0].min())
2.0
Cutting with the 'keep' option will leave triangles on the edge
untouched:
>>> m_keep = m.cut(cut_expr, at_intersection='keep')
>>> float(m_keep[:, 0].min())
1.0
>>> m_keep.nfaces()
12
Cutting with the 'split' option will create new triangles on the edge:
>>> m_split = m.cut(cut_expr, at_intersection='split')
>>> float(m_split[:, 0].min())
1.5
>>> len(m_split)
15
>>> m_split.nfaces()
15
Cut with 'return_template=True' will return the exact same mesh but
additionally an instruction to conduct the exact same cut fast (template)
>>> m_split_2, template = m.cut(cut_expr, at_intersection='split',
... return_template=True)
>>> m_split_template = m.cut(template)
>>> assert m_split.equal(m_split_2, equal_nan=True)
>>> assert m_split.equal(m_split_template, equal_nan=True)
>>> assert len(template.fields) == 1
>>> assert len(m_split.fields) == 1
>>> assert len(m_split_template.fields) == 1
>>> assert m_split.fields[0].equal(
... list(range(8, 16)) + [np.nan] * 7, equal_nan=True)
>>> assert m_split_template.fields[0].equal(
... list(range(8, 16)) + [np.nan] * 7, equal_nan=True)
This seems irrelevant at first but consider, the map field or the
tensor field changes:
>>> m_altered_fields = m.copy()
>>> m_altered_fields[0] += 42
>>> assert not m_split.equal(m_altered_fields.cut(template))
>>> assert tfields.Tensors(m_split).equal(
... m_altered_fields.cut(template))
>>> assert tfields.Tensors(m_split.maps[3]).equal(
... m_altered_fields.cut(template).maps[3])
The cut expression may be a sympy.BooleanFunction:
>>> cut_expr_bool_fun = (x > 1.5) & (y < 1.5) & (y >0.2) & (z > -0.5)
>>> m_split_bool = m.cut(cut_expr_bool_fun,
... at_intersection='split')
Returns:
copy of cut mesh
* optional: template
| def cut(self, *args, **kwargs):
"""
cut method for Mesh3D.
Args:
expression (sympy logical expression | Mesh3D):
sympy locical expression: Sympy expression that defines planes
in 3D
Mesh3D: A mesh3D will be interpreted as a template, i.e. a
fast instruction of how to cut the triangles.
It is the second part of the tuple, returned by a previous
cut with a sympy locial expression with 'return_template=True'.
We use the vertices and maps of the Mesh as the skelleton of
the returned mesh. The fields are mapped according to
indices in the template.maps[i].fields.
coord_sys (coordinate system to cut in):
at_intersection (str): instruction on what to do, when a cut will intersect a triangle.
Options: 'remove' (Default) - remove the faces that are on the edge
'keep' - keep the faces that are on the edge
'split' - Create new triangles that make up the old one.
return_template (bool): If True: return the template
to redo the same cut fast
Examples:
define the cut
>>> import numpy as np
>>> import tfields
>>> from sympy.abc import x,y,z
>>> cut_expr = x > 1.5
>>> m = tfields.Mesh3D.grid((0, 3, 4),
... (0, 3, 4),
... (0, 0, 1))
>>> m.fields.append(tfields.Tensors(np.linspace(0, len(m) - 1,
... len(m))))
>>> m.maps[3].fields.append(
... tfields.Tensors(np.linspace(0,
... len(m.maps[3]) - 1,
... len(m.maps[3]))))
>>> mNew = m.cut(cut_expr)
>>> len(mNew)
8
>>> mNew.nfaces()
6
>>> float(mNew[:, 0].min())
2.0
Cutting with the 'keep' option will leave triangles on the edge
untouched:
>>> m_keep = m.cut(cut_expr, at_intersection='keep')
>>> float(m_keep[:, 0].min())
1.0
>>> m_keep.nfaces()
12
Cutting with the 'split' option will create new triangles on the edge:
>>> m_split = m.cut(cut_expr, at_intersection='split')
>>> float(m_split[:, 0].min())
1.5
>>> len(m_split)
15
>>> m_split.nfaces()
15
Cut with 'return_template=True' will return the exact same mesh but
additionally an instruction to conduct the exact same cut fast (template)
>>> m_split_2, template = m.cut(cut_expr, at_intersection='split',
... return_template=True)
>>> m_split_template = m.cut(template)
>>> assert m_split.equal(m_split_2, equal_nan=True)
>>> assert m_split.equal(m_split_template, equal_nan=True)
>>> assert len(template.fields) == 1
>>> assert len(m_split.fields) == 1
>>> assert len(m_split_template.fields) == 1
>>> assert m_split.fields[0].equal(
... list(range(8, 16)) + [np.nan] * 7, equal_nan=True)
>>> assert m_split_template.fields[0].equal(
... list(range(8, 16)) + [np.nan] * 7, equal_nan=True)
This seems irrelevant at first but consider, the map field or the
tensor field changes:
>>> m_altered_fields = m.copy()
>>> m_altered_fields[0] += 42
>>> assert not m_split.equal(m_altered_fields.cut(template))
>>> assert tfields.Tensors(m_split).equal(
... m_altered_fields.cut(template))
>>> assert tfields.Tensors(m_split.maps[3]).equal(
... m_altered_fields.cut(template).maps[3])
The cut expression may be a sympy.BooleanFunction:
>>> cut_expr_bool_fun = (x > 1.5) & (y < 1.5) & (y >0.2) & (z > -0.5)
>>> m_split_bool = m.cut(cut_expr_bool_fun,
... at_intersection='split')
Returns:
copy of cut mesh
* optional: template
"""
return super().cut(*args, **kwargs)
| (self, *args, **kwargs) |
21,110 | tfields.core | disjoint_map |
Find the disjoint sets of map = self.maps[map_dim]
As an example, this method is interesting for splitting a mesh
consisting of seperate parts
Args:
map_dim (int): reference to map position
used like: self.maps[map_dim]
Returns:
Tuple(int, List(List(int))): map description(tuple): see self.parts
Examples:
>>> import tfields
>>> a = tfields.TensorMaps(
... [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]],
... maps=[[[0, 1, 2], [0, 2, 3]]])
>>> b = a.copy()
>>> b[:, 0] += 2
>>> m = tfields.TensorMaps.merged(a, b)
>>> mp_description = m.disjoint_map(3)
>>> parts = m.parts(mp_description)
>>> aa, ba = parts
>>> assert aa.maps[3].equal(ba.maps[3])
>>> assert aa.equal(a)
>>> assert ba.equal(b)
| def disjoint_map(self, map_dim):
"""
Find the disjoint sets of map = self.maps[map_dim]
As an example, this method is interesting for splitting a mesh
consisting of seperate parts
Args:
map_dim (int): reference to map position
used like: self.maps[map_dim]
Returns:
Tuple(int, List(List(int))): map description(tuple): see self.parts
Examples:
>>> import tfields
>>> a = tfields.TensorMaps(
... [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]],
... maps=[[[0, 1, 2], [0, 2, 3]]])
>>> b = a.copy()
>>> b[:, 0] += 2
>>> m = tfields.TensorMaps.merged(a, b)
>>> mp_description = m.disjoint_map(3)
>>> parts = m.parts(mp_description)
>>> aa, ba = parts
>>> assert aa.maps[3].equal(ba.maps[3])
>>> assert aa.equal(a)
>>> assert ba.equal(b)
"""
maps_list = tfields.lib.sets.disjoint_group_indices(self.maps[map_dim])
return (map_dim, maps_list)
| (self, map_dim) |
21,111 | tfields.mesh_3d | disjoint_parts |
Returns:
disjoint_parts(List(cls)), templates(List(cls))
>>> import tfields
>>> a = tfields.Mesh3D(
... [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]],
... maps=[[[0, 1, 2], [0, 2, 3]]])
>>> b = a.copy()
>>> b[:, 0] += 2
>>> m = tfields.Mesh3D.merged(a, b)
>>> parts = m.disjoint_parts()
>>> aa, ba = parts
>>> assert aa.maps[3].equal(ba.maps[3])
>>> assert aa.equal(a)
>>> assert ba.equal(b)
| def disjoint_parts(self, return_template=False):
"""
Returns:
disjoint_parts(List(cls)), templates(List(cls))
>>> import tfields
>>> a = tfields.Mesh3D(
... [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]],
... maps=[[[0, 1, 2], [0, 2, 3]]])
>>> b = a.copy()
>>> b[:, 0] += 2
>>> m = tfields.Mesh3D.merged(a, b)
>>> parts = m.disjoint_parts()
>>> aa, ba = parts
>>> assert aa.maps[3].equal(ba.maps[3])
>>> assert aa.equal(a)
>>> assert ba.equal(b)
"""
mp_description = self.disjoint_map(3)
parts = self.parts(mp_description)
if not return_template:
return parts
else:
templates = []
for i, part in enumerate(parts):
template = part.copy()
template.maps[3].fields = [tfields.Tensors(mp_description[1][i])]
templates.append(template)
return parts, templates
| (self, return_template=False) |
21,112 | tfields.core | distances |
Args:
other(Iterable)
**kwargs:
... is forwarded to scipy.spatial.distance.cdist
Examples:
>>> import tfields
>>> p = tfields.Tensors.grid((0, 2, 3j),
... (0, 2, 3j),
... (0, 0, 1j))
>>> p[4,2] = 1
>>> p.distances(p)[0,0]
0.0
>>> p.distances(p)[5,1]
1.4142135623730951
>>> p.distances([[0,1,2]])[-1][0] == 3
True
| def distances(self, other, **kwargs):
"""
Args:
other(Iterable)
**kwargs:
... is forwarded to scipy.spatial.distance.cdist
Examples:
>>> import tfields
>>> p = tfields.Tensors.grid((0, 2, 3j),
... (0, 2, 3j),
... (0, 0, 1j))
>>> p[4,2] = 1
>>> p.distances(p)[0,0]
0.0
>>> p.distances(p)[5,1]
1.4142135623730951
>>> p.distances([[0,1,2]])[-1][0] == 3
True
"""
if issubclass(type(other), Tensors) and self.coord_sys != other.coord_sys:
other = other.copy()
other.transform(self.coord_sys)
return scipy.spatial.distance.cdist(self, other, **kwargs)
| (self, other, **kwargs) |
21,113 | tfields.core | dot |
Computes the n-d dot product between self and other defined as in
`mathematica <https://reference.wolfram.com/legacy/v5/Built-inFunctions/
AdvancedDocumentation/LinearAlgebra/2.7.html>`_
by summing over the last dimension.
When self and b are both one-dimensional vectors, this is just the "usual" dot product;
when self and b are 2D matrices, this is matrix multiplication.
Note:
* This is not the same as the numpy.dot function.
Examples:
>>> import tfields
>>> import numpy as np
Scalar product by transposed dot product
>>> a = tfields.Tensors([[4, 0, 4]])
>>> b = tfields.Tensors([[10, 0, 0.5]])
>>> c = a.t.dot(b)
>>> assert c.equal([42])
>>> assert c.equal(np.dot(a[0], b[0]))
>>> assert c.rank == 0
To get the angle between a and b you now just need
>>> angle = np.arccos(c)
Matrix vector multiplication
>>> a = tfields.Tensors([[[1, 20, 0], [2, 18, 1], [1, 5, 10]]])
>>> b = tfields.Tensors([[1, 2, 3]])
>>> c = a.dot(b)
>>> assert c.equal([[41,41,41]])
TODO: generalize dot product to inner
# Matrix matrix multiplication can not be done like this. It requires
# >>> a = tfields.Tensors([[[1, 8], [2, 4]]])
# >>> b = tfields.Tensors([[[1, 2], [1/2, 1/4]]])
# >>> c = a.dot(b)
# >>> c
# >>> assert c.equal([[[5, 4], [4, 5]]])
TODO: handle types, fields and maps (which fields etc to choose for the output?)
| def dot(self, b, out=None):
# pylint:disable=line-too-long
"""
Computes the n-d dot product between self and other defined as in
`mathematica <https://reference.wolfram.com/legacy/v5/Built-inFunctions/
AdvancedDocumentation/LinearAlgebra/2.7.html>`_
by summing over the last dimension.
When self and b are both one-dimensional vectors, this is just the "usual" dot product;
when self and b are 2D matrices, this is matrix multiplication.
Note:
* This is not the same as the numpy.dot function.
Examples:
>>> import tfields
>>> import numpy as np
Scalar product by transposed dot product
>>> a = tfields.Tensors([[4, 0, 4]])
>>> b = tfields.Tensors([[10, 0, 0.5]])
>>> c = a.t.dot(b)
>>> assert c.equal([42])
>>> assert c.equal(np.dot(a[0], b[0]))
>>> assert c.rank == 0
To get the angle between a and b you now just need
>>> angle = np.arccos(c)
Matrix vector multiplication
>>> a = tfields.Tensors([[[1, 20, 0], [2, 18, 1], [1, 5, 10]]])
>>> b = tfields.Tensors([[1, 2, 3]])
>>> c = a.dot(b)
>>> assert c.equal([[41,41,41]])
TODO: generalize dot product to inner
# Matrix matrix multiplication can not be done like this. It requires
# >>> a = tfields.Tensors([[[1, 8], [2, 4]]])
# >>> b = tfields.Tensors([[[1, 2], [1/2, 1/4]]])
# >>> c = a.dot(b)
# >>> c
# >>> assert c.equal([[[5, 4], [4, 5]]])
TODO: handle types, fields and maps (which fields etc to choose for the output?)
"""
if out is not None:
raise NotImplementedError("performance feature 'out' not yet implemented")
return Tensors(np.einsum("t...i,t...i->t...", self, b))
| (self, b, out=None) |
21,114 | tfields.core | epsilon_neighbourhood |
Returns:
indices for those sets of points that lie within epsilon around the
other
Examples:
Create mesh grid with one extra point that will have 8 neighbours
within epsilon
>>> import tfields
>>> p = tfields.Tensors.grid((0, 1, 2j),
... (0, 1, 2j),
... (0, 1, 2j))
>>> p = tfields.Tensors.merged(p, [[0.5, 0.5, 0.5]])
>>> [len(en) for en in p.epsilon_neighbourhood(0.9)]
[2, 2, 2, 2, 2, 2, 2, 2, 9]
| def epsilon_neighbourhood(self, epsilon):
"""
Returns:
indices for those sets of points that lie within epsilon around the
other
Examples:
Create mesh grid with one extra point that will have 8 neighbours
within epsilon
>>> import tfields
>>> p = tfields.Tensors.grid((0, 1, 2j),
... (0, 1, 2j),
... (0, 1, 2j))
>>> p = tfields.Tensors.merged(p, [[0.5, 0.5, 0.5]])
>>> [len(en) for en in p.epsilon_neighbourhood(0.9)]
[2, 2, 2, 2, 2, 2, 2, 2, 9]
"""
indices = np.arange(self.shape[0])
dists = self.distances(self) # this takes long
dists_in_epsilon = dists <= epsilon
indices = [indices[die] for die in dists_in_epsilon] # this takes long
return indices
| (self, epsilon) |
21,115 | tfields.core | equal |
Test, whether the instance has the same content as other.
Args:
other (iterable)
optional:
see TensorFields.equal
Examples:
>>> import tfields
>>> maps = [tfields.TensorFields([[1]], [42])]
>>> tm = tfields.TensorMaps(maps[0], maps=maps)
# >>> assert tm.equal(tm)
>>> cp = tm.copy()
# >>> assert tm.equal(cp)
>>> cp.maps[1].fields[0] = -42
>>> assert tm.maps[1].fields[0] == 42
>>> assert not tm.equal(cp)
| def equal(self, other, **kwargs):
"""
Test, whether the instance has the same content as other.
Args:
other (iterable)
optional:
see TensorFields.equal
Examples:
>>> import tfields
>>> maps = [tfields.TensorFields([[1]], [42])]
>>> tm = tfields.TensorMaps(maps[0], maps=maps)
# >>> assert tm.equal(tm)
>>> cp = tm.copy()
# >>> assert tm.equal(cp)
>>> cp.maps[1].fields[0] = -42
>>> assert tm.maps[1].fields[0] == 42
>>> assert not tm.equal(cp)
"""
if not issubclass(type(other), Tensors):
return super(TensorMaps, self).equal(other, **kwargs)
with other.tmp_transform(self.coord_sys):
mask = super(TensorMaps, self).equal(other, **kwargs)
if issubclass(type(other), TensorMaps):
mask &= self.maps.equal(other.maps, **kwargs)
return mask
| (self, other, **kwargs) |
21,116 | tfields.core | evalf |
Args:
expression (sympy logical expression)
coord_sys (str): coord_sys to evalfuate the expression in.
Returns:
np.ndarray: mask of dtype bool with lenght of number of points in
self. This array is True, where expression evalfuates True.
Examples:
>>> import tfields
>>> import numpy as np
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> np.array_equal(p.evalf(x > 0),
... [True, True, True, False, True, False])
True
>>> np.array_equal(p.evalf(x >= 0),
... [True, True, True, False, True, True])
True
And combination
>>> np.array_equal(p.evalf((x > 0) & (y < 3)),
... [True, False, True, False, True, False])
True
Or combination
>>> np.array_equal(p.evalf((x > 0) | (y > 3)),
... [True, True, True, False, True, False])
True
| def evalf(self, expression=None, coord_sys=None):
"""
Args:
expression (sympy logical expression)
coord_sys (str): coord_sys to evalfuate the expression in.
Returns:
np.ndarray: mask of dtype bool with lenght of number of points in
self. This array is True, where expression evalfuates True.
Examples:
>>> import tfields
>>> import numpy as np
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> np.array_equal(p.evalf(x > 0),
... [True, True, True, False, True, False])
True
>>> np.array_equal(p.evalf(x >= 0),
... [True, True, True, False, True, True])
True
And combination
>>> np.array_equal(p.evalf((x > 0) & (y < 3)),
... [True, False, True, False, True, False])
True
Or combination
>>> np.array_equal(p.evalf((x > 0) | (y > 3)),
... [True, True, True, False, True, False])
True
"""
coords = sympy.symbols("x y z")
with self.tmp_transform(coord_sys or self.coord_sys):
mask = tfields.evalf(np.array(self), expression, coords=coords)
return mask
| (self, expression=None, coord_sys=None) |
21,117 | tfields.mesh_3d | in_faces |
Check whether points lie within triangles with Barycentric Technique
see Triangles3D.in_triangles. If multiple requests are done on huge meshes,
this can be hugely optimized by requesting the property
self.tree or setting it to self.tree = <saved tree> before calling in_faces.
| def in_faces(self, points, delta, **kwargs):
"""
Check whether points lie within triangles with Barycentric Technique
see Triangles3D.in_triangles. If multiple requests are done on huge meshes,
this can be hugely optimized by requesting the property
self.tree or setting it to self.tree = <saved tree> before calling in_faces.
"""
key = "mesh_tree"
if hasattr(self, "_cache") and key in self._cache:
log = logging.getLogger()
log.info("Using cached decision tree to speed up point - face mapping.")
indices = self.tree.in_faces(points, delta, **kwargs)
else:
indices = self.triangles().in_triangles(points, delta, **kwargs)
return indices
| (self, points, delta, **kwargs) |
21,118 | tfields.core | index |
Args:
tensor
Returns:
int: index of tensor occuring
| def index(self, tensor, **kwargs):
"""
Args:
tensor
Returns:
int: index of tensor occuring
"""
indices = self.indices(tensor, **kwargs)
if not indices:
return None
if len(indices) == 1:
return indices[0]
raise ValueError("Multiple occurences of value {}".format(tensor))
| (self, tensor, **kwargs) |
21,119 | tfields.core | indices |
Returns:
list of int: indices of tensor occuring
Examples:
Rank 1 Tensors
>>> import tfields
>>> p = tfields.Tensors([[1,2,3], [4,5,6], [6,7,8], [4,5,6],
... [4.1, 5, 6]])
>>> p.indices([4,5,6])
array([1, 3])
>>> p.indices([4,5,6.1], rtol=1e-5, atol=1e-1)
array([1, 3, 4])
Rank 0 Tensors
>>> p = tfields.Tensors([2, 3, 6, 3.01])
>>> p.indices(3)
array([1])
>>> p.indices(3, rtol=1e-5, atol=1e-1)
array([1, 3])
| def indices(self, tensor, rtol=None, atol=None):
"""
Returns:
list of int: indices of tensor occuring
Examples:
Rank 1 Tensors
>>> import tfields
>>> p = tfields.Tensors([[1,2,3], [4,5,6], [6,7,8], [4,5,6],
... [4.1, 5, 6]])
>>> p.indices([4,5,6])
array([1, 3])
>>> p.indices([4,5,6.1], rtol=1e-5, atol=1e-1)
array([1, 3, 4])
Rank 0 Tensors
>>> p = tfields.Tensors([2, 3, 6, 3.01])
>>> p.indices(3)
array([1])
>>> p.indices(3, rtol=1e-5, atol=1e-1)
array([1, 3])
"""
self_array, other_array = np.asarray(self), np.asarray(tensor)
if rtol is None and atol is None:
equal_method = np.equal
else:
equal_method = lambda a, b: np.isclose(a, b, rtol=rtol, atol=atol) # NOQA
# inspired by
# https://stackoverflow.com/questions/19228295/find-ordered-vector-in-numpy-array
if self.rank == 0:
indices = np.where(equal_method((self_array - other_array), 0))[0]
elif self.rank == 1:
indices = np.where(
np.all(equal_method((self_array - other_array), 0), axis=1)
)[0]
else:
raise NotImplementedError()
return indices
| (self, tensor, rtol=None, atol=None) |
21,120 | tfields.core | keep |
Return copy of self with vertices where keep_condition is True
Copy because self is immutable
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.TensorMaps(
... [[0,0,0], [1,1,1], [2,2,2], [0,0,0],
... [3,3,3], [4,4,4], [5,5,5]],
... maps=[tfields.TensorFields([[0, 1, 2], [0, 1, 3],
... [3, 4, 5], [3, 4, 1],
... [3, 4, 6]],
... [1, 3, 5, 7, 9],
... [2, 4, 6, 8, 0])])
>>> c = m.removed([True, True, True, False, False, False, False])
>>> c.equal([[0, 0, 0],
... [3, 3, 3],
... [4, 4, 4],
... [5, 5, 5]])
True
>>> assert c.maps[3].equal(np.array([[0, 1, 2], [0, 1, 3]]))
>>> assert c.maps[3].fields[0].equal([5, 9])
>>> assert c.maps[3].fields[1].equal([6, 0])
| def keep(self, keep_condition):
"""
Return copy of self with vertices where keep_condition is True
Copy because self is immutable
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.TensorMaps(
... [[0,0,0], [1,1,1], [2,2,2], [0,0,0],
... [3,3,3], [4,4,4], [5,5,5]],
... maps=[tfields.TensorFields([[0, 1, 2], [0, 1, 3],
... [3, 4, 5], [3, 4, 1],
... [3, 4, 6]],
... [1, 3, 5, 7, 9],
... [2, 4, 6, 8, 0])])
>>> c = m.removed([True, True, True, False, False, False, False])
>>> c.equal([[0, 0, 0],
... [3, 3, 3],
... [4, 4, 4],
... [5, 5, 5]])
True
>>> assert c.maps[3].equal(np.array([[0, 1, 2], [0, 1, 3]]))
>>> assert c.maps[3].fields[0].equal([5, 9])
>>> assert c.maps[3].fields[1].equal([6, 0])
"""
keep_condition = np.array(keep_condition)
return self[keep_condition]
| (self, keep_condition) |
21,121 | tfields.core | main_axes |
Returns:
Main Axes eigen-vectors
| def main_axes(self, weights=None):
"""
Returns:
Main Axes eigen-vectors
"""
# weights = self.getNormedWeightedAreas(weights=weights)
weights = self._weights(weights)
mean = np.array(self).mean(axis=0)
relative_coords = self - mean
cov = np.cov(relative_coords.T, ddof=0, aweights=weights)
# calculate eigenvalues and eigenvectors of covariance
evalfs, evecs = np.linalg.eigh(cov)
return (evecs * evalfs.T).T
| (self, weights=None) |
21,122 | tfields.core | min_dists |
Args:
other(array | None): if None: closest distance to self
**kwargs:
memory_saving (bool): for very large array comparisons
default False
... rest is forwarded to scipy.spatial.distance.cdist
Returns:
np.array: minimal distances of self to other
Examples:
>>> import tfields
>>> import numpy as np
>>> p = tfields.Tensors.grid((0, 2, 3),
... (0, 2, 3),
... (0, 0, 1))
>>> p[4,2] = 1
>>> dMin = p.min_dists()
>>> expected = [1] * 9
>>> expected[4] = np.sqrt(2)
>>> np.array_equal(dMin, expected)
True
>>> dMin2 = p.min_dists(memory_saving=True)
>>> bool((dMin2 == dMin).all())
True
| def min_dists(self, other=None, **kwargs):
"""
Args:
other(array | None): if None: closest distance to self
**kwargs:
memory_saving (bool): for very large array comparisons
default False
... rest is forwarded to scipy.spatial.distance.cdist
Returns:
np.array: minimal distances of self to other
Examples:
>>> import tfields
>>> import numpy as np
>>> p = tfields.Tensors.grid((0, 2, 3),
... (0, 2, 3),
... (0, 0, 1))
>>> p[4,2] = 1
>>> dMin = p.min_dists()
>>> expected = [1] * 9
>>> expected[4] = np.sqrt(2)
>>> np.array_equal(dMin, expected)
True
>>> dMin2 = p.min_dists(memory_saving=True)
>>> bool((dMin2 == dMin).all())
True
"""
memory_saving = kwargs.pop("memory_saving", False)
if other is None:
other = self
else:
raise NotImplementedError(
"Should be easy but make shure not to remove diagonal"
)
try:
if memory_saving:
raise MemoryError()
dists = self.distances(other, **kwargs)
return dists[dists > 0].reshape(dists.shape[0], -1).min(axis=1)
except MemoryError:
min_dists = np.empty(self.shape[0])
for i, point in enumerate(np.array(other)):
dists = self.distances([point], **kwargs)
min_dists[i] = dists[dists > 0].reshape(-1).min()
return min_dists
| (self, other=None, **kwargs) |
21,123 | tfields.core | mirror |
Reflect/Mirror the entries meeting <condition> at <coordinate> = 0
Args:
coordinate (int): coordinate index
Examples:
>>> import tfields
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
>>> p.mirror(1)
>>> assert p.equal([[1, -2, 3], [4, -5, 6], [1, -2, -6]])
multiple coordinates can be mirrored at the same time
i.e. a point mirrorion would be
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
>>> p.mirror([0,2])
>>> assert p.equal([[-1, 2, -3], [-4, 5, -6], [-1, 2., 6.]])
You can give a condition as mask or as str.
The mirroring will only be applied to the points meeting the
condition.
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> p.mirror([0, 2], y > 3)
>>> p.equal([[-1, 2, -3], [4, 5, 6], [-1, 2, 6]])
True
| def mirror(self, coordinate, condition=None):
"""
Reflect/Mirror the entries meeting <condition> at <coordinate> = 0
Args:
coordinate (int): coordinate index
Examples:
>>> import tfields
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
>>> p.mirror(1)
>>> assert p.equal([[1, -2, 3], [4, -5, 6], [1, -2, -6]])
multiple coordinates can be mirrored at the same time
i.e. a point mirrorion would be
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
>>> p.mirror([0,2])
>>> assert p.equal([[-1, 2, -3], [-4, 5, -6], [-1, 2., 6.]])
You can give a condition as mask or as str.
The mirroring will only be applied to the points meeting the
condition.
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> p.mirror([0, 2], y > 3)
>>> p.equal([[-1, 2, -3], [4, 5, 6], [-1, 2, 6]])
True
"""
if condition is None:
condition = np.array([True for i in range(len(self))])
elif isinstance(condition, sympy.Basic):
condition = self.evalf(condition)
if isinstance(coordinate, (list, tuple)):
for coord in coordinate:
self.mirror(coord, condition=condition)
elif isinstance(coordinate, int):
self[:, coordinate][condition] *= -1
else:
raise TypeError()
| (self, coordinate, condition=None) |
21,124 | tfields.core | moment |
Returns:
Moments of the distribution.
Args:
moment (int): n-th moment
Examples:
>>> import tfields
Skalars
>>> t = tfields.Tensors(range(1, 6))
>>> assert t.moment(1) == 0
>>> assert t.moment(1, weights=[-2, -1, 20, 1, 2]) == 0.5
>>> assert t.moment(2, weights=[0.25, 1, 17.5, 1, 0.25]) == 0.2
Vectors
>>> t = tfields.Tensors(list(zip(range(1, 6), range(1, 6))))
>>> assert tfields.Tensors([0.5, 0.5]).equal(
... t.moment(1, weights=[-2, -1, 20, 1, 2]))
>>> assert tfields.Tensors([1. , 0.5]).equal(
... t.moment(1, weights=list(zip([-2, -1, 10, 1, 2],
... [-2, -1, 20, 1, 2]))))
| def moment(self, moment, weights=None):
"""
Returns:
Moments of the distribution.
Args:
moment (int): n-th moment
Examples:
>>> import tfields
Skalars
>>> t = tfields.Tensors(range(1, 6))
>>> assert t.moment(1) == 0
>>> assert t.moment(1, weights=[-2, -1, 20, 1, 2]) == 0.5
>>> assert t.moment(2, weights=[0.25, 1, 17.5, 1, 0.25]) == 0.2
Vectors
>>> t = tfields.Tensors(list(zip(range(1, 6), range(1, 6))))
>>> assert tfields.Tensors([0.5, 0.5]).equal(
... t.moment(1, weights=[-2, -1, 20, 1, 2]))
>>> assert tfields.Tensors([1. , 0.5]).equal(
... t.moment(1, weights=list(zip([-2, -1, 10, 1, 2],
... [-2, -1, 20, 1, 2]))))
"""
array = tfields.lib.stats.moment(self, moment, weights=weights)
if self.rank == 0: # scalar
array = [array]
return Tensors(array, coord_sys=self.coord_sys)
| (self, moment, weights=None) |
21,125 | tfields.mesh_3d | nfaces | null | def nfaces(self):
return self.faces.shape[0]
| (self) |
21,126 | tfields.core | norm |
Calculate the norm up to rank 2
Args:
See numpy.linal.norm except redefinition in axis
axis: by default omitting first axis
Examples:
>>> import tfields
>>> a = tfields.Tensors([[1, 0, 0]])
>>> assert a.norm().equal([1])
| def norm(self, ord=None, axis=None, keepdims=False):
"""
Calculate the norm up to rank 2
Args:
See numpy.linal.norm except redefinition in axis
axis: by default omitting first axis
Examples:
>>> import tfields
>>> a = tfields.Tensors([[1, 0, 0]])
>>> assert a.norm().equal([1])
"""
if axis is None:
axis = tuple(range(self.ndim)[1:])
return Tensors(np.linalg.norm(self, ord=ord, axis=axis, keepdims=keepdims))
| (self, ord=None, axis=None, keepdims=False) |
21,127 | tfields.core | normalized |
Return the self / norm(self)
Args:
forwarded to :meth:norm
Examples:
>>> import tfields
>>> a = tfields.Tensors([[1, 4, 3]])
>>> assert not a.norm().equal([1])
>>> a = a.normalized()
>>> assert a.norm().equal([1])
>>> a = tfields.Tensors([[1, 0, 0],
... [0, 2, 0],
... [0, 0, 3]])
>>> assert a.norm().equal([1, 2, 3])
>>> a = a.normalized()
>>> assert a.equal([
... [1, 0, 0],
... [0, 1, 0],
... [0, 0, 1],
... ])
>>> assert a.norm().equal([1, 1, 1])
| def normalized(self, *args, **kwargs):
"""
Return the self / norm(self)
Args:
forwarded to :meth:norm
Examples:
>>> import tfields
>>> a = tfields.Tensors([[1, 4, 3]])
>>> assert not a.norm().equal([1])
>>> a = a.normalized()
>>> assert a.norm().equal([1])
>>> a = tfields.Tensors([[1, 0, 0],
... [0, 2, 0],
... [0, 0, 3]])
>>> assert a.norm().equal([1, 2, 3])
>>> a = a.normalized()
>>> assert a.equal([
... [1, 0, 0],
... [0, 1, 0],
... [0, 0, 1],
... ])
>>> assert a.norm().equal([1, 1, 1])
"""
# return np.divide(self.T, self.norm(*args, **kwargs)).T
return np.divide(self, self.norm(*args, **kwargs)[:, None])
| (self, *args, **kwargs) |
21,128 | tfields.core | parts |
Args:
*map_descriptions (Tuple(int, List(List(int)))): tuples of
map_dim (int): reference to map position
used like: self.maps[map_dim]
map_indices_list (List(List(int))): each int refers
to index in a map.
Returns:
List(cls): One TensorMaps or TensorMaps subclass per
map_description
| def parts(self, *map_descriptions):
"""
Args:
*map_descriptions (Tuple(int, List(List(int)))): tuples of
map_dim (int): reference to map position
used like: self.maps[map_dim]
map_indices_list (List(List(int))): each int refers
to index in a map.
Returns:
List(cls): One TensorMaps or TensorMaps subclass per
map_description
"""
parts = []
for map_description in map_descriptions:
map_dim, map_indices_list = map_description
for map_indices in map_indices_list:
obj = self.copy()
map_indices = set(map_indices) # for speed up
map_delete_mask = np.array(
[i not in map_indices for i in range(len(self.maps[map_dim]))]
)
obj.maps[map_dim] = obj.maps[map_dim][~map_delete_mask]
obj = obj.cleaned(duplicates=False)
parts.append(obj)
return parts
| (self, *map_descriptions) |
21,129 | tfields.core | paths |
Find the minimal amount of graphs building the original graph with
maximum of two links per node i.e.
"o-----o o-----o"
" \ / \ /"
"" \ / \ /""
"o--o--o o--o 8--o"
| |
| = | + +
o o o
/ \ / \
/ \ / \
o o o o
where 8 is a duplicated node (one has two links and one has only one.)
Examples:
>>> import tfields
Ascii figure above:
>>> a = tfields.TensorMaps([[1, 0], [3, 0], [2, 2], [0, 4], [2, 4],
... [4, 4], [1, 6], [3, 6], [2, 2]],
... maps=[[[0, 2], [2, 4], [3, 4], [5, 4],
... [1, 8], [6, 4], [6, 7], [7, 4]]])
>>> paths = a.paths(2)
>>> assert paths[0].equal([[ 1., 0.],
... [ 2., 2.],
... [ 2., 4.],
... [ 0., 4.]])
>>> assert paths[0].maps[4].equal([[ 0., 1., 2., 3.]])
>>> assert paths[1].equal([[ 4., 4.],
... [ 2., 4.],
... [ 1., 6.],
... [ 3., 6.],
... [ 2., 4.]])
>>> assert paths[2].equal([[ 3., 0.],
... [ 2., 2.]])
Note:
The Longest path problem is a NP-hard problem.
| def paths(
self, map_dim
): # noqa: E501 pylint: disable=too-many-locals,too-many-branches,too-many-statements
"""
Find the minimal amount of graphs building the original graph with
maximum of two links per node i.e.
"o-----o o-----o"
" \\ / \\ /"
"" \\ / \\ /""
"o--o--o o--o 8--o"
| |
| = | + +
o o o
/ \\ / \\
/ \\ / \\
o o o o
where 8 is a duplicated node (one has two links and one has only one.)
Examples:
>>> import tfields
Ascii figure above:
>>> a = tfields.TensorMaps([[1, 0], [3, 0], [2, 2], [0, 4], [2, 4],
... [4, 4], [1, 6], [3, 6], [2, 2]],
... maps=[[[0, 2], [2, 4], [3, 4], [5, 4],
... [1, 8], [6, 4], [6, 7], [7, 4]]])
>>> paths = a.paths(2)
>>> assert paths[0].equal([[ 1., 0.],
... [ 2., 2.],
... [ 2., 4.],
... [ 0., 4.]])
>>> assert paths[0].maps[4].equal([[ 0., 1., 2., 3.]])
>>> assert paths[1].equal([[ 4., 4.],
... [ 2., 4.],
... [ 1., 6.],
... [ 3., 6.],
... [ 2., 4.]])
>>> assert paths[2].equal([[ 3., 0.],
... [ 2., 2.]])
Note:
The Longest path problem is a NP-hard problem.
"""
obj = self.cleaned()
flat_map = np.array(obj.maps[map_dim].flat)
values, counts = np.unique(flat_map, return_counts=True)
counts = dict(zip(values, counts))
# last is a helper
last = np.full(max(flat_map) + 1, -3, dtype=int)
duplicat_indices = []
d_index = len(obj)
for i, val in enumerate(flat_map.copy()):
if counts[val] > 2:
# The first two occurences are uncritical
if last[val] < -1:
last[val] += 1
continue
# Now we talk about nodes with more than two edges
if last[val] == -1:
# append a point and re-link
duplicat_indices.append(val)
flat_map[i] = d_index
last[val] = d_index
d_index += 1
else:
# last occurence of val was a duplicate, so we use the same
# value again.
flat_map[i] = last[val]
last[val] = -1
if duplicat_indices:
duplicates = obj[duplicat_indices]
obj = type(obj).merged(obj, duplicates)
obj.maps = [flat_map.reshape(-1, *obj.maps[map_dim].shape[1:])]
paths = obj.parts(obj.disjoint_map(map_dim))
# remove duplicate map entries and sort
sorted_paths = []
for path in paths:
# find start index
values, counts = np.unique(path.maps[map_dim].flat, return_counts=True)
first_node = None
for value, count in zip(values, counts):
if count == 1:
first_node = value
break
edges = [list(edge) for edge in path.maps[map_dim]]
if first_node is None:
first_node = 0 # edges[0][0]
path = path[list(range(len(path))) + [0]]
found_first_node = False
for edge in edges:
if first_node in edge:
if found_first_node:
edge[edge.index(first_node)] = len(path) - 1
break
found_first_node = True
# follow the edges until you hit the end
chain = [first_node]
visited = set()
n_edges = len(edges)
node = first_node
while len(visited) < n_edges:
for i, edge in enumerate(edges):
if i in visited:
continue
if node not in edge:
continue
# found edge
visited.add(i)
if edge.index(node) != 0:
edge = list(reversed(edge))
chain.extend(edge[1:])
node = edge[-1]
path = path[chain]
path_map = Maps.to_map([sorted(chain)])
path.maps[dim(path_map)] = path_map
sorted_paths.append(path)
paths = sorted_paths
return paths
| (self, map_dim) |
21,130 | tfields.mesh_3d | planes | null | def planes(self):
return self._planes
| (self) |
21,131 | tfields.core | plot |
Generic plotting method of TensorMaps.
Args:
*args:
Depending on Positional arguments passed to the underlying
:func:`rna.plotting.plot_tensor_map` function for arbitrary .
dim (int): dimension of the plot representation (axes).
map (int): index of the map to plot (default is 3).
edgecolor (color): color of the edges (dim = 3)
| def plot(self, *args, **kwargs): # pragma: no cover
"""
Generic plotting method of TensorMaps.
Args:
*args:
Depending on Positional arguments passed to the underlying
:func:`rna.plotting.plot_tensor_map` function for arbitrary .
dim (int): dimension of the plot representation (axes).
map (int): index of the map to plot (default is 3).
edgecolor (color): color of the edges (dim = 3)
"""
scalars_demanded = (
"color" not in kwargs
and "facecolors" not in kwargs
and any(v in kwargs for v in ["vmin", "vmax", "cmap"])
)
map_ = self.maps[kwargs.pop("map", 3)]
map_index = kwargs.pop("map_index", None if not scalars_demanded else 0)
if map_index is not None:
if not len(map_) == 0:
kwargs["color"] = map_.fields[map_index]
if map_.dim == 3:
# TODO: Mesh plotting only for Mesh3D().
# Overload this function for Mesh3D() specifically.
return rna.plotting.plot_mesh(self, *args, map_, **kwargs)
return rna.plotting.plot_tensor_map(self, *args, map_, **kwargs)
| (self, *args, **kwargs) |
21,132 | tfields.mesh_3d | project |
Project the points of the tensor_field to a copy of the mesh
and set the face values accord to the field to the maps field.
If no field is present in tensor_field, the number of points in a mesh
is counted.
Args:
tensor_field (Tensors | TensorFields)
delta (float | None): forwarded to Mesh3D.in_faces
merge_functions (callable): if multiple Tensors lie in the same face,
they are mapped with the merge_function to one value
point_face_assignment (np.array, dtype=int): array assigning each
point to a face. Each entry position corresponds to a point of the
tensor, each entry value is the index of the assigned face
return_point_face_assignment (bool): if true, return the
point_face_assignment
Examples:
>>> import tfields
>>> import numpy as np
>>> mp = tfields.TensorFields([[0,1,2],[2,3,0],[3,2,5],[5,4,3]],
... [1, 2, 3, 4])
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [1,1,0], [0,1,0], [0,2,0], [1,2,0]],
... maps=[mp])
>>> points = tfields.Tensors([[0.5, 0.2, 0.0],
... [0.5, 0.02, 0.0],
... [0.5, 0.8, 0.0],
... [0.5, 0.8, 0.1]]) # not contained
Projecting points onto the mesh gives the count
>>> m_points = m.project(points, delta=0.01)
>>> list(m_points.maps[3].fields[0])
[2, 1, 0, 0]
TensorFields with arbitrary size are projected,
combinging the fields automatically
>>> fields = [tfields.Tensors([1,3,42, -1]),
... tfields.Tensors([[0,1,2], [2,3,4], [3,4,5], [-1] * 3]),
... tfields.Tensors([[[0, 0]] * 2,
... [[2, 2]] * 2,
... [[3, 3]] * 2,
... [[9, 9]] * 2])]
>>> tf = tfields.TensorFields(points, *fields)
>>> m_tf = m.project(tf, delta=0.01)
>>> assert m_tf.maps[3].fields[0].equal([2, 42, np.nan, np.nan], equal_nan=True)
>>> assert m_tf.maps[3].fields[1].equal([[1, 2, 3],
... [3, 4, 5],
... [np.nan] * 3,
... [np.nan] * 3],
... equal_nan=True)
>>> assert m_tf.maps[3].fields[2].equal([[[1, 1]] * 2,
... [[3, 3]] * 2,
... [[np.nan, np.nan]] * 2,
... [[np.nan, np.nan]] * 2],
... equal_nan=True)
Returning the calculated point_face_assignment can speed up multiple
results
>>> m_tf, point_face_assignment = m.project(tf, delta=0.01,
... return_point_face_assignment=True)
>>> m_tf_fast = m.project(tf, delta=0.01, point_face_assignment=point_face_assignment)
>>> assert m_tf.equal(m_tf_fast, equal_nan=True)
| def project(
self,
tensor_field,
delta=None,
merge_functions=None,
point_face_assignment=None,
return_point_face_assignment=False,
):
"""
Project the points of the tensor_field to a copy of the mesh
and set the face values accord to the field to the maps field.
If no field is present in tensor_field, the number of points in a mesh
is counted.
Args:
tensor_field (Tensors | TensorFields)
delta (float | None): forwarded to Mesh3D.in_faces
merge_functions (callable): if multiple Tensors lie in the same face,
they are mapped with the merge_function to one value
point_face_assignment (np.array, dtype=int): array assigning each
point to a face. Each entry position corresponds to a point of the
tensor, each entry value is the index of the assigned face
return_point_face_assignment (bool): if true, return the
point_face_assignment
Examples:
>>> import tfields
>>> import numpy as np
>>> mp = tfields.TensorFields([[0,1,2],[2,3,0],[3,2,5],[5,4,3]],
... [1, 2, 3, 4])
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [1,1,0], [0,1,0], [0,2,0], [1,2,0]],
... maps=[mp])
>>> points = tfields.Tensors([[0.5, 0.2, 0.0],
... [0.5, 0.02, 0.0],
... [0.5, 0.8, 0.0],
... [0.5, 0.8, 0.1]]) # not contained
Projecting points onto the mesh gives the count
>>> m_points = m.project(points, delta=0.01)
>>> list(m_points.maps[3].fields[0])
[2, 1, 0, 0]
TensorFields with arbitrary size are projected,
combinging the fields automatically
>>> fields = [tfields.Tensors([1,3,42, -1]),
... tfields.Tensors([[0,1,2], [2,3,4], [3,4,5], [-1] * 3]),
... tfields.Tensors([[[0, 0]] * 2,
... [[2, 2]] * 2,
... [[3, 3]] * 2,
... [[9, 9]] * 2])]
>>> tf = tfields.TensorFields(points, *fields)
>>> m_tf = m.project(tf, delta=0.01)
>>> assert m_tf.maps[3].fields[0].equal([2, 42, np.nan, np.nan], equal_nan=True)
>>> assert m_tf.maps[3].fields[1].equal([[1, 2, 3],
... [3, 4, 5],
... [np.nan] * 3,
... [np.nan] * 3],
... equal_nan=True)
>>> assert m_tf.maps[3].fields[2].equal([[[1, 1]] * 2,
... [[3, 3]] * 2,
... [[np.nan, np.nan]] * 2,
... [[np.nan, np.nan]] * 2],
... equal_nan=True)
Returning the calculated point_face_assignment can speed up multiple
results
>>> m_tf, point_face_assignment = m.project(tf, delta=0.01,
... return_point_face_assignment=True)
>>> m_tf_fast = m.project(tf, delta=0.01, point_face_assignment=point_face_assignment)
>>> assert m_tf.equal(m_tf_fast, equal_nan=True)
"""
if not issubclass(type(tensor_field), tfields.Tensors):
tensor_field = tfields.TensorFields(tensor_field)
inst = self.copy()
# setup empty map fields and collect fields
n_faces = len(self.maps[3])
point_indices = np.arange(len(tensor_field))
if not hasattr(tensor_field, "fields") or len(tensor_field.fields) == 0:
# if not fields is existing use int type fields and empty_map_fields
# in order to generate a sum
fields = [np.full(len(tensor_field), 1, dtype=int)]
empty_map_fields = [tfields.Tensors(np.full(n_faces, 0, dtype=int))]
if merge_functions is None:
merge_functions = [np.sum]
else:
fields = tensor_field.fields
empty_map_fields = []
for field in fields:
cls = type(field)
kwargs = {key: getattr(field, key) for key in cls.__slots__}
shape = (n_faces,) + field.shape[1:]
empty_map_fields.append(cls(np.full(shape, np.nan), **kwargs))
if merge_functions is None:
merge_functions = [lambda x: np.mean(x, axis=0)] * len(fields)
# build point_face_assignment if not given.
if point_face_assignment is not None:
if len(point_face_assignment) != len(tensor_field):
raise ValueError("Template needs same lenght as tensor_field")
else:
point_face_assignment = self.in_faces(tensor_field, delta=delta)
point_face_assignment_set = set(point_face_assignment)
# merge the fields according to point_face_assignment
map_fields = []
for field, map_field, merge_function in zip(
fields, empty_map_fields, merge_functions
):
for i, f_index in enumerate(point_face_assignment_set):
if f_index == -1:
# point could not be mapped
continue
point_in_face_indices = point_indices[point_face_assignment == f_index]
res = field[point_in_face_indices]
if len(res) == 1:
map_field[f_index] = res
else:
map_field[f_index] = merge_function(res)
map_fields.append(map_field)
inst.maps[3].fields = map_fields
if return_point_face_assignment:
return inst, point_face_assignment
return inst
| (self, tensor_field, delta=None, merge_functions=None, point_face_assignment=None, return_point_face_assignment=False) |
21,134 | tfields.mesh_3d | remove_faces |
Remove faces where face_delete_mask is True
| def remove_faces(self, face_delete_mask):
"""
Remove faces where face_delete_mask is True
"""
face_delete_mask = np.array(face_delete_mask, dtype=bool)
self.faces = self.faces[~face_delete_mask]
self.faces.fields = self.faces.fields[~face_delete_mask]
| (self, face_delete_mask) |
21,135 | tfields.core | removed |
Return copy of self without vertices where remove_condition is True
Copy because self is immutable
Examples:
>>> import tfields
>>> m = tfields.TensorMaps(
... [[0,0,0], [1,1,1], [2,2,2], [0,0,0],
... [3,3,3], [4,4,4], [5,5,5]],
... maps=[tfields.TensorFields([[0, 1, 2], [0, 1, 3],
... [3, 4, 5], [3, 4, 1],
... [3, 4, 6]],
... [1, 3, 5, 7, 9],
... [2, 4, 6, 8, 0])])
>>> c = m.keep([False, False, False, True, True, True, True])
>>> c.equal([[0, 0, 0],
... [3, 3, 3],
... [4, 4, 4],
... [5, 5, 5]])
True
>>> assert c.maps[3].equal([[0, 1, 2], [0, 1, 3]])
>>> assert c.maps[3].fields[0].equal([5, 9])
>>> assert c.maps[3].fields[1].equal([6, 0])
| def removed(self, remove_condition):
"""
Return copy of self without vertices where remove_condition is True
Copy because self is immutable
Examples:
>>> import tfields
>>> m = tfields.TensorMaps(
... [[0,0,0], [1,1,1], [2,2,2], [0,0,0],
... [3,3,3], [4,4,4], [5,5,5]],
... maps=[tfields.TensorFields([[0, 1, 2], [0, 1, 3],
... [3, 4, 5], [3, 4, 1],
... [3, 4, 6]],
... [1, 3, 5, 7, 9],
... [2, 4, 6, 8, 0])])
>>> c = m.keep([False, False, False, True, True, True, True])
>>> c.equal([[0, 0, 0],
... [3, 3, 3],
... [4, 4, 4],
... [5, 5, 5]])
True
>>> assert c.maps[3].equal([[0, 1, 2], [0, 1, 3]])
>>> assert c.maps[3].fields[0].equal([5, 9])
>>> assert c.maps[3].fields[1].equal([6, 0])
"""
remove_condition = np.array(remove_condition)
return self[~remove_condition]
| (self, remove_condition) |
21,137 | tfields.core | stale |
Returns:
Mask for all vertices that are stale i.e. are not refered by maps
Examples:
>>> import numpy as np
>>> import tfields
>>> vectors = tfields.Tensors(
... [[0, 0, 0], [0, 0, 1], [0, -1, 0], [4, 4, 4]])
>>> tm = tfields.TensorMaps(
... vectors,
... maps=[[[0, 1, 2], [0, 1, 2]], [[1, 1], [2, 2]]])
>>> assert np.array_equal(tm.stale(), [False, False, False, True])
| def stale(self):
"""
Returns:
Mask for all vertices that are stale i.e. are not refered by maps
Examples:
>>> import numpy as np
>>> import tfields
>>> vectors = tfields.Tensors(
... [[0, 0, 0], [0, 0, 1], [0, -1, 0], [4, 4, 4]])
>>> tm = tfields.TensorMaps(
... vectors,
... maps=[[[0, 1, 2], [0, 1, 2]], [[1, 1], [2, 2]]])
>>> assert np.array_equal(tm.stale(), [False, False, False, True])
"""
stale_mask = np.full(self.shape[0], False, dtype=bool)
used = set(ind for mp in self.maps.values() for ind in mp.flatten())
for i in range(self.shape[0]):
if i not in used:
stale_mask[i] = True
return stale_mask
| (self) |
21,138 | tfields.mesh_3d | template |
'Manual' way to build a template that can be used with self.cut
Returns:
Mesh3D: template (see cut), can be used as template to retrieve
sub_mesh from self instance
Examples:
>>> import tfields
>>> from sympy.abc import y
>>> mp = tfields.TensorFields([[0,1,2],[2,3,0],[3,2,5],[5,4,3]],
... [1, 2, 3, 4])
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [1,1,0], [0,1,0], [0,2,0], [1,2,0]],
... maps=[mp])
>>> m_cut = m.cut(y < 1.5, at_intersection='split')
>>> template = m.template(m_cut)
>>> assert m_cut.equal(m.cut(template))
TODO:
fields template not yet implemented
| def template(self, sub_mesh):
"""
'Manual' way to build a template that can be used with self.cut
Returns:
Mesh3D: template (see cut), can be used as template to retrieve
sub_mesh from self instance
Examples:
>>> import tfields
>>> from sympy.abc import y
>>> mp = tfields.TensorFields([[0,1,2],[2,3,0],[3,2,5],[5,4,3]],
... [1, 2, 3, 4])
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [1,1,0], [0,1,0], [0,2,0], [1,2,0]],
... maps=[mp])
>>> m_cut = m.cut(y < 1.5, at_intersection='split')
>>> template = m.template(m_cut)
>>> assert m_cut.equal(m.cut(template))
TODO:
fields template not yet implemented
"""
cents = tfields.Tensors(sub_mesh.centroids())
face_indices = self.in_faces(cents, delta=None)
inst = sub_mesh.copy()
if inst.maps:
inst.maps[3].fields = [tfields.Tensors(face_indices, dim=1)]
else:
inst.maps = [
tfields.TensorFields([], tfields.Tensors([], dim=1), dim=3, dtype=int)
]
return inst
| (self, sub_mesh) |
21,139 | tfields.core | tmp_transform |
Temporarily change the coord_sys to another coord_sys and change it back at exit
This method is for cleaner code only.
No speed improvements go with this.
Args:
see transform
Examples:
>>> import tfields
>>> p = tfields.Tensors([[1,2,3]], coord_sys=tfields.bases.SPHERICAL)
>>> with p.tmp_transform(tfields.bases.CYLINDER):
... assert p.coord_sys == tfields.bases.CYLINDER
>>> assert p.coord_sys == tfields.bases.SPHERICAL
| @classmethod
def _from_dict(cls, content: dict):
type_ = content.get("type")
assert type_ == cls.__name__
return _from_dict(content)
| (self, coord_sys) |
21,140 | tfields.core | to_segment |
For circular (close into themself after
<periodicity>) coordinates at index <coordinate> assume
<num_segments> segments and transform all values to
segment number <segment>
Args:
segment (int): segment index (starting at 0)
num_segments (int): number of segments
coordinate (int): coordinate index
periodicity (float): after what lenght, the coordiante repeats
offset (float): offset in the mapping
coord_sys (str or sympy.CoordinateSystem): in which coord sys the
transformation should be done
Examples:
>>> import tfields
>>> import numpy as np
>>> pStart = tfields.Points3D([[6, 2 * np.pi, 1],
... [6, 2 * np.pi / 5 * 3, 1]],
... coord_sys='cylinder')
>>> p = tfields.Points3D(pStart)
>>> p.to_segment(0, 5, 1, offset=-2 * np.pi / 10)
>>> assert np.array_equal(p[:, 1], [0, 0])
>>> p2 = tfields.Points3D(pStart)
>>> p2.to_segment(1, 5, 1, offset=-2 * np.pi / 10)
>>> assert np.array_equal(np.round(p2[:, 1], 4), [1.2566] * 2)
| def to_segment( # pylint: disable=too-many-arguments
self,
segment,
num_segments,
coordinate,
periodicity=2 * np.pi,
offset=0.0,
coord_sys=None,
):
"""
For circular (close into themself after
<periodicity>) coordinates at index <coordinate> assume
<num_segments> segments and transform all values to
segment number <segment>
Args:
segment (int): segment index (starting at 0)
num_segments (int): number of segments
coordinate (int): coordinate index
periodicity (float): after what lenght, the coordiante repeats
offset (float): offset in the mapping
coord_sys (str or sympy.CoordinateSystem): in which coord sys the
transformation should be done
Examples:
>>> import tfields
>>> import numpy as np
>>> pStart = tfields.Points3D([[6, 2 * np.pi, 1],
... [6, 2 * np.pi / 5 * 3, 1]],
... coord_sys='cylinder')
>>> p = tfields.Points3D(pStart)
>>> p.to_segment(0, 5, 1, offset=-2 * np.pi / 10)
>>> assert np.array_equal(p[:, 1], [0, 0])
>>> p2 = tfields.Points3D(pStart)
>>> p2.to_segment(1, 5, 1, offset=-2 * np.pi / 10)
>>> assert np.array_equal(np.round(p2[:, 1], 4), [1.2566] * 2)
"""
if segment > num_segments - 1:
raise ValueError("Segment {0} not existent.".format(segment))
if coord_sys is None:
coord_sys = self.coord_sys
with self.tmp_transform(coord_sys):
# map all values to first segment
self[:, coordinate] = (
(self[:, coordinate] - offset) % (periodicity / num_segments)
+ offset
+ segment * periodicity / num_segments
)
| (self, segment, num_segments, coordinate, periodicity=6.283185307179586, offset=0.0, coord_sys=None) |
21,141 | tfields.core | transform |
Args:
coord_sys (str)
Examples:
>>> import numpy as np
>>> import tfields
CARTESIAN to SPHERICAL
>>> t = tfields.Tensors([[1, 2, 2], [1, 0, 0], [0, 0, -1],
... [0, 0, 1], [0, 0, 0]])
>>> t.transform('spherical')
r
>>> assert t[0, 0] == 3
phi
>>> assert t[1, 1] == 0.
>>> assert t[2, 1] == 0.
theta is 0 at (0, 0, 1) and pi / 2 at (0, 0, -1)
>>> assert round(t[1, 2], 10) == round(0, 10)
>>> assert t[2, 2] == -np.pi / 2
>>> assert t[3, 2] == np.pi / 2
theta is defined 0 for R == 0
>>> assert t[4, 0] == 0.
>>> assert t[4, 2] == 0.
CARTESIAN to CYLINDER
>>> tCart = tfields.Tensors([[3, 4, 42], [1, 0, 0], [0, 1, -1],
... [-1, 0, 1], [0, 0, 0]])
>>> t_cyl = tCart.copy()
>>> t_cyl.transform('cylinder')
>>> assert t_cyl.coord_sys == 'cylinder'
R
>>> assert t_cyl[0, 0] == 5
>>> assert t_cyl[1, 0] == 1
>>> assert t_cyl[2, 0] == 1
>>> assert t_cyl[4, 0] == 0
Phi
>>> assert round(t_cyl[0, 1], 10) == round(np.arctan(4. / 3), 10)
>>> assert t_cyl[1, 1] == 0
>>> assert round(t_cyl[2, 1], 10) == round(np.pi / 2, 10)
>>> assert t_cyl[1, 1] == 0
Z
>>> assert t_cyl[0, 2] == 42
>>> assert t_cyl[2, 2] == -1
>>> t_cyl.transform('cartesian')
>>> assert t_cyl.coord_sys == 'cartesian'
>>> assert round(t_cyl[0, 0], 10) == 3
| def transform(self, coord_sys, **kwargs):
"""
Args:
coord_sys (str)
Examples:
>>> import numpy as np
>>> import tfields
CARTESIAN to SPHERICAL
>>> t = tfields.Tensors([[1, 2, 2], [1, 0, 0], [0, 0, -1],
... [0, 0, 1], [0, 0, 0]])
>>> t.transform('spherical')
r
>>> assert t[0, 0] == 3
phi
>>> assert t[1, 1] == 0.
>>> assert t[2, 1] == 0.
theta is 0 at (0, 0, 1) and pi / 2 at (0, 0, -1)
>>> assert round(t[1, 2], 10) == round(0, 10)
>>> assert t[2, 2] == -np.pi / 2
>>> assert t[3, 2] == np.pi / 2
theta is defined 0 for R == 0
>>> assert t[4, 0] == 0.
>>> assert t[4, 2] == 0.
CARTESIAN to CYLINDER
>>> tCart = tfields.Tensors([[3, 4, 42], [1, 0, 0], [0, 1, -1],
... [-1, 0, 1], [0, 0, 0]])
>>> t_cyl = tCart.copy()
>>> t_cyl.transform('cylinder')
>>> assert t_cyl.coord_sys == 'cylinder'
R
>>> assert t_cyl[0, 0] == 5
>>> assert t_cyl[1, 0] == 1
>>> assert t_cyl[2, 0] == 1
>>> assert t_cyl[4, 0] == 0
Phi
>>> assert round(t_cyl[0, 1], 10) == round(np.arctan(4. / 3), 10)
>>> assert t_cyl[1, 1] == 0
>>> assert round(t_cyl[2, 1], 10) == round(np.pi / 2, 10)
>>> assert t_cyl[1, 1] == 0
Z
>>> assert t_cyl[0, 2] == 42
>>> assert t_cyl[2, 2] == -1
>>> t_cyl.transform('cartesian')
>>> assert t_cyl.coord_sys == 'cartesian'
>>> assert round(t_cyl[0, 0], 10) == 3
"""
if self.rank == 0 or any(s == 0 for s in self.shape):
# scalar or empty
self.coord_sys = coord_sys # pylint: disable=attribute-defined-outside-init
return
if self.coord_sys == coord_sys:
# already correct
return
tfields.bases.transform(self, self.coord_sys, coord_sys, **kwargs)
# self[:] = tfields.bases.transform(self, self.coord_sys, coord_sys)
self.coord_sys = coord_sys # pylint: disable=attribute-defined-outside-init
| (self, coord_sys, **kwargs) |
21,142 | tfields.core | transform_field |
Transform the field to the coordinate system of choice.
NOTE: This is not yet any way generic!!! Have a look at Einsteinpy and actual status of
sympy for further implementation
| def transform_field(self, coord_sys, field_index=0):
"""
Transform the field to the coordinate system of choice.
NOTE: This is not yet any way generic!!! Have a look at Einsteinpy and actual status of
sympy for further implementation
"""
self.fields[field_index].transform(coord_sys, position=self)
| (self, coord_sys, field_index=0) |
21,143 | tfields.mesh_3d | triangles |
Cached method to retrieve the triangles, belonging to this mesh
Examples:
>>> import tfields
>>> mesh = tfields.Mesh3D.grid((0, 1, 3), (1, 2, 3), (2, 3, 3))
>>> assert mesh.triangles() is mesh.triangles()
| def triangles(self):
"""
Cached method to retrieve the triangles, belonging to this mesh
Examples:
>>> import tfields
>>> mesh = tfields.Mesh3D.grid((0, 1, 3), (1, 2, 3), (2, 3, 3))
>>> assert mesh.triangles() is mesh.triangles()
"""
return self._triangles
| (self) |
21,144 | tfields.bounding_box | Node |
This class allows to increase the performance with cuts in
x,y and z direction
An extension to arbitrary cuts might be possible in the future
Args:
parent: Parent node of self
mesh: Mesh corresponding to the node
cut_expr: Cut that determines the seperation in left and right node
cuts: List of cuts for the children nodes
Attrs:
parent (Node)
remaining_cuts (dict): key specifies dimension, value the cuts that
are still not done
cut_expr (dict): part of parents remaining_cuts. The dimension defines
what is meant by left and right
Examples:
>>> import tfields
>>> mesh = tfields.Mesh3D.grid((5.6, 6.2, 3),
... (-0.25, 0.25, 4),
... (-1, 1, 10))
>>> cuts = {'x': [5.7, 6.1],
... 'y': [-0.2, 0, 0.2],
... 'z': [-0.5, 0.5]}
>>> tree = tfields.bounding_box.Node(mesh,
... cuts,
... at_intersection='keep')
>>> leaves = tree.leaves()
>>> leaves = tfields.bounding_box.Node.sort_leaves(leaves)
>>> meshes = [leaf.mesh for leaf in leaves]
>>> templates = [leaf.template for leaf in leaves]
>>> special_leaf = tree.find_leaf([5.65, -0.21, 0])
| class Node(object):
"""
This class allows to increase the performance with cuts in
x,y and z direction
An extension to arbitrary cuts might be possible in the future
Args:
parent: Parent node of self
mesh: Mesh corresponding to the node
cut_expr: Cut that determines the seperation in left and right node
cuts: List of cuts for the children nodes
Attrs:
parent (Node)
remaining_cuts (dict): key specifies dimension, value the cuts that
are still not done
cut_expr (dict): part of parents remaining_cuts. The dimension defines
what is meant by left and right
Examples:
>>> import tfields
>>> mesh = tfields.Mesh3D.grid((5.6, 6.2, 3),
... (-0.25, 0.25, 4),
... (-1, 1, 10))
>>> cuts = {'x': [5.7, 6.1],
... 'y': [-0.2, 0, 0.2],
... 'z': [-0.5, 0.5]}
>>> tree = tfields.bounding_box.Node(mesh,
... cuts,
... at_intersection='keep')
>>> leaves = tree.leaves()
>>> leaves = tfields.bounding_box.Node.sort_leaves(leaves)
>>> meshes = [leaf.mesh for leaf in leaves]
>>> templates = [leaf.template for leaf in leaves]
>>> special_leaf = tree.find_leaf([5.65, -0.21, 0])
"""
def __init__(
self,
mesh,
cuts,
coord_sys=None,
at_intersection="split",
delta=0.0,
parent=None,
box=None,
internal_template=None,
cut_expr=None,
):
self.parent = parent
# initialize
self.mesh = copy.deepcopy(mesh)
if self.is_root():
cuts = copy.deepcopy(cuts) # dicts are mutable
self.remaining_cuts = cuts
logging.debug(cuts)
self.delta = delta
if box is None:
vertices = np.array(self.mesh)
self.box = {
"x": [min(vertices[:, 0]) - delta, max(vertices[:, 0]) + delta],
"y": [min(vertices[:, 1]) - delta, max(vertices[:, 1]) + delta],
"z": [min(vertices[:, 2]) - delta, max(vertices[:, 2]) + delta],
}
else:
self.box = box
self.left = None
self.right = None
self.at_intersection = at_intersection
self._internal_template = internal_template
if self.is_leaf():
self._template = None
if self.is_root():
self._trim_to_box()
self.cut_expr = cut_expr
self.left_template = None
self.right_template = None
self.coord_sys = coord_sys
# start the splitting process
self._build()
def _build(self):
if not self.is_last_cut():
self._choose_next_cut()
self._split()
def is_leaf(self):
if self.left is None and self.right is None:
return True
else:
return False
def is_root(self):
if self.parent is None:
return True
else:
return False
def is_last_cut(self):
for key in self.remaining_cuts:
if len(self.remaining_cuts[key]) != 0:
return False
return True
def in_box(self, point):
x, y, z = point
for key in ["x", "y", "z"]:
value = locals()[key]
if value < self.box[key][0] or self.box[key][1] < value:
return False
return True
@property
def root(self):
if self.is_root:
return self
return self.parent.root
@classmethod
def sort_leaves(cls, leaves_list):
"""
sorting the leaves first in x, then y, then z direction
"""
sorted_leaves = sorted(
leaves_list, key=lambda x: (x.box["x"][1], x.box["y"][1], x.box["z"][1])
)
return sorted_leaves
def _trim_to_box(self):
# 6 cuts to remove outer part of the box
x, y, z = sympy.symbols("x y z")
eps = 0.0000000001
x_cut = (float(self.box["x"][0] - eps) <= x) & (
x <= float(self.box["x"][1] + eps)
)
y_cut = (float(self.box["y"][0] - eps) <= y) & (
y <= float(self.box["y"][1] + eps)
)
z_cut = (float(self.box["z"][0] - eps) <= z) & (
z <= float(self.box["z"][1] + eps)
)
section_cut = x_cut & y_cut & z_cut
self.mesh, self._internal_template = self.mesh.cut(
section_cut, at_intersection=self.at_intersection, return_template=True
)
def leaves(self):
"""
Recursive function to create a list of all leaves
Returns:
list: of all leaves descending from this node
"""
if self.is_leaf():
return [self]
else:
if self.left is not None:
leftLeaves = self.left.leaves()
else:
leftLeaves = []
if self.right is not None:
rightLeaves = self.right.leaves()
else:
rightLeaves = []
return tfields.lib.util.flatten(leftLeaves + rightLeaves)
def find_leaf(self, point, _in_recursion=False):
"""
Returns:
Node / None:
Node: leaf note, containinig point
None: point outside root box
"""
x, y, z = point
if self.is_root():
if not self.in_box(point):
return None
else:
if not _in_recursion:
raise RuntimeError("Only root node can search for all leaves")
if self.is_leaf():
return self
if len(self.cut_expr) > 1:
raise ValueError("cut_expr is too long")
key = list(self.cut_expr)[0]
value = locals()[key]
if value <= self.cut_expr[key]:
return self.left.find_leaf(point, _in_recursion=True)
return self.right.find_leaf(point, _in_recursion=True)
def _split(self):
"""
Split the node in two new nodes, if there is no cut_expr set and
remaing cuts exist.
"""
if self.cut_expr is None and self.remaining_cuts is None:
raise RuntimeError(
"Cannot split the mesh without cut_expr and" "remaining_cuts"
)
else:
# create cut expression
x, y, z = sympy.symbols("x y z")
if "x" in self.cut_expr:
left_cut_expression = x <= self.cut_expr["x"]
right_cut_expression = x >= self.cut_expr["x"]
key = "x"
elif "y" in self.cut_expr:
left_cut_expression = y <= self.cut_expr["y"]
right_cut_expression = y >= self.cut_expr["y"]
key = "y"
elif "z" in self.cut_expr:
left_cut_expression = z <= self.cut_expr["z"]
right_cut_expression = z >= self.cut_expr["z"]
key = "z"
else:
raise KeyError()
# split the cuts into left / right
left_cuts = self.remaining_cuts.copy()
right_cuts = self.remaining_cuts.copy()
left_cuts[key] = [
value
for value in self.remaining_cuts[key]
if value <= self.cut_expr[key]
]
right_cuts[key] = [
value
for value in self.remaining_cuts[key]
if value > self.cut_expr[key]
]
left_box = copy.deepcopy(self.box)
right_box = copy.deepcopy(self.box)
left_box[key][1] = self.cut_expr[key]
right_box[key][0] = self.cut_expr[key]
# actually cut!
left_mesh, self.left_template = self.mesh.cut(
left_cut_expression,
at_intersection=self.at_intersection,
return_template=True,
)
right_mesh, self.right_template = self.mesh.cut(
right_cut_expression,
at_intersection=self.at_intersection,
return_template=True,
)
# two new Nodes
self.left = Node(
left_mesh,
left_cuts,
parent=self,
internal_template=self.left_template,
cut_expr=None,
coord_sys=self.coord_sys,
at_intersection=self.at_intersection,
box=left_box,
)
self.right = Node(
right_mesh,
right_cuts,
parent=self,
internal_template=self.right_template,
cut_expr=None,
coord_sys=self.coord_sys,
at_intersection=self.at_intersection,
box=right_box,
)
def _choose_next_cut(self):
"""
Set self.cut_expr by choosing the dimension with the most remaining
cuts. Remove that cut from remaining cuts
"""
largest = 0
for key in self.remaining_cuts:
if len(self.remaining_cuts[key]) > largest:
largest = len(self.remaining_cuts[key])
largest_key = key
median = sorted(self.remaining_cuts[largest_key])[
int(0.5 * (len(self.remaining_cuts[largest_key]) - 1))
]
# pop median cut from remaining cuts
self.remaining_cuts[largest_key] = [
x for x in self.remaining_cuts[largest_key] if x != median
]
self.cut_expr = {largest_key: median}
def _convert_map_index(self, index):
"""
Recursively getting the map fields index from root
Args:
index (int): map field index on leaf
(index with respect to parent node, not to root)
Returns:
int: map field index
"""
if self.is_root():
return index
else:
return_value = self.parent._convert_map_index(
self.parent._internal_template.maps[3].fields[0][int(index)]
)
return return_value
def _convert_field_index(self, index):
"""
Recursively getting the fields index from root
Args:
index (int): field index on leaf
(index with respect to parent node, not to root)
Returns:
int: field index
"""
if self.is_root():
return index
else:
return_value = self.parent._convert_field_index(
self.parent._internal_template.fields[0][int(index)]
)
return return_value
@property
def template(self):
"""
Get the global template for a leaf. This can be applied to the root mesh
with the cut method to retrieve exactly this leaf mesh again.
Returns:
tfields.Mesh3D: mesh with first scalars as an instruction on how to build
this cut (scalars point to faceIndices on mother mesh). Can be
used with Mesh3D.cut
"""
if not self.is_leaf():
raise RuntimeError("Only leaf nodes can return a template")
if self._template is None:
template = self._internal_template.copy()
template_field = []
if template.fields:
for idx in template.fields[0]:
template_field.append(self._convert_field_index(idx))
template.fields = [tfields.Tensors(template_field, dim=1, dtype=int)]
template_map_field = []
if len(template.maps[3]) > 0:
for idx in template.maps[3].fields[0]:
template_map_field.append(self._convert_map_index(idx))
template.maps[3].fields = [
tfields.Tensors(template_map_field, dim=1, dtype=int)
]
self._template = template
return self._template
| (mesh, cuts, coord_sys=None, at_intersection='split', delta=0.0, parent=None, box=None, internal_template=None, cut_expr=None) |
21,145 | tfields.bounding_box | __init__ | null | def __init__(
self,
mesh,
cuts,
coord_sys=None,
at_intersection="split",
delta=0.0,
parent=None,
box=None,
internal_template=None,
cut_expr=None,
):
self.parent = parent
# initialize
self.mesh = copy.deepcopy(mesh)
if self.is_root():
cuts = copy.deepcopy(cuts) # dicts are mutable
self.remaining_cuts = cuts
logging.debug(cuts)
self.delta = delta
if box is None:
vertices = np.array(self.mesh)
self.box = {
"x": [min(vertices[:, 0]) - delta, max(vertices[:, 0]) + delta],
"y": [min(vertices[:, 1]) - delta, max(vertices[:, 1]) + delta],
"z": [min(vertices[:, 2]) - delta, max(vertices[:, 2]) + delta],
}
else:
self.box = box
self.left = None
self.right = None
self.at_intersection = at_intersection
self._internal_template = internal_template
if self.is_leaf():
self._template = None
if self.is_root():
self._trim_to_box()
self.cut_expr = cut_expr
self.left_template = None
self.right_template = None
self.coord_sys = coord_sys
# start the splitting process
self._build()
| (self, mesh, cuts, coord_sys=None, at_intersection='split', delta=0.0, parent=None, box=None, internal_template=None, cut_expr=None) |
21,146 | tfields.bounding_box | _build | null | def _build(self):
if not self.is_last_cut():
self._choose_next_cut()
self._split()
| (self) |
21,147 | tfields.bounding_box | _choose_next_cut |
Set self.cut_expr by choosing the dimension with the most remaining
cuts. Remove that cut from remaining cuts
| def _choose_next_cut(self):
"""
Set self.cut_expr by choosing the dimension with the most remaining
cuts. Remove that cut from remaining cuts
"""
largest = 0
for key in self.remaining_cuts:
if len(self.remaining_cuts[key]) > largest:
largest = len(self.remaining_cuts[key])
largest_key = key
median = sorted(self.remaining_cuts[largest_key])[
int(0.5 * (len(self.remaining_cuts[largest_key]) - 1))
]
# pop median cut from remaining cuts
self.remaining_cuts[largest_key] = [
x for x in self.remaining_cuts[largest_key] if x != median
]
self.cut_expr = {largest_key: median}
| (self) |
21,148 | tfields.bounding_box | _convert_field_index |
Recursively getting the fields index from root
Args:
index (int): field index on leaf
(index with respect to parent node, not to root)
Returns:
int: field index
| def _convert_field_index(self, index):
"""
Recursively getting the fields index from root
Args:
index (int): field index on leaf
(index with respect to parent node, not to root)
Returns:
int: field index
"""
if self.is_root():
return index
else:
return_value = self.parent._convert_field_index(
self.parent._internal_template.fields[0][int(index)]
)
return return_value
| (self, index) |
21,149 | tfields.bounding_box | _convert_map_index |
Recursively getting the map fields index from root
Args:
index (int): map field index on leaf
(index with respect to parent node, not to root)
Returns:
int: map field index
| def _convert_map_index(self, index):
"""
Recursively getting the map fields index from root
Args:
index (int): map field index on leaf
(index with respect to parent node, not to root)
Returns:
int: map field index
"""
if self.is_root():
return index
else:
return_value = self.parent._convert_map_index(
self.parent._internal_template.maps[3].fields[0][int(index)]
)
return return_value
| (self, index) |
21,150 | tfields.bounding_box | _split |
Split the node in two new nodes, if there is no cut_expr set and
remaing cuts exist.
| def _split(self):
"""
Split the node in two new nodes, if there is no cut_expr set and
remaing cuts exist.
"""
if self.cut_expr is None and self.remaining_cuts is None:
raise RuntimeError(
"Cannot split the mesh without cut_expr and" "remaining_cuts"
)
else:
# create cut expression
x, y, z = sympy.symbols("x y z")
if "x" in self.cut_expr:
left_cut_expression = x <= self.cut_expr["x"]
right_cut_expression = x >= self.cut_expr["x"]
key = "x"
elif "y" in self.cut_expr:
left_cut_expression = y <= self.cut_expr["y"]
right_cut_expression = y >= self.cut_expr["y"]
key = "y"
elif "z" in self.cut_expr:
left_cut_expression = z <= self.cut_expr["z"]
right_cut_expression = z >= self.cut_expr["z"]
key = "z"
else:
raise KeyError()
# split the cuts into left / right
left_cuts = self.remaining_cuts.copy()
right_cuts = self.remaining_cuts.copy()
left_cuts[key] = [
value
for value in self.remaining_cuts[key]
if value <= self.cut_expr[key]
]
right_cuts[key] = [
value
for value in self.remaining_cuts[key]
if value > self.cut_expr[key]
]
left_box = copy.deepcopy(self.box)
right_box = copy.deepcopy(self.box)
left_box[key][1] = self.cut_expr[key]
right_box[key][0] = self.cut_expr[key]
# actually cut!
left_mesh, self.left_template = self.mesh.cut(
left_cut_expression,
at_intersection=self.at_intersection,
return_template=True,
)
right_mesh, self.right_template = self.mesh.cut(
right_cut_expression,
at_intersection=self.at_intersection,
return_template=True,
)
# two new Nodes
self.left = Node(
left_mesh,
left_cuts,
parent=self,
internal_template=self.left_template,
cut_expr=None,
coord_sys=self.coord_sys,
at_intersection=self.at_intersection,
box=left_box,
)
self.right = Node(
right_mesh,
right_cuts,
parent=self,
internal_template=self.right_template,
cut_expr=None,
coord_sys=self.coord_sys,
at_intersection=self.at_intersection,
box=right_box,
)
| (self) |
21,151 | tfields.bounding_box | _trim_to_box | null | def _trim_to_box(self):
# 6 cuts to remove outer part of the box
x, y, z = sympy.symbols("x y z")
eps = 0.0000000001
x_cut = (float(self.box["x"][0] - eps) <= x) & (
x <= float(self.box["x"][1] + eps)
)
y_cut = (float(self.box["y"][0] - eps) <= y) & (
y <= float(self.box["y"][1] + eps)
)
z_cut = (float(self.box["z"][0] - eps) <= z) & (
z <= float(self.box["z"][1] + eps)
)
section_cut = x_cut & y_cut & z_cut
self.mesh, self._internal_template = self.mesh.cut(
section_cut, at_intersection=self.at_intersection, return_template=True
)
| (self) |
21,152 | tfields.bounding_box | find_leaf |
Returns:
Node / None:
Node: leaf note, containinig point
None: point outside root box
| def find_leaf(self, point, _in_recursion=False):
"""
Returns:
Node / None:
Node: leaf note, containinig point
None: point outside root box
"""
x, y, z = point
if self.is_root():
if not self.in_box(point):
return None
else:
if not _in_recursion:
raise RuntimeError("Only root node can search for all leaves")
if self.is_leaf():
return self
if len(self.cut_expr) > 1:
raise ValueError("cut_expr is too long")
key = list(self.cut_expr)[0]
value = locals()[key]
if value <= self.cut_expr[key]:
return self.left.find_leaf(point, _in_recursion=True)
return self.right.find_leaf(point, _in_recursion=True)
| (self, point, _in_recursion=False) |
21,153 | tfields.bounding_box | in_box | null | def in_box(self, point):
x, y, z = point
for key in ["x", "y", "z"]:
value = locals()[key]
if value < self.box[key][0] or self.box[key][1] < value:
return False
return True
| (self, point) |
21,154 | tfields.bounding_box | is_last_cut | null | def is_last_cut(self):
for key in self.remaining_cuts:
if len(self.remaining_cuts[key]) != 0:
return False
return True
| (self) |
21,155 | tfields.bounding_box | is_leaf | null | def is_leaf(self):
if self.left is None and self.right is None:
return True
else:
return False
| (self) |
21,156 | tfields.bounding_box | is_root | null | def is_root(self):
if self.parent is None:
return True
else:
return False
| (self) |
21,157 | tfields.bounding_box | leaves |
Recursive function to create a list of all leaves
Returns:
list: of all leaves descending from this node
| def leaves(self):
"""
Recursive function to create a list of all leaves
Returns:
list: of all leaves descending from this node
"""
if self.is_leaf():
return [self]
else:
if self.left is not None:
leftLeaves = self.left.leaves()
else:
leftLeaves = []
if self.right is not None:
rightLeaves = self.right.leaves()
else:
rightLeaves = []
return tfields.lib.util.flatten(leftLeaves + rightLeaves)
| (self) |
21,158 | tfields.planes_3d | Planes3D |
Point-NormVector representaion of planes
Examples:
>>> import tfields
>>> points = [[0, 1, 0]]
>>> norms = [[0, 0, 1]]
>>> plane = tfields.Planes3D(points, norms)
>>> plane.symbolic()[0]
Plane(Point3D(0, 1, 0), (0, 0, 1))
| class Planes3D(tfields.TensorFields):
"""
Point-NormVector representaion of planes
Examples:
>>> import tfields
>>> points = [[0, 1, 0]]
>>> norms = [[0, 0, 1]]
>>> plane = tfields.Planes3D(points, norms)
>>> plane.symbolic()[0]
Plane(Point3D(0, 1, 0), (0, 0, 1))
"""
def symbolic(self):
"""
Returns:
list: list with sympy.Plane objects
"""
return [
sympy.Plane(point, normal_vector=vector)
for point, vector in zip(self, self.fields[0])
]
def plot(self, **kwargs): # pragma: no cover
"""
forward to Mesh3D plotting
"""
artists = []
centers = np.array(self)
norms = np.array(self.fields[0])
for i in range(len(self)):
artists.append(rna.plotting.plot_plane(centers[i], norms[i], **kwargs))
return artists
| (tensors, *fields, **kwargs) |
21,161 | tfields.core | __getitem__ |
In addition to the usual, also slice fields
Examples:
>>> import tfields
>>> import numpy as np
>>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> scalar_field = tfields.TensorFields(
... vectors,
... [42, 21, 10.5],
... [1, 2, 3],
... [[0, 0], [-1, -1], [-2, -2]])
Slicing
>>> sliced = scalar_field[2:]
>>> assert isinstance(sliced, tfields.TensorFields)
>>> assert isinstance(sliced.fields[0], tfields.Tensors)
>>> assert sliced.fields[0].equal([10.5])
Picking
>>> picked = scalar_field[1]
>>> assert np.array_equal(picked, [0, 0, 1])
>>> assert np.array_equal(picked.fields[0], 21)
Masking
>>> masked = scalar_field[np.array([True, False, True])]
>>> assert masked.equal([[0, 0, 0], [0, -1, 0]])
>>> assert masked.fields[0].equal([42, 10.5])
>>> assert masked.fields[1].equal([1, 3])
Iteration
>>> _ = [point for point in scalar_field]
| def __getitem__(self, index):
"""
In addition to the usual, also slice fields
Examples:
>>> import tfields
>>> import numpy as np
>>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> scalar_field = tfields.TensorFields(
... vectors,
... [42, 21, 10.5],
... [1, 2, 3],
... [[0, 0], [-1, -1], [-2, -2]])
Slicing
>>> sliced = scalar_field[2:]
>>> assert isinstance(sliced, tfields.TensorFields)
>>> assert isinstance(sliced.fields[0], tfields.Tensors)
>>> assert sliced.fields[0].equal([10.5])
Picking
>>> picked = scalar_field[1]
>>> assert np.array_equal(picked, [0, 0, 1])
>>> assert np.array_equal(picked.fields[0], 21)
Masking
>>> masked = scalar_field[np.array([True, False, True])]
>>> assert masked.equal([[0, 0, 0], [0, -1, 0]])
>>> assert masked.fields[0].equal([42, 10.5])
>>> assert masked.fields[1].equal([1, 3])
Iteration
>>> _ = [point for point in scalar_field]
"""
item = super().__getitem__(index)
try:
if issubclass(type(item), TensorFields):
if isinstance(index, tuple):
index = index[0]
if item.fields:
# circumvent the setter here.
with self._bypass_setters("fields", demand_existence=False):
item.fields = [
field.__getitem__(index) for field in item.fields
]
except IndexError as err: # noqa: F841 pylint: disable=possibly-unused-variable
warnings.warn(
"Index error occured for field.__getitem__. Error "
"message: {err}".format(**locals())
)
return item
| (self, index) |
21,163 | tfields.core | __new__ | null | def __new__(cls, tensors, *fields, **kwargs):
rigid = kwargs.pop("rigid", True)
obj = super(TensorFields, cls).__new__(cls, tensors, **kwargs)
if issubclass(type(tensors), TensorFields):
obj.fields = tensors.fields
elif not fields:
obj.fields = []
if fields:
# (over)write fields
obj.fields = fields
if rigid:
olen = len(obj)
field_lengths = [len(f) for f in obj.fields]
if not all(flen == olen for flen in field_lengths):
raise ValueError(
"Length of base ({olen}) should be the same as"
" the length of all fields ({field_lengths}).".format(**locals())
)
return obj
| (cls, tensors, *fields, **kwargs) |
21,170 | tfields.core | _cut_sympy | null | def _cut_sympy(self, expression):
if len(self) == 0:
return self.copy()
mask = self.evalf(expression) # coord_sys is handled by tmp_transform
mask.astype(bool)
inst = self[mask].copy()
# template
indices = np.arange(len(self))[mask]
template = tfields.TensorFields(np.empty((len(indices), 0)), indices)
return inst, template
| (self, expression) |
21,171 | tfields.core | _cut_template |
In principle, what we do is returning
self[template.fields[0]]
If the templates tensors is given (has no dimension 0), 0))), we switch
to only extruding the field entries according to the indices provided
by template.fields[0]. This allows the template to define additional
points, extending the object it should cut. This becomes relevant for
Mesh3D when adding vertices at the edge of the cut is necessary.
| def _cut_template(self, template):
"""
In principle, what we do is returning
self[template.fields[0]]
If the templates tensors is given (has no dimension 0), 0))), we switch
to only extruding the field entries according to the indices provided
by template.fields[0]. This allows the template to define additional
points, extending the object it should cut. This becomes relevant for
Mesh3D when adding vertices at the edge of the cut is necessary.
"""
# Redirect fields
fields = []
if template.fields and issubclass(type(self), TensorFields):
template_field = np.array(template.fields[0])
if len(self) > 0:
# if new vertices have been created in the template, it is in principle unclear
# what fields we have to refer to. Thus in creating the template, we gave np.nan.
# To make it fast, we replace nan with 0 as a dummy and correct the field entries
# afterwards with np.nan.
nan_mask = np.isnan(template_field)
template_field[nan_mask] = 0 # dummy reference to index 0.
template_field = template_field.astype(int)
for field in self.fields:
projected_field = field[template_field]
projected_field[nan_mask] = np.nan # correction for nan
fields.append(projected_field)
if dim(template) == 0:
# for speed circumvent __getitem__ of the complexer subclasses
tensors = Tensors(self)[template.fields[0]]
else:
tensors = template
return type(self)(tensors, *fields)
| (self, template) |
21,182 | tfields.core | cut |
Extract a part of the object according to the logic given
by <expression>.
Args:
expression (sympy logical expression|tfields.TensorFields): logical
expression which will be evaluated. use symbols x, y and z.
If tfields.TensorFields or subclass is given, the expression
refers to a template.
coord_sys (str): coord_sys to evaluate the expression in. Only
active for template expression
Examples:
>>> import tfields
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> p.cut(x > 0).equal([[1, 2, 3],
... [4, 5, 6],
... [1, 2, -6],
... [1, 0, -1]])
True
combinations of cuts
>>> cut_expression = (x > 0) & (z < 0)
>>> combi_cut = p.cut(cut_expression)
>>> combi_cut.equal([[1, 2, -6], [1, 0, -1]])
True
Templates can be used to speed up the repeated cuts on the same
underlying tensor with the same expression but new fields.
First let us cut a but request the template on return:
>>> field1 = list(range(len(p)))
>>> tf = tfields.TensorFields(p, field1)
>>> tf_cut, template = tf.cut(cut_expression,
... return_template=True)
Now repeat the cut with a new field:
>>> field2 = p
>>> tf.fields.append(field2)
>>> tf_template_cut = tf.cut(template)
>>> tf_template_cut.equal(combi_cut)
True
>>> tf_template_cut.fields[0].equal([2, 4])
True
>>> tf_template_cut.fields[1].equal(combi_cut)
True
Returns:
copy of self with cut applied
[optional: template - requires <return_template> switch]
| def cut(self, expression, coord_sys=None, return_template=False, **kwargs):
"""
Extract a part of the object according to the logic given
by <expression>.
Args:
expression (sympy logical expression|tfields.TensorFields): logical
expression which will be evaluated. use symbols x, y and z.
If tfields.TensorFields or subclass is given, the expression
refers to a template.
coord_sys (str): coord_sys to evaluate the expression in. Only
active for template expression
Examples:
>>> import tfields
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> p.cut(x > 0).equal([[1, 2, 3],
... [4, 5, 6],
... [1, 2, -6],
... [1, 0, -1]])
True
combinations of cuts
>>> cut_expression = (x > 0) & (z < 0)
>>> combi_cut = p.cut(cut_expression)
>>> combi_cut.equal([[1, 2, -6], [1, 0, -1]])
True
Templates can be used to speed up the repeated cuts on the same
underlying tensor with the same expression but new fields.
First let us cut a but request the template on return:
>>> field1 = list(range(len(p)))
>>> tf = tfields.TensorFields(p, field1)
>>> tf_cut, template = tf.cut(cut_expression,
... return_template=True)
Now repeat the cut with a new field:
>>> field2 = p
>>> tf.fields.append(field2)
>>> tf_template_cut = tf.cut(template)
>>> tf_template_cut.equal(combi_cut)
True
>>> tf_template_cut.fields[0].equal([2, 4])
True
>>> tf_template_cut.fields[1].equal(combi_cut)
True
Returns:
copy of self with cut applied
[optional: template - requires <return_template> switch]
"""
with self.tmp_transform(coord_sys or self.coord_sys):
if issubclass(type(expression), TensorFields):
template = expression
obj = self._cut_template(template)
else:
obj, template = self._cut_sympy(expression, **kwargs)
if return_template:
return obj, template
return obj
| (self, expression, coord_sys=None, return_template=False, **kwargs) |
21,186 | tfields.core | equal |
Test, whether the instance has the same content as other.
Args:
other (iterable)
**kwargs: see Tensors.equal
| def equal(self, other, **kwargs): # pylint: disable=arguments-differ
"""
Test, whether the instance has the same content as other.
Args:
other (iterable)
**kwargs: see Tensors.equal
"""
if not issubclass(type(other), Tensors):
return super(TensorFields, self).equal(other, **kwargs)
with other.tmp_transform(self.coord_sys):
mask = super(TensorFields, self).equal(other, **kwargs)
if issubclass(type(other), TensorFields):
if len(self.fields) != len(other.fields):
mask &= False
else:
for i, field in enumerate(self.fields):
mask &= field.equal(other.fields[i], **kwargs)
return mask
| (self, other, **kwargs) |
21,196 | tfields.planes_3d | plot |
forward to Mesh3D plotting
| def plot(self, **kwargs): # pragma: no cover
"""
forward to Mesh3D plotting
"""
artists = []
centers = np.array(self)
norms = np.array(self.fields[0])
for i in range(len(self)):
artists.append(rna.plotting.plot_plane(centers[i], norms[i], **kwargs))
return artists
| (self, **kwargs) |
21,199 | tfields.planes_3d | symbolic |
Returns:
list: list with sympy.Plane objects
| def symbolic(self):
"""
Returns:
list: list with sympy.Plane objects
"""
return [
sympy.Plane(point, normal_vector=vector)
for point, vector in zip(self, self.fields[0])
]
| (self) |
21,204 | tfields.points_3d | Points3D |
Points3D is a general class for 3D Point operations and storage.
Points are stored in np.arrays of shape (len, 3).
Thus the three coordinates of the Points stay close.
Args:
points3DInstance -> copy constructor
[points3DInstance1, points3DInstance2, ...] -> coord_sys are correctly treated
list of coordinates (see examples)
Kwargs:
coord_sys (str):
Use tfields.bases.CARTESIAN -> x, y, z
Use tfields.bases.CYLINDER -> r, phi, z
Use tfields.bases.SPHERICAL -> r, phi, theta
Examples:
Initializing with 3 vectors
>>> import tfields
>>> import numpy as np
>>> p1 = tfields.Points3D([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
>>> assert p1.equal([[1., 2., 3.],
... [4., 5., 6.],
... [1., 2., -6.]])
Initializing with listof coordinates
>>> p2 = tfields.Points3D(np.array([[1., 2., 3., 4, 5,],
... [4., 5., 6., 7, 8],
... [1, 2, -6, -1, 0]]).T)
>>> assert p2.equal(
... [[ 1., 4., 1.],
... [ 2., 5., 2.],
... [ 3., 6., -6.],
... [ 4., 7., -1.],
... [ 5., 8., 0.]], atol=1e-8)
>>> p2.transform(tfields.bases.CYLINDER)
>>> assert p2.equal(
... [[ 4.12310563, 1.32581766, 1.],
... [ 5.38516481, 1.19028995, 2.],
... [ 6.70820393, 1.10714872, -6.],
... [ 8.06225775, 1.05165021, -1.],
... [ 9.43398113, 1.01219701, 0.]], atol=1e-8)
Copy constructor with one instance preserves coord_sys of instance
>>> assert tfields.Points3D(p2).coord_sys == p2.coord_sys
Unless you specify other:
>>> assert tfields.Points3D(p2,
... coord_sys=tfields.bases.CARTESIAN).equal(
... [[ 1., 4., 1.],
... [ 2., 5., 2.],
... [ 3., 6., -6.],
... [ 4., 7., -1.],
... [ 5., 8., 0.]], atol=1e-8)
Copy constructor with many instances chooses majority of coordinates
systems to avoid much transformation
>>> assert tfields.Points3D.merged(p1, p2, p1).equal(
... [[ 1., 2., 3.],
... [ 4., 5., 6.],
... [ 1., 2., -6.],
... [ 1., 4., 1.],
... [ 2., 5., 2.],
... [ 3., 6., -6.],
... [ 4., 7., -1.],
... [ 5., 8., 0.],
... [ 1., 2., 3.],
... [ 4., 5., 6.],
... [ 1., 2., -6.]], atol=1e-8)
>>> p1.transform(tfields.bases.CYLINDER)
unless specified other. Here it is specified
>>> assert tfields.Points3D.merged(
... p1, p2, coord_sys=tfields.bases.CYLINDER).equal(
... [[ 2.23606798, 1.10714872, 3. ],
... [ 6.40312424, 0.89605538, 6. ],
... [ 2.23606798, 1.10714872, -6. ],
... [ 4.12310563, 1.32581766, 1. ],
... [ 5.38516481, 1.19028995, 2. ],
... [ 6.70820393, 1.10714872, -6. ],
... [ 8.06225775, 1.05165021, -1. ],
... [ 9.43398113, 1.01219701, 0. ]], atol=1e-8)
Shape is always (..., 3)
>>> p = tfields.Points3D([[1., 2., 3.], [4., 5., 6.],
... [1, 2, -6], [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> p.shape
(6, 3)
Empty array will create an ndarray of the form (0, 3)
>>> tfields.Points3D([])
Points3D([], shape=(0, 3), dtype=float64)
Use it as np.ndarrays -> masking etc. is inherited
>>> mask = np.array([True, False, True, False, False, True])
>>> mp = p[mask].copy()
Copy constructor
>>> assert mp.equal(
... [[ 1., 2., 3.],
... [ 1., 2., -6.],
... [ 0., 1., -1.]])
>>> assert tfields.Points3D(mp).equal(
... [[ 1., 2., 3.],
... [ 1., 2., -6.],
... [ 0., 1., -1.]])
Coordinate system is implemented. Default is cartesian
>>> p_cart = p.copy()
>>> p.transform(tfields.bases.CYLINDER)
>>> assert p.equal(
... tfields.Points3D([[2.236, 1.107, 3.],
... [6.403, 0.896, 6.],
... [2.236, 1.107, -6.],
... [7.071, -2.356, -5.],
... [1. , 0. , -1.],
... [1. , 1.571, -1.]],
... coord_sys=tfields.bases.CYLINDER),
... atol=1e-3)
>>> p.transform(tfields.bases.CARTESIAN)
>>> assert p.equal(p_cart, atol=1e-15)
| class Points3D(tfields.Tensors):
# pylint: disable=R0904
"""
Points3D is a general class for 3D Point operations and storage.
Points are stored in np.arrays of shape (len, 3).
Thus the three coordinates of the Points stay close.
Args:
points3DInstance -> copy constructor
[points3DInstance1, points3DInstance2, ...] -> coord_sys are correctly treated
list of coordinates (see examples)
Kwargs:
coord_sys (str):
Use tfields.bases.CARTESIAN -> x, y, z
Use tfields.bases.CYLINDER -> r, phi, z
Use tfields.bases.SPHERICAL -> r, phi, theta
Examples:
Initializing with 3 vectors
>>> import tfields
>>> import numpy as np
>>> p1 = tfields.Points3D([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
>>> assert p1.equal([[1., 2., 3.],
... [4., 5., 6.],
... [1., 2., -6.]])
Initializing with listof coordinates
>>> p2 = tfields.Points3D(np.array([[1., 2., 3., 4, 5,],
... [4., 5., 6., 7, 8],
... [1, 2, -6, -1, 0]]).T)
>>> assert p2.equal(
... [[ 1., 4., 1.],
... [ 2., 5., 2.],
... [ 3., 6., -6.],
... [ 4., 7., -1.],
... [ 5., 8., 0.]], atol=1e-8)
>>> p2.transform(tfields.bases.CYLINDER)
>>> assert p2.equal(
... [[ 4.12310563, 1.32581766, 1.],
... [ 5.38516481, 1.19028995, 2.],
... [ 6.70820393, 1.10714872, -6.],
... [ 8.06225775, 1.05165021, -1.],
... [ 9.43398113, 1.01219701, 0.]], atol=1e-8)
Copy constructor with one instance preserves coord_sys of instance
>>> assert tfields.Points3D(p2).coord_sys == p2.coord_sys
Unless you specify other:
>>> assert tfields.Points3D(p2,
... coord_sys=tfields.bases.CARTESIAN).equal(
... [[ 1., 4., 1.],
... [ 2., 5., 2.],
... [ 3., 6., -6.],
... [ 4., 7., -1.],
... [ 5., 8., 0.]], atol=1e-8)
Copy constructor with many instances chooses majority of coordinates
systems to avoid much transformation
>>> assert tfields.Points3D.merged(p1, p2, p1).equal(
... [[ 1., 2., 3.],
... [ 4., 5., 6.],
... [ 1., 2., -6.],
... [ 1., 4., 1.],
... [ 2., 5., 2.],
... [ 3., 6., -6.],
... [ 4., 7., -1.],
... [ 5., 8., 0.],
... [ 1., 2., 3.],
... [ 4., 5., 6.],
... [ 1., 2., -6.]], atol=1e-8)
>>> p1.transform(tfields.bases.CYLINDER)
unless specified other. Here it is specified
>>> assert tfields.Points3D.merged(
... p1, p2, coord_sys=tfields.bases.CYLINDER).equal(
... [[ 2.23606798, 1.10714872, 3. ],
... [ 6.40312424, 0.89605538, 6. ],
... [ 2.23606798, 1.10714872, -6. ],
... [ 4.12310563, 1.32581766, 1. ],
... [ 5.38516481, 1.19028995, 2. ],
... [ 6.70820393, 1.10714872, -6. ],
... [ 8.06225775, 1.05165021, -1. ],
... [ 9.43398113, 1.01219701, 0. ]], atol=1e-8)
Shape is always (..., 3)
>>> p = tfields.Points3D([[1., 2., 3.], [4., 5., 6.],
... [1, 2, -6], [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> p.shape
(6, 3)
Empty array will create an ndarray of the form (0, 3)
>>> tfields.Points3D([])
Points3D([], shape=(0, 3), dtype=float64)
Use it as np.ndarrays -> masking etc. is inherited
>>> mask = np.array([True, False, True, False, False, True])
>>> mp = p[mask].copy()
Copy constructor
>>> assert mp.equal(
... [[ 1., 2., 3.],
... [ 1., 2., -6.],
... [ 0., 1., -1.]])
>>> assert tfields.Points3D(mp).equal(
... [[ 1., 2., 3.],
... [ 1., 2., -6.],
... [ 0., 1., -1.]])
Coordinate system is implemented. Default is cartesian
>>> p_cart = p.copy()
>>> p.transform(tfields.bases.CYLINDER)
>>> assert p.equal(
... tfields.Points3D([[2.236, 1.107, 3.],
... [6.403, 0.896, 6.],
... [2.236, 1.107, -6.],
... [7.071, -2.356, -5.],
... [1. , 0. , -1.],
... [1. , 1.571, -1.]],
... coord_sys=tfields.bases.CYLINDER),
... atol=1e-3)
>>> p.transform(tfields.bases.CARTESIAN)
>>> assert p.equal(p_cart, atol=1e-15)
"""
def __new__(cls, tensors, **kwargs):
if not issubclass(type(tensors), Points3D):
kwargs["dim"] = 3
return super(Points3D, cls).__new__(cls, tensors, **kwargs)
def balls(self, radius, spacing=(5, 3)):
"""
Args:
radius (float): radius of spheres
spacing (tuple of int): n_phi, n_theta
Returns:
tfields.Mesh3D: Builds a sphere around each point with a resolution
defined by spacing and given radius
"""
sphere = tfields.Mesh3D.grid(
(radius, radius, 1),
(-np.pi, np.pi, spacing[0]),
(-np.pi / 2, np.pi / 2, spacing[1]),
coord_sys="spherical",
)
sphere.transform("cartesian")
balls = []
with self.tmp_transform("cartesian"):
for point in self:
ball = sphere.copy()
ball += point
balls.append(ball)
return tfields.Mesh3D.merged(*balls)
| (tensors, **kwargs) |
21,208 | tfields.points_3d | __new__ | null | def __new__(cls, tensors, **kwargs):
if not issubclass(type(tensors), Points3D):
kwargs["dim"] = 3
return super(Points3D, cls).__new__(cls, tensors, **kwargs)
| (cls, tensors, **kwargs) |
21,212 | tfields.core | _args | null | def _args(self):
return (np.array(self),)
| (self) |
21,216 | tfields.core | _kwargs | null | def _kwargs(self):
return dict((attr, getattr(self, attr)) for attr in self._iter_slots())
| (self) |
21,221 | tfields.core | _weights |
transformer method for weights inputs.
Args:
weights (np.ndarray | None):
If weights is None, use np.ones
Otherwise just pass the weights.
rigid (bool): demand equal weights and tensor length
Returns:
weight array
| def _weights(self, weights, rigid=True):
"""
transformer method for weights inputs.
Args:
weights (np.ndarray | None):
If weights is None, use np.ones
Otherwise just pass the weights.
rigid (bool): demand equal weights and tensor length
Returns:
weight array
"""
# set weights to 1.0 if weights is None
if weights is None:
weights = np.ones(len(self))
if rigid:
if not len(weights) == len(self):
raise ValueError("Equal number of weights as tensors demanded.")
return weights
| (self, weights, rigid=True) |
21,222 | tfields.points_3d | balls |
Args:
radius (float): radius of spheres
spacing (tuple of int): n_phi, n_theta
Returns:
tfields.Mesh3D: Builds a sphere around each point with a resolution
defined by spacing and given radius
| def balls(self, radius, spacing=(5, 3)):
"""
Args:
radius (float): radius of spheres
spacing (tuple of int): n_phi, n_theta
Returns:
tfields.Mesh3D: Builds a sphere around each point with a resolution
defined by spacing and given radius
"""
sphere = tfields.Mesh3D.grid(
(radius, radius, 1),
(-np.pi, np.pi, spacing[0]),
(-np.pi / 2, np.pi / 2, spacing[1]),
coord_sys="spherical",
)
sphere.transform("cartesian")
balls = []
with self.tmp_transform("cartesian"):
for point in self:
ball = sphere.copy()
ball += point
balls.append(ball)
return tfields.Mesh3D.merged(*balls)
| (self, radius, spacing=(5, 3)) |
21,231 | tfields.core | equal |
Evaluate, whether the instance has the same content as other.
Args:
optional:
rtol (float)
atol (float)
equal_nan (bool)
see numpy.isclose
| def equal(
self, other, rtol=None, atol=None, equal_nan=False, return_bool=True
): # noqa: E501 pylint: disable=too-many-arguments
"""
Evaluate, whether the instance has the same content as other.
Args:
optional:
rtol (float)
atol (float)
equal_nan (bool)
see numpy.isclose
"""
if issubclass(type(other), Tensors) and self.coord_sys != other.coord_sys:
other = other.copy()
other.transform(self.coord_sys)
self_array, other_array = np.asarray(self), np.asarray(other)
if rtol is None and atol is None:
mask = self_array == other_array
if equal_nan:
both_nan = np.isnan(self_array) & np.isnan(other_array)
mask[both_nan] = both_nan[both_nan]
else:
if rtol is None:
rtol = 0.0
if atol is None:
atol = 0.0
mask = np.isclose(
self_array, other_array, rtol=rtol, atol=atol, equal_nan=equal_nan
)
if return_bool:
return bool(np.all(mask))
return mask
| (self, other, rtol=None, atol=None, equal_nan=False, return_bool=True) |
21,241 | tfields.core | plot |
Generic plotting method of Tensors.
Forwarding to rna.plotting.plot_tensor
| def plot(self, *args, **kwargs):
"""
Generic plotting method of Tensors.
Forwarding to rna.plotting.plot_tensor
"""
artist = rna.plotting.plot_tensor(
self, *args, **kwargs
) # pylint: disable=no-member
return artist
| (self, *args, **kwargs) |
21,247 | tfields.core | TensorFields |
Discrete Tensor Field
Args:
tensors (array): base tensors
*fields (array): multiple fields assigned to one base tensor. Fields
themself are also of type tensor
**kwargs:
rigid (bool): demand equal field and tensor lenght
... : see tfields.Tensors
Examples:
>>> import tfields
>>> from tfields import Tensors, TensorFields
>>> scalars = Tensors([0, 1, 2])
>>> vectors = Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> scalar_field = TensorFields(vectors, scalars)
>>> scalar_field.rank
1
>>> scalar_field.fields[0].rank
0
>>> vectorField = TensorFields(vectors, vectors)
>>> vectorField.fields[0].rank
1
>>> vectorField.fields[0].dim
3
>>> multiField = TensorFields(vectors, scalars, vectors)
>>> multiField.fields[0].dim
1
>>> multiField.fields[1].dim
3
Empty initialization
>>> empty_field = TensorFields([], dim=3)
>>> assert empty_field.shape == (0, 3)
>>> assert empty_field.fields == []
Directly initializing with lists or arrays
>>> vec_field_raw = tfields.TensorFields([[0, 1, 2], [3, 4, 5]],
... [1, 6], [2, 7])
>>> assert len(vec_field_raw.fields) == 2
Copying
>>> cp = TensorFields(vectorField)
>>> assert vectorField.equal(cp)
Copying takes care of coord_sys
>>> cp.transform(tfields.bases.CYLINDER)
>>> cp_cyl = TensorFields(cp)
>>> assert cp_cyl.coord_sys == tfields.bases.CYLINDER
Copying with changing type
>>> tcp = TensorFields(vectorField, dtype=int)
>>> assert vectorField.equal(tcp)
>>> assert tcp.dtype == int
Raises:
TypeError:
>>> import tfields
>>> tfields.TensorFields([1, 2, 3], [3]) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Length of base (3) should be the same as the length of all fields ([1]).
This error can be suppressed by setting rigid=False
>>> loose = tfields.TensorFields([1, 2, 3], [3], rigid=False)
>>> assert len(loose) != 1
| class TensorFields(Tensors):
"""
Discrete Tensor Field
Args:
tensors (array): base tensors
*fields (array): multiple fields assigned to one base tensor. Fields
themself are also of type tensor
**kwargs:
rigid (bool): demand equal field and tensor lenght
... : see tfields.Tensors
Examples:
>>> import tfields
>>> from tfields import Tensors, TensorFields
>>> scalars = Tensors([0, 1, 2])
>>> vectors = Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> scalar_field = TensorFields(vectors, scalars)
>>> scalar_field.rank
1
>>> scalar_field.fields[0].rank
0
>>> vectorField = TensorFields(vectors, vectors)
>>> vectorField.fields[0].rank
1
>>> vectorField.fields[0].dim
3
>>> multiField = TensorFields(vectors, scalars, vectors)
>>> multiField.fields[0].dim
1
>>> multiField.fields[1].dim
3
Empty initialization
>>> empty_field = TensorFields([], dim=3)
>>> assert empty_field.shape == (0, 3)
>>> assert empty_field.fields == []
Directly initializing with lists or arrays
>>> vec_field_raw = tfields.TensorFields([[0, 1, 2], [3, 4, 5]],
... [1, 6], [2, 7])
>>> assert len(vec_field_raw.fields) == 2
Copying
>>> cp = TensorFields(vectorField)
>>> assert vectorField.equal(cp)
Copying takes care of coord_sys
>>> cp.transform(tfields.bases.CYLINDER)
>>> cp_cyl = TensorFields(cp)
>>> assert cp_cyl.coord_sys == tfields.bases.CYLINDER
Copying with changing type
>>> tcp = TensorFields(vectorField, dtype=int)
>>> assert vectorField.equal(tcp)
>>> assert tcp.dtype == int
Raises:
TypeError:
>>> import tfields
>>> tfields.TensorFields([1, 2, 3], [3]) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Length of base (3) should be the same as the length of all fields ([1]).
This error can be suppressed by setting rigid=False
>>> loose = tfields.TensorFields([1, 2, 3], [3], rigid=False)
>>> assert len(loose) != 1
"""
__slots__ = ["coord_sys", "name", "fields"]
__slot_setters__ = [tfields.bases.get_coord_system_name, None, as_fields]
def __new__(cls, tensors, *fields, **kwargs):
rigid = kwargs.pop("rigid", True)
obj = super(TensorFields, cls).__new__(cls, tensors, **kwargs)
if issubclass(type(tensors), TensorFields):
obj.fields = tensors.fields
elif not fields:
obj.fields = []
if fields:
# (over)write fields
obj.fields = fields
if rigid:
olen = len(obj)
field_lengths = [len(f) for f in obj.fields]
if not all(flen == olen for flen in field_lengths):
raise ValueError(
"Length of base ({olen}) should be the same as"
" the length of all fields ({field_lengths}).".format(**locals())
)
return obj
def _args(self) -> tuple:
return super()._args() + tuple(self.fields)
def _kwargs(self) -> dict:
content = super()._kwargs()
content.pop("fields") # instantiated via _args
return content
def __getitem__(self, index):
"""
In addition to the usual, also slice fields
Examples:
>>> import tfields
>>> import numpy as np
>>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> scalar_field = tfields.TensorFields(
... vectors,
... [42, 21, 10.5],
... [1, 2, 3],
... [[0, 0], [-1, -1], [-2, -2]])
Slicing
>>> sliced = scalar_field[2:]
>>> assert isinstance(sliced, tfields.TensorFields)
>>> assert isinstance(sliced.fields[0], tfields.Tensors)
>>> assert sliced.fields[0].equal([10.5])
Picking
>>> picked = scalar_field[1]
>>> assert np.array_equal(picked, [0, 0, 1])
>>> assert np.array_equal(picked.fields[0], 21)
Masking
>>> masked = scalar_field[np.array([True, False, True])]
>>> assert masked.equal([[0, 0, 0], [0, -1, 0]])
>>> assert masked.fields[0].equal([42, 10.5])
>>> assert masked.fields[1].equal([1, 3])
Iteration
>>> _ = [point for point in scalar_field]
"""
item = super().__getitem__(index)
try:
if issubclass(type(item), TensorFields):
if isinstance(index, tuple):
index = index[0]
if item.fields:
# circumvent the setter here.
with self._bypass_setters("fields", demand_existence=False):
item.fields = [
field.__getitem__(index) for field in item.fields
]
except IndexError as err: # noqa: F841 pylint: disable=possibly-unused-variable
warnings.warn(
"Index error occured for field.__getitem__. Error "
"message: {err}".format(**locals())
)
return item
def __setitem__(self, index, item):
"""
In addition to the usual, also slice fields
Examples:
>>> import tfields
>>> import numpy as np
>>> original = tfields.TensorFields(
... [[0, 0, 0], [0, 0, 1], [0, -1, 0]],
... [42, 21, 10.5], [1, 2, 3])
>>> obj = tfields.TensorFields(
... [[0, 0, 0], [0, 0, np.nan],
... [0, -1, 0]], [42, 22, 10.5], [1, -1, 3])
>>> slice_obj = obj.copy()
>>> assert not obj.equal(original)
>>> obj[1] = original[1]
>>> assert obj[:2].equal(original[:2])
>>> assert not slice_obj.equal(original)
>>> slice_obj[:] = original[:]
>>> assert slice_obj.equal(original)
"""
super(TensorFields, self).__setitem__(index, item)
if issubclass(type(item), TensorFields):
if isinstance(index, slice):
for i, field in enumerate(item.fields):
self.fields[i].__setitem__(index, field)
elif isinstance(index, tuple):
for i, field in enumerate(item.fields):
self.fields[i].__setitem__(index[0], field)
else:
for i, field in enumerate(item.fields):
self.fields[i].__setitem__(index, field)
@classmethod
def merged(cls, *objects, **kwargs):
if not all(isinstance(o, cls) for o in objects):
# Note: could allow if all map_fields are none
raise TypeError(
"Merge constructor only accepts {cls} instances."
"Got objects of types {types} instead.".format(
cls=cls,
types=[type(o) for o in objects],
)
)
return_value = super(TensorFields, cls).merged(*objects, **kwargs)
return_templates = kwargs.get("return_templates", False)
if return_templates:
inst, templates = return_value
else:
inst, templates = (return_value, None)
fields = []
if all(len(obj.fields) == len(objects[0].fields) for obj in objects):
for fld_idx in range(len(objects[0].fields)):
field = tfields.Tensors.merged(
*[obj.fields[fld_idx] for obj in objects]
)
fields.append(field)
inst = cls.__new__(cls, inst, *fields)
if return_templates: # pylint: disable=no-else-return
return inst, templates
else:
return inst
def transform_field(self, coord_sys, field_index=0):
"""
Transform the field to the coordinate system of choice.
NOTE: This is not yet any way generic!!! Have a look at Einsteinpy and actual status of
sympy for further implementation
"""
self.fields[field_index].transform(coord_sys, position=self)
@property
def names(self):
"""
Retrive the names of the fields as a list
Examples:
>>> import tfields
>>> s = tfields.Tensors([1,2,3], name=1.)
>>> tf = tfields.TensorFields(s, *[s]*10)
>>> assert len(tf.names) == 10
>>> assert set(tf.names) == {1.}
>>> tf.names = range(10)
>>> tf.names
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
return [f.name for f in self.fields]
@names.setter
def names(self, names):
if not len(names) == len(self.fields):
raise ValueError(
"len(names) ({0}) != len(fields) ({1})".format(
len(names), len(self.fields)
)
)
for i, name in enumerate(names):
self.fields[i].name = name
def equal(self, other, **kwargs): # pylint: disable=arguments-differ
"""
Test, whether the instance has the same content as other.
Args:
other (iterable)
**kwargs: see Tensors.equal
"""
if not issubclass(type(other), Tensors):
return super(TensorFields, self).equal(other, **kwargs)
with other.tmp_transform(self.coord_sys):
mask = super(TensorFields, self).equal(other, **kwargs)
if issubclass(type(other), TensorFields):
if len(self.fields) != len(other.fields):
mask &= False
else:
for i, field in enumerate(self.fields):
mask &= field.equal(other.fields[i], **kwargs)
return mask
def _weights(self, weights, rigid=True):
"""
Expansion of Tensors._weights with integer inputs
Args:
weights (np.ndarray | int | None):
if weights is int: use field at index <weights>
else: see Tensors._weights
"""
if isinstance(weights, int):
weights = self.fields[weights]
return super(TensorFields, self)._weights(weights, rigid=rigid)
def plot(self, *args, **kwargs):
"""
Generic plotting method of TensorFields.
Args:
field_index: index of the field to plot (as quiver by default)
normalize: If True, normalize the field vectors to show only the direction
color: additional str argument 'norm' added. If color="norm", color with the norm.
"""
field_index = kwargs.pop("field_index", None)
field_args = ["normalize"]
if field_index is None:
for field_arg in field_args:
if field_arg in kwargs:
kwargs.pop(field_arg)
LOGGER.warning("Unused option %s", field_arg)
artist = super(TensorFields, self).plot(*args, **kwargs)
else:
normalize_field = kwargs.pop("normalize", False)
color = kwargs.get("color", None)
field = self.fields[field_index].copy()
# this tranfomration is compmlicated. Transforming the field is not yet understood
# if self.dim == field.dim:
# field.transform(self.coord_sys)
# else:
# logging.debug(
# "Careful: Plotting tensors with field of"
# "different dimension. No coord_sys check performed."
# )
if color == "norm":
norm = field.norm()
kwargs["color"] = norm
if normalize_field:
field = field.normalized()
if field.dim <= 3:
artist = (
rna.plotting.plot_tensor( # noqa: E501 pylint: disable=no-member
self, *args, field, **kwargs
)
)
else:
raise NotImplementedError(
"Field of dimension {field.dim}".format(**locals())
)
return artist
| (tensors, *fields, **kwargs) |
21,285 | tfields.core | plot |
Generic plotting method of TensorFields.
Args:
field_index: index of the field to plot (as quiver by default)
normalize: If True, normalize the field vectors to show only the direction
color: additional str argument 'norm' added. If color="norm", color with the norm.
| def plot(self, *args, **kwargs):
"""
Generic plotting method of TensorFields.
Args:
field_index: index of the field to plot (as quiver by default)
normalize: If True, normalize the field vectors to show only the direction
color: additional str argument 'norm' added. If color="norm", color with the norm.
"""
field_index = kwargs.pop("field_index", None)
field_args = ["normalize"]
if field_index is None:
for field_arg in field_args:
if field_arg in kwargs:
kwargs.pop(field_arg)
LOGGER.warning("Unused option %s", field_arg)
artist = super(TensorFields, self).plot(*args, **kwargs)
else:
normalize_field = kwargs.pop("normalize", False)
color = kwargs.get("color", None)
field = self.fields[field_index].copy()
# this tranfomration is compmlicated. Transforming the field is not yet understood
# if self.dim == field.dim:
# field.transform(self.coord_sys)
# else:
# logging.debug(
# "Careful: Plotting tensors with field of"
# "different dimension. No coord_sys check performed."
# )
if color == "norm":
norm = field.norm()
kwargs["color"] = norm
if normalize_field:
field = field.normalized()
if field.dim <= 3:
artist = (
rna.plotting.plot_tensor( # noqa: E501 pylint: disable=no-member
self, *args, field, **kwargs
)
)
else:
raise NotImplementedError(
"Field of dimension {field.dim}".format(**locals())
)
return artist
| (self, *args, **kwargs) |
21,292 | tfields.tensor_grid | TensorGrid |
A Tensor Grid is a TensorField which is aware of it's grid nature, which is order of iteration
(iter-order) over the base vectors (base_vectors).
Args:
*base_vectors (tuple): indices of the axes which should be iterated
**kwargs:
num (np.array): same as np.linspace 'num'
iter_order (np.array): index order of building the grid.
further: see TensorFields class
| class TensorGrid(TensorFields):
"""
A Tensor Grid is a TensorField which is aware of it's grid nature, which is order of iteration
(iter-order) over the base vectors (base_vectors).
Args:
*base_vectors (tuple): indices of the axes which should be iterated
**kwargs:
num (np.array): same as np.linspace 'num'
iter_order (np.array): index order of building the grid.
further: see TensorFields class
"""
__slots__ = ["coord_sys", "name", "fields", "base_vectors", "num", "iter_order"]
__slot_setters__ = TensorFields.__slot_setters__ + [
None,
None,
None,
]
def __new__(cls, tensors, *fields, **kwargs):
if isinstance(tensors, TensorGrid):
default_base_vectors = tensors.base_vectors
default_num = tensors.num
default_iter_order = tensors.iter_order
else:
default_base_vectors = kwargs.pop("base_vectors", None)
default_num = None
default_iter_order = None
base_vectors = kwargs.pop("base_vectors", default_base_vectors)
num = kwargs.pop("num", default_num)
iter_order = kwargs.pop("iter_order", default_iter_order)
obj = super(TensorGrid, cls).__new__(cls, tensors, *fields, **kwargs)
if len(base_vectors) == 3:
base_vectors = tuple(tuple(bv) for bv in base_vectors)
base_vectors = grid.ensure_complex(*base_vectors)
if (
isinstance(base_vectors, (tuple, list))
and base_vectors
and len(base_vectors[0]) == 3
):
if num is None:
num = np.array([int(bv[2].imag) for bv in base_vectors], dtype=int)
base_vectors = np.transpose([[bv[0], bv[1]] for bv in base_vectors])
# base_vectors
base_vectors = Tensors(base_vectors, coord_sys=obj.coord_sys)
if len(base_vectors) != 2:
raise ValueError(
f"base_vectors must be of lenght 2. Lenght is {len(base_vectors)}."
)
obj.base_vectors = base_vectors
# num
if num is None:
num = np.array([1 for _ in range(base_vectors.dim)])
else:
num = np.array(num, dtype=int)
obj.num = num
# iter_order
if iter_order is None:
iter_order = np.arange(base_vectors.dim)
else:
iter_order = np.array(iter_order, dtype=int)
obj.iter_order = iter_order
if isinstance(tensors, TensorGrid):
if (obj.num != tensors.num).all() or (
obj.is_empty() and not obj.base_vectors.equal(tensors.base_vectors)
):
# copy constructor with shape change
return obj.empty(*obj.base_num_tuples(), iter_order=iter_order)
if (obj.iter_order != tensors.iter_order).all():
# iter_order was changed in copy constructor
obj.iter_order = (
tensors.iter_order
) # set to 'default_iter_order' and change later
obj.change_iter_order(iter_order)
return obj
def __getitem__(self, index):
if not self.is_empty():
return super().__getitem__(index)
item = self.explicit()
if not util.is_full_slice(index, item.shape):
# downgrade to TensorFields
item = TensorFields(item)
return item.__getitem__(index)
@classmethod
# pylint:disable=arguments-differ
def grid(cls, *base_vectors, tensors=None, fields=None, **kwargs):
"""
Build the grid (explicitly) from base vectors
Args:
explicit args: see __new__
**kwargs: see TensorFields
"""
iter_order = kwargs.pop("iter_order", np.arange(len(base_vectors)))
if tensors is None:
tensors = TensorFields.grid(*base_vectors, iter_order=iter_order, **kwargs)
obj = cls(tensors, base_vectors=base_vectors, iter_order=iter_order, **kwargs)
if fields:
# pylint:disable=attribute-defined-outside-init
obj.fields = fields
return obj
@classmethod
def empty(cls, *base_vectors, **kwargs):
"""
Build the grid (implicitly) from base vectors
"""
base_vectors = grid.ensure_complex(*base_vectors)
bv_lengths = [int(bv[2].imag) for bv in base_vectors]
tensors = np.empty(shape=(np.prod(bv_lengths), 0))
return cls.grid(*base_vectors, tensors=tensors, **kwargs)
@classmethod
def merged(cls, *objects, **kwargs):
if "base_vectors" not in kwargs:
base_vectors = None
for obj in objects:
if base_vectors is None:
base_vectors = obj.base_vectors
else:
if not all(
((a == b).all() for a, b in zip(base_vectors, obj.base_vectors))
):
raise NotImplementedError("Non-alligned base vectors")
kwargs.setdefault("base_vectors", base_vectors)
merge = super().merged(*objects, **kwargs)
return merge
def base_num_tuples(self):
"""
Returns the grid style base_vectors + num tuples
"""
return tuple(
(bv[0], bv[1], complex(0, n))
for bv, n in zip(self.base_vectors.T, self.num)
)
@property
def rank(self):
if self.is_empty():
return 1
return super().rank
def is_empty(self):
"""
Check if the object is an implicit grid (base points are empty but base_vectors and iter
order can be used to build the explicit grid's base points).
"""
return 0 in self.shape
def explicit(self):
"""
Build the grid explicitly (e.g. after changing base_vector, iter_order or init with empty)
"""
kwargs = {
attr: getattr(self, attr)
for attr in self.__slots__
if attr not in ("base_vectors", "num", "coord_sys")
}
base_num_tuples = self.base_num_tuples()
kwargs["coord_sys"] = self.base_vectors.coord_sys
obj = self.grid(*base_num_tuples, **kwargs)
obj.transform(self.coord_sys)
return obj
def change_iter_order(self, iter_order):
"""
Transform the iter order
"""
field_swap_indices = grid.change_iter_order(
# pylint:disable=access-member-before-definition
self.num,
self.iter_order,
iter_order,
)
for field in self.fields:
field[:] = field[field_swap_indices]
# pylint:disable=attribute-defined-outside-init
self.iter_order = iter_order
self[:] = self.explicit()
| (tensors, *fields, **kwargs) |
21,295 | tfields.tensor_grid | __getitem__ | null | def __getitem__(self, index):
if not self.is_empty():
return super().__getitem__(index)
item = self.explicit()
if not util.is_full_slice(index, item.shape):
# downgrade to TensorFields
item = TensorFields(item)
return item.__getitem__(index)
| (self, index) |
21,297 | tfields.tensor_grid | __new__ | null | def __new__(cls, tensors, *fields, **kwargs):
if isinstance(tensors, TensorGrid):
default_base_vectors = tensors.base_vectors
default_num = tensors.num
default_iter_order = tensors.iter_order
else:
default_base_vectors = kwargs.pop("base_vectors", None)
default_num = None
default_iter_order = None
base_vectors = kwargs.pop("base_vectors", default_base_vectors)
num = kwargs.pop("num", default_num)
iter_order = kwargs.pop("iter_order", default_iter_order)
obj = super(TensorGrid, cls).__new__(cls, tensors, *fields, **kwargs)
if len(base_vectors) == 3:
base_vectors = tuple(tuple(bv) for bv in base_vectors)
base_vectors = grid.ensure_complex(*base_vectors)
if (
isinstance(base_vectors, (tuple, list))
and base_vectors
and len(base_vectors[0]) == 3
):
if num is None:
num = np.array([int(bv[2].imag) for bv in base_vectors], dtype=int)
base_vectors = np.transpose([[bv[0], bv[1]] for bv in base_vectors])
# base_vectors
base_vectors = Tensors(base_vectors, coord_sys=obj.coord_sys)
if len(base_vectors) != 2:
raise ValueError(
f"base_vectors must be of lenght 2. Lenght is {len(base_vectors)}."
)
obj.base_vectors = base_vectors
# num
if num is None:
num = np.array([1 for _ in range(base_vectors.dim)])
else:
num = np.array(num, dtype=int)
obj.num = num
# iter_order
if iter_order is None:
iter_order = np.arange(base_vectors.dim)
else:
iter_order = np.array(iter_order, dtype=int)
obj.iter_order = iter_order
if isinstance(tensors, TensorGrid):
if (obj.num != tensors.num).all() or (
obj.is_empty() and not obj.base_vectors.equal(tensors.base_vectors)
):
# copy constructor with shape change
return obj.empty(*obj.base_num_tuples(), iter_order=iter_order)
if (obj.iter_order != tensors.iter_order).all():
# iter_order was changed in copy constructor
obj.iter_order = (
tensors.iter_order
) # set to 'default_iter_order' and change later
obj.change_iter_order(iter_order)
return obj
| (cls, tensors, *fields, **kwargs) |
21,312 | tfields.tensor_grid | base_num_tuples |
Returns the grid style base_vectors + num tuples
| def base_num_tuples(self):
"""
Returns the grid style base_vectors + num tuples
"""
return tuple(
(bv[0], bv[1], complex(0, n))
for bv, n in zip(self.base_vectors.T, self.num)
)
| (self) |
21,313 | tfields.tensor_grid | change_iter_order |
Transform the iter order
| def change_iter_order(self, iter_order):
"""
Transform the iter order
"""
field_swap_indices = grid.change_iter_order(
# pylint:disable=access-member-before-definition
self.num,
self.iter_order,
iter_order,
)
for field in self.fields:
field[:] = field[field_swap_indices]
# pylint:disable=attribute-defined-outside-init
self.iter_order = iter_order
self[:] = self.explicit()
| (self, iter_order) |
21,324 | tfields.tensor_grid | explicit |
Build the grid explicitly (e.g. after changing base_vector, iter_order or init with empty)
| def explicit(self):
"""
Build the grid explicitly (e.g. after changing base_vector, iter_order or init with empty)
"""
kwargs = {
attr: getattr(self, attr)
for attr in self.__slots__
if attr not in ("base_vectors", "num", "coord_sys")
}
base_num_tuples = self.base_num_tuples()
kwargs["coord_sys"] = self.base_vectors.coord_sys
obj = self.grid(*base_num_tuples, **kwargs)
obj.transform(self.coord_sys)
return obj
| (self) |
21,327 | tfields.tensor_grid | is_empty |
Check if the object is an implicit grid (base points are empty but base_vectors and iter
order can be used to build the explicit grid's base points).
| def is_empty(self):
"""
Check if the object is an implicit grid (base points are empty but base_vectors and iter
order can be used to build the explicit grid's base points).
"""
return 0 in self.shape
| (self) |
21,341 | tfields.core | TensorMaps |
Args:
tensors: see Tensors class
*fields (Tensors): see TensorFields class
**kwargs:
coord_sys ('str'): see Tensors class
maps (array-like): indices indicating a connection between the
tensors at the respective index positions
Examples:
>>> import tfields
>>> scalars = tfields.Tensors([0, 1, 2])
>>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> maps = [tfields.TensorFields([[0, 1, 2], [0, 1, 2]], [42, 21]),
... tfields.TensorFields([[1], [2]], [-42, -21])]
>>> mesh = tfields.TensorMaps(vectors, scalars,
... maps=maps)
>>> assert isinstance(mesh.maps, tfields.Maps)
>>> assert len(mesh.maps) == 2
>>> assert mesh.equal(tfields.TensorFields(vectors, scalars))
Copy constructor
>>> mesh_copy = tfields.TensorMaps(mesh)
Copying takes care of coord_sys
>>> mesh_copy.transform(tfields.bases.CYLINDER)
>>> mesh_cp_cyl = tfields.TensorMaps(mesh_copy)
>>> assert mesh_cp_cyl.coord_sys == tfields.bases.CYLINDER
| class TensorMaps(TensorFields):
"""
Args:
tensors: see Tensors class
*fields (Tensors): see TensorFields class
**kwargs:
coord_sys ('str'): see Tensors class
maps (array-like): indices indicating a connection between the
tensors at the respective index positions
Examples:
>>> import tfields
>>> scalars = tfields.Tensors([0, 1, 2])
>>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> maps = [tfields.TensorFields([[0, 1, 2], [0, 1, 2]], [42, 21]),
... tfields.TensorFields([[1], [2]], [-42, -21])]
>>> mesh = tfields.TensorMaps(vectors, scalars,
... maps=maps)
>>> assert isinstance(mesh.maps, tfields.Maps)
>>> assert len(mesh.maps) == 2
>>> assert mesh.equal(tfields.TensorFields(vectors, scalars))
Copy constructor
>>> mesh_copy = tfields.TensorMaps(mesh)
Copying takes care of coord_sys
>>> mesh_copy.transform(tfields.bases.CYLINDER)
>>> mesh_cp_cyl = tfields.TensorMaps(mesh_copy)
>>> assert mesh_cp_cyl.coord_sys == tfields.bases.CYLINDER
"""
__slots__ = ["coord_sys", "name", "fields", "maps"]
__slot_setters__ = [
tfields.bases.get_coord_system_name,
None,
as_fields,
as_maps,
]
def __new__(cls, tensors, *fields, **kwargs):
if issubclass(type(tensors), TensorMaps):
default_maps = tensors.maps
else:
default_maps = {}
maps = Maps(kwargs.pop("maps", default_maps))
obj = super(TensorMaps, cls).__new__(cls, tensors, *fields, **kwargs)
obj.maps = maps
return obj
def __getitem__(self, index):
"""
In addition to the usual, also slice fields
Examples:
>>> import tfields
>>> import numpy as np
>>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0],
... [1, 1, 1], [-1, -1, -1]])
>>> maps=[tfields.TensorFields([[0, 1, 2], [0, 1, 3], [2, 3, 4]],
... [[1, 2], [3, 4], [5, 6]]),
... tfields.TensorFields([[0], [1], [2], [3], [4]])]
>>> mesh = tfields.TensorMaps(vectors,
... [42, 21, 10.5, 1, 1],
... [1, 2, 3, 3, 3],
... maps=maps)
Slicing
>>> sliced = mesh[2:]
>>> assert isinstance(sliced, tfields.TensorMaps)
>>> assert isinstance(sliced.fields[0], tfields.Tensors)
>>> assert isinstance(sliced.maps[3], tfields.TensorFields)
>>> assert sliced.fields[0].equal([10.5, 1, 1])
>>> assert sliced.maps[3].equal([[0, 1, 2]])
>>> assert sliced.maps[3].fields[0].equal([[5, 6]])
Picking
>>> picked = mesh[1]
>>> assert np.array_equal(picked, [0, 0, 1])
>>> assert np.array_equal(picked.maps[3], np.empty((0, 3)))
>>> assert np.array_equal(picked.maps[1], [[0]])
Masking
>>> masked = mesh[np.array([True, False, True, True, True])]
>>> assert masked.equal([[0, 0, 0], [0, -1, 0],
... [1, 1, 1], [-1, -1, -1]])
>>> assert masked.fields[0].equal([42, 10.5, 1, 1])
>>> assert masked.fields[1].equal([1, 3, 3, 3])
>>> assert masked.maps[3].equal([[1, 2, 3]])
>>> assert masked.maps[1].equal([[0], [1], [2], [3]])
Iteration
>>> _ = [vertex for vertex in mesh]
"""
item = super(TensorMaps, self).__getitem__(index)
if issubclass(type(item), TensorMaps): # pylint: disable=too-many-nested-blocks
if isinstance(index, tuple):
index = index[0]
if item.maps:
item.maps = Maps(item.maps)
indices = np.arange(len(self))
keep_indices = indices[index]
if isinstance(keep_indices, (int, np.integer)):
keep_indices = [keep_indices]
delete_indices = set(indices).difference(set(keep_indices))
# correct all maps that contain deleted indices
for map_dim in self.maps:
# build mask, where the map should be deleted
map_delete_mask = np.full(
(len(self.maps[map_dim]),), False, dtype=bool
)
for i, map_ in enumerate( # pylint: disable=invalid-name
self.maps[map_dim]
):
for node_index in map_:
if node_index in delete_indices:
map_delete_mask[i] = True
break
map_mask = ~map_delete_mask
# build the correction counters
move_up_counter = np.zeros(self.maps[map_dim].shape, dtype=int)
for delete_index in delete_indices:
move_up_counter[self.maps[map_dim] > delete_index] -= 1
item.maps[map_dim] = (self.maps[map_dim] + move_up_counter)[
map_mask
]
return item
@classmethod
def merged(
cls, *objects, **kwargs
): # pylint: disable=too-many-locals,too-many-branches
if not all(isinstance(o, cls) for o in objects):
# Note: could allow if all face_fields are none
raise TypeError(
"Merge constructor only accepts {cls} instances.".format(**locals())
)
tensor_lengths = [len(o) for o in objects]
cum_tensor_lengths = [sum(tensor_lengths[:i]) for i in range(len(objects))]
return_value = super().merged(*objects, **kwargs)
return_templates = kwargs.get("return_templates", False)
if return_templates:
inst, templates = return_value
else:
inst, templates = (return_value, None)
dim_maps_dict = {} # {dim: {i: map_}
for i, obj in enumerate(objects):
for dimension, map_ in obj.maps.items():
map_ = map_ + cum_tensor_lengths[i]
if dimension not in dim_maps_dict:
dim_maps_dict[dimension] = {}
dim_maps_dict[dimension][i] = map_
maps = []
template_maps_list = [[] for i in range(len(objects))]
for dimension in sorted(dim_maps_dict):
# sort by object index
dim_maps = [
dim_maps_dict[dimension][i]
for i in range(len(objects))
if i in dim_maps_dict[dimension]
]
return_value = TensorFields.merged(
*dim_maps,
return_templates=return_templates,
)
if return_templates:
(
map_, # pylint: disable=invalid-name
dimension_map_templates,
) = return_value
for i in range(len(objects)):
template_maps_list[i].append(
(dimension, dimension_map_templates[i])
)
else:
map_ = return_value # pylint: disable=invalid-name
maps.append(map_)
inst.maps = maps
if return_templates: # pylint: disable=no-else-return
for i, template_maps in enumerate(template_maps_list):
# template maps will not have dimensions according to their
# tensors which are indices
templates[i] = tfields.TensorMaps(
templates[i], maps=Maps(template_maps)
)
return inst, templates
else:
return inst
def _cut_template(self, template):
"""
Args:
template (tfields.TensorMaps)
Examples:
>>> import tfields
>>> import numpy as np
Build mesh
>>> mmap = tfields.TensorFields([[0, 1, 2], [0, 3, 4]],
... [[42, 21], [-42, -21]])
>>> m = tfields.Mesh3D([[0]*3, [1]*3, [2]*3, [3]*3, [4]*3],
... [0.0, 0.1, 0.2, 0.3, 0.4],
... [0.0, -0.1, -0.2, -0.3, -0.4],
... maps=[mmap])
Build template
>>> tmap = tfields.TensorFields([[0, 3, 4], [0, 1, 2]],
... [1, 0])
>>> t = tfields.Mesh3D([[0]*3, [-1]*3, [-2]*3, [-3]*3, [-4]*3],
... [1, 0, 3, 2, 4],
... maps=[tmap])
Use template as instruction to make a fast cut
>>> res = m._cut_template(t)
>>> assert np.array_equal(res.fields,
... [[0.1, 0.0, 0.3, 0.2, 0.4],
... [-0.1, 0.0, -0.3, -0.2, -0.4]])
>>> assert np.array_equal(res.maps[3].fields[0],
... [[-42, -21], [42, 21]])
"""
inst = super()._cut_template(template) # this will set maps=Maps({})
# Redirect maps and their fields
if template.fields:
# bulk was cut so we need to correct the map references.
index_lut = np.full(len(self), np.nan) # float type
index_lut[template.fields[0]] = np.arange(len(template.fields[0]))
for map_dim, map_ in self.maps.items():
map_ = map_._cut_template( # pylint: disable=protected-access
template.maps[map_dim]
)
if template.fields:
# correct
map_ = Maps.to_map( # pylint: disable=invalid-name
index_lut[map_], *map_.fields
)
inst.maps[map_dim] = map_
return inst
def equal(self, other, **kwargs):
"""
Test, whether the instance has the same content as other.
Args:
other (iterable)
optional:
see TensorFields.equal
Examples:
>>> import tfields
>>> maps = [tfields.TensorFields([[1]], [42])]
>>> tm = tfields.TensorMaps(maps[0], maps=maps)
# >>> assert tm.equal(tm)
>>> cp = tm.copy()
# >>> assert tm.equal(cp)
>>> cp.maps[1].fields[0] = -42
>>> assert tm.maps[1].fields[0] == 42
>>> assert not tm.equal(cp)
"""
if not issubclass(type(other), Tensors):
return super(TensorMaps, self).equal(other, **kwargs)
with other.tmp_transform(self.coord_sys):
mask = super(TensorMaps, self).equal(other, **kwargs)
if issubclass(type(other), TensorMaps):
mask &= self.maps.equal(other.maps, **kwargs)
return mask
def stale(self):
"""
Returns:
Mask for all vertices that are stale i.e. are not refered by maps
Examples:
>>> import numpy as np
>>> import tfields
>>> vectors = tfields.Tensors(
... [[0, 0, 0], [0, 0, 1], [0, -1, 0], [4, 4, 4]])
>>> tm = tfields.TensorMaps(
... vectors,
... maps=[[[0, 1, 2], [0, 1, 2]], [[1, 1], [2, 2]]])
>>> assert np.array_equal(tm.stale(), [False, False, False, True])
"""
stale_mask = np.full(self.shape[0], False, dtype=bool)
used = set(ind for mp in self.maps.values() for ind in mp.flatten())
for i in range(self.shape[0]):
if i not in used:
stale_mask[i] = True
return stale_mask
def cleaned(self, stale=True, duplicates=True):
"""
Args:
stale (bool): remove stale vertices
duplicates (bool): replace duplicate vertices by originals
Examples:
>>> import numpy as np
>>> import tfields
>>> mp1 = tfields.TensorFields([[0, 1, 2], [3, 4, 5]],
... *zip([1,2,3,4,5], [6,7,8,9,0]))
>>> mp2 = tfields.TensorFields([[0], [3]])
>>> tm = tfields.TensorMaps([[0,0,0], [1,1,1], [2,2,2], [0,0,0],
... [3,3,3], [4,4,4], [5,6,7]],
... maps=[mp1, mp2])
>>> c = tm.cleaned()
>>> assert c.equal([[0., 0., 0.],
... [1., 1., 1.],
... [2., 2., 2.],
... [3., 3., 3.],
... [4., 4., 4.]])
>>> assert np.array_equal(c.maps[3], [[0, 1, 2], [0, 3, 4]])
>>> assert np.array_equal(c.maps[1], [[0], [0]])
Returns:
copy of self without stale vertices and duplicat points (depending
on arguments)
"""
if not stale and not duplicates:
inst = self.copy()
if stale:
# remove stale vertices i.e. those that are not referred by any
# map
remove_mask = self.stale()
inst = self.removed(remove_mask)
if duplicates: # pylint: disable=too-many-nested-blocks
# remove duplicates in order to not have any artificial separations
if not stale:
# we have not yet made a copy but want to work on inst
inst = self.copy()
remove_mask = np.full(inst.shape[0], False, dtype=bool)
duplicates = tfields.lib.util.duplicates(inst, axis=0)
tensor_indices = np.arange(inst.shape[0])
duplicates_mask = duplicates != tensor_indices
if duplicates_mask.any():
# redirect maps. Note: work on inst.maps instead of
# self.maps in case stale vertices where removed
keys = tensor_indices[duplicates_mask]
values = duplicates[duplicates_mask]
for map_dim in inst.maps:
tfields.lib.sets.remap(
inst.maps[map_dim], keys, values, inplace=True
)
# mark duplicates for removal
remove_mask[keys] = True
if remove_mask.any():
# prevent another copy
inst = inst.removed(remove_mask)
return inst
def removed(self, remove_condition):
"""
Return copy of self without vertices where remove_condition is True
Copy because self is immutable
Examples:
>>> import tfields
>>> m = tfields.TensorMaps(
... [[0,0,0], [1,1,1], [2,2,2], [0,0,0],
... [3,3,3], [4,4,4], [5,5,5]],
... maps=[tfields.TensorFields([[0, 1, 2], [0, 1, 3],
... [3, 4, 5], [3, 4, 1],
... [3, 4, 6]],
... [1, 3, 5, 7, 9],
... [2, 4, 6, 8, 0])])
>>> c = m.keep([False, False, False, True, True, True, True])
>>> c.equal([[0, 0, 0],
... [3, 3, 3],
... [4, 4, 4],
... [5, 5, 5]])
True
>>> assert c.maps[3].equal([[0, 1, 2], [0, 1, 3]])
>>> assert c.maps[3].fields[0].equal([5, 9])
>>> assert c.maps[3].fields[1].equal([6, 0])
"""
remove_condition = np.array(remove_condition)
return self[~remove_condition]
def keep(self, keep_condition):
"""
Return copy of self with vertices where keep_condition is True
Copy because self is immutable
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.TensorMaps(
... [[0,0,0], [1,1,1], [2,2,2], [0,0,0],
... [3,3,3], [4,4,4], [5,5,5]],
... maps=[tfields.TensorFields([[0, 1, 2], [0, 1, 3],
... [3, 4, 5], [3, 4, 1],
... [3, 4, 6]],
... [1, 3, 5, 7, 9],
... [2, 4, 6, 8, 0])])
>>> c = m.removed([True, True, True, False, False, False, False])
>>> c.equal([[0, 0, 0],
... [3, 3, 3],
... [4, 4, 4],
... [5, 5, 5]])
True
>>> assert c.maps[3].equal(np.array([[0, 1, 2], [0, 1, 3]]))
>>> assert c.maps[3].fields[0].equal([5, 9])
>>> assert c.maps[3].fields[1].equal([6, 0])
"""
keep_condition = np.array(keep_condition)
return self[keep_condition]
def parts(self, *map_descriptions):
"""
Args:
*map_descriptions (Tuple(int, List(List(int)))): tuples of
map_dim (int): reference to map position
used like: self.maps[map_dim]
map_indices_list (List(List(int))): each int refers
to index in a map.
Returns:
List(cls): One TensorMaps or TensorMaps subclass per
map_description
"""
parts = []
for map_description in map_descriptions:
map_dim, map_indices_list = map_description
for map_indices in map_indices_list:
obj = self.copy()
map_indices = set(map_indices) # for speed up
map_delete_mask = np.array(
[i not in map_indices for i in range(len(self.maps[map_dim]))]
)
obj.maps[map_dim] = obj.maps[map_dim][~map_delete_mask]
obj = obj.cleaned(duplicates=False)
parts.append(obj)
return parts
def disjoint_map(self, map_dim):
"""
Find the disjoint sets of map = self.maps[map_dim]
As an example, this method is interesting for splitting a mesh
consisting of seperate parts
Args:
map_dim (int): reference to map position
used like: self.maps[map_dim]
Returns:
Tuple(int, List(List(int))): map description(tuple): see self.parts
Examples:
>>> import tfields
>>> a = tfields.TensorMaps(
... [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]],
... maps=[[[0, 1, 2], [0, 2, 3]]])
>>> b = a.copy()
>>> b[:, 0] += 2
>>> m = tfields.TensorMaps.merged(a, b)
>>> mp_description = m.disjoint_map(3)
>>> parts = m.parts(mp_description)
>>> aa, ba = parts
>>> assert aa.maps[3].equal(ba.maps[3])
>>> assert aa.equal(a)
>>> assert ba.equal(b)
"""
maps_list = tfields.lib.sets.disjoint_group_indices(self.maps[map_dim])
return (map_dim, maps_list)
def paths(
self, map_dim
): # noqa: E501 pylint: disable=too-many-locals,too-many-branches,too-many-statements
"""
Find the minimal amount of graphs building the original graph with
maximum of two links per node i.e.
"o-----o o-----o"
" \\ / \\ /"
"" \\ / \\ /""
"o--o--o o--o 8--o"
| |
| = | + +
o o o
/ \\ / \\
/ \\ / \\
o o o o
where 8 is a duplicated node (one has two links and one has only one.)
Examples:
>>> import tfields
Ascii figure above:
>>> a = tfields.TensorMaps([[1, 0], [3, 0], [2, 2], [0, 4], [2, 4],
... [4, 4], [1, 6], [3, 6], [2, 2]],
... maps=[[[0, 2], [2, 4], [3, 4], [5, 4],
... [1, 8], [6, 4], [6, 7], [7, 4]]])
>>> paths = a.paths(2)
>>> assert paths[0].equal([[ 1., 0.],
... [ 2., 2.],
... [ 2., 4.],
... [ 0., 4.]])
>>> assert paths[0].maps[4].equal([[ 0., 1., 2., 3.]])
>>> assert paths[1].equal([[ 4., 4.],
... [ 2., 4.],
... [ 1., 6.],
... [ 3., 6.],
... [ 2., 4.]])
>>> assert paths[2].equal([[ 3., 0.],
... [ 2., 2.]])
Note:
The Longest path problem is a NP-hard problem.
"""
obj = self.cleaned()
flat_map = np.array(obj.maps[map_dim].flat)
values, counts = np.unique(flat_map, return_counts=True)
counts = dict(zip(values, counts))
# last is a helper
last = np.full(max(flat_map) + 1, -3, dtype=int)
duplicat_indices = []
d_index = len(obj)
for i, val in enumerate(flat_map.copy()):
if counts[val] > 2:
# The first two occurences are uncritical
if last[val] < -1:
last[val] += 1
continue
# Now we talk about nodes with more than two edges
if last[val] == -1:
# append a point and re-link
duplicat_indices.append(val)
flat_map[i] = d_index
last[val] = d_index
d_index += 1
else:
# last occurence of val was a duplicate, so we use the same
# value again.
flat_map[i] = last[val]
last[val] = -1
if duplicat_indices:
duplicates = obj[duplicat_indices]
obj = type(obj).merged(obj, duplicates)
obj.maps = [flat_map.reshape(-1, *obj.maps[map_dim].shape[1:])]
paths = obj.parts(obj.disjoint_map(map_dim))
# remove duplicate map entries and sort
sorted_paths = []
for path in paths:
# find start index
values, counts = np.unique(path.maps[map_dim].flat, return_counts=True)
first_node = None
for value, count in zip(values, counts):
if count == 1:
first_node = value
break
edges = [list(edge) for edge in path.maps[map_dim]]
if first_node is None:
first_node = 0 # edges[0][0]
path = path[list(range(len(path))) + [0]]
found_first_node = False
for edge in edges:
if first_node in edge:
if found_first_node:
edge[edge.index(first_node)] = len(path) - 1
break
found_first_node = True
# follow the edges until you hit the end
chain = [first_node]
visited = set()
n_edges = len(edges)
node = first_node
while len(visited) < n_edges:
for i, edge in enumerate(edges):
if i in visited:
continue
if node not in edge:
continue
# found edge
visited.add(i)
if edge.index(node) != 0:
edge = list(reversed(edge))
chain.extend(edge[1:])
node = edge[-1]
path = path[chain]
path_map = Maps.to_map([sorted(chain)])
path.maps[dim(path_map)] = path_map
sorted_paths.append(path)
paths = sorted_paths
return paths
def plot(self, *args, **kwargs): # pragma: no cover
"""
Generic plotting method of TensorMaps.
Args:
*args:
Depending on Positional arguments passed to the underlying
:func:`rna.plotting.plot_tensor_map` function for arbitrary .
dim (int): dimension of the plot representation (axes).
map (int): index of the map to plot (default is 3).
edgecolor (color): color of the edges (dim = 3)
"""
scalars_demanded = (
"color" not in kwargs
and "facecolors" not in kwargs
and any(v in kwargs for v in ["vmin", "vmax", "cmap"])
)
map_ = self.maps[kwargs.pop("map", 3)]
map_index = kwargs.pop("map_index", None if not scalars_demanded else 0)
if map_index is not None:
if not len(map_) == 0:
kwargs["color"] = map_.fields[map_index]
if map_.dim == 3:
# TODO: Mesh plotting only for Mesh3D().
# Overload this function for Mesh3D() specifically.
return rna.plotting.plot_mesh(self, *args, map_, **kwargs)
return rna.plotting.plot_tensor_map(self, *args, map_, **kwargs)
| (tensors, *fields, **kwargs) |
21,346 | tfields.core | __new__ | null | def __new__(cls, tensors, *fields, **kwargs):
if issubclass(type(tensors), TensorMaps):
default_maps = tensors.maps
else:
default_maps = {}
maps = Maps(kwargs.pop("maps", default_maps))
obj = super(TensorMaps, cls).__new__(cls, tensors, *fields, **kwargs)
obj.maps = maps
return obj
| (cls, tensors, *fields, **kwargs) |
21,354 | tfields.core | _cut_template |
Args:
template (tfields.TensorMaps)
Examples:
>>> import tfields
>>> import numpy as np
Build mesh
>>> mmap = tfields.TensorFields([[0, 1, 2], [0, 3, 4]],
... [[42, 21], [-42, -21]])
>>> m = tfields.Mesh3D([[0]*3, [1]*3, [2]*3, [3]*3, [4]*3],
... [0.0, 0.1, 0.2, 0.3, 0.4],
... [0.0, -0.1, -0.2, -0.3, -0.4],
... maps=[mmap])
Build template
>>> tmap = tfields.TensorFields([[0, 3, 4], [0, 1, 2]],
... [1, 0])
>>> t = tfields.Mesh3D([[0]*3, [-1]*3, [-2]*3, [-3]*3, [-4]*3],
... [1, 0, 3, 2, 4],
... maps=[tmap])
Use template as instruction to make a fast cut
>>> res = m._cut_template(t)
>>> assert np.array_equal(res.fields,
... [[0.1, 0.0, 0.3, 0.2, 0.4],
... [-0.1, 0.0, -0.3, -0.2, -0.4]])
>>> assert np.array_equal(res.maps[3].fields[0],
... [[-42, -21], [42, 21]])
| def _cut_template(self, template):
"""
Args:
template (tfields.TensorMaps)
Examples:
>>> import tfields
>>> import numpy as np
Build mesh
>>> mmap = tfields.TensorFields([[0, 1, 2], [0, 3, 4]],
... [[42, 21], [-42, -21]])
>>> m = tfields.Mesh3D([[0]*3, [1]*3, [2]*3, [3]*3, [4]*3],
... [0.0, 0.1, 0.2, 0.3, 0.4],
... [0.0, -0.1, -0.2, -0.3, -0.4],
... maps=[mmap])
Build template
>>> tmap = tfields.TensorFields([[0, 3, 4], [0, 1, 2]],
... [1, 0])
>>> t = tfields.Mesh3D([[0]*3, [-1]*3, [-2]*3, [-3]*3, [-4]*3],
... [1, 0, 3, 2, 4],
... maps=[tmap])
Use template as instruction to make a fast cut
>>> res = m._cut_template(t)
>>> assert np.array_equal(res.fields,
... [[0.1, 0.0, 0.3, 0.2, 0.4],
... [-0.1, 0.0, -0.3, -0.2, -0.4]])
>>> assert np.array_equal(res.maps[3].fields[0],
... [[-42, -21], [42, 21]])
"""
inst = super()._cut_template(template) # this will set maps=Maps({})
# Redirect maps and their fields
if template.fields:
# bulk was cut so we need to correct the map references.
index_lut = np.full(len(self), np.nan) # float type
index_lut[template.fields[0]] = np.arange(len(template.fields[0]))
for map_dim, map_ in self.maps.items():
map_ = map_._cut_template( # pylint: disable=protected-access
template.maps[map_dim]
)
if template.fields:
# correct
map_ = Maps.to_map( # pylint: disable=invalid-name
index_lut[map_], *map_.fields
)
inst.maps[map_dim] = map_
return inst
| (self, template) |
21,393 | tfields.core | Tensors |
Set of tensors with the same basis.
Args:
tensors: np.ndarray or AbstractNdarray subclass
**kwargs:
name: optional - custom name, can be anything
Examples:
>>> import numpy as np
>>> import tfields
Initialize a scalar range
>>> scalars = tfields.Tensors([0, 1, 2])
>>> scalars.rank == 0
True
Initialize vectors
>>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> vectors.rank == 1
True
>>> vectors.dim == 3
True
>>> assert vectors.coord_sys == 'cartesian'
Initialize the Levi-Zivita Tensor
>>> matrices = tfields.Tensors([[[0, 0, 0], [0, 0, 1], [0, -1, 0]],
... [[0, 0, -1], [0, 0, 0], [1, 0, 0]],
... [[0, 1, 0], [-1, 0, 0], [0, 0, 0]]])
>>> matrices.shape == (3, 3, 3)
True
>>> matrices.rank == 2
True
>>> matrices.dim == 3
True
Initializing in different start coordinate system
>>> cyl = tfields.Tensors([[5, np.arctan(4. / 3.), 42]],
... coord_sys='cylinder')
>>> assert cyl.coord_sys == 'cylinder'
>>> cyl.transform('cartesian')
>>> assert cyl.coord_sys == 'cartesian'
>>> cart = cyl
>>> assert round(cart[0, 0], 10) == 3.
>>> assert round(cart[0, 1], 10) == 4.
>>> assert cart[0, 2] == 42
Initialize with copy constructor keeps the coordinate system
>>> with vectors.tmp_transform('cylinder'):
... vect_cyl = tfields.Tensors(vectors)
... assert vect_cyl.coord_sys == vectors.coord_sys
>>> assert vect_cyl.coord_sys == 'cylinder'
You can demand a special dimension.
>>> _ = tfields.Tensors([[1, 2, 3]], dim=3)
>>> _ = tfields.Tensors([[1, 2, 3]], dim=2) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Incorrect dimension: 3 given, 2 demanded.
The dimension argument (dim) becomes necessary if you want to initialize
an empty array
>>> _ = tfields.Tensors([]) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Empty tensors need dimension parameter 'dim'.
>>> tfields.Tensors([], dim=7)
Tensors([], shape=(0, 7), dtype=float64)
| class Tensors(AbstractNdarray): # pylint: disable=too-many-public-methods
"""
Set of tensors with the same basis.
Args:
tensors: np.ndarray or AbstractNdarray subclass
**kwargs:
name: optional - custom name, can be anything
Examples:
>>> import numpy as np
>>> import tfields
Initialize a scalar range
>>> scalars = tfields.Tensors([0, 1, 2])
>>> scalars.rank == 0
True
Initialize vectors
>>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> vectors.rank == 1
True
>>> vectors.dim == 3
True
>>> assert vectors.coord_sys == 'cartesian'
Initialize the Levi-Zivita Tensor
>>> matrices = tfields.Tensors([[[0, 0, 0], [0, 0, 1], [0, -1, 0]],
... [[0, 0, -1], [0, 0, 0], [1, 0, 0]],
... [[0, 1, 0], [-1, 0, 0], [0, 0, 0]]])
>>> matrices.shape == (3, 3, 3)
True
>>> matrices.rank == 2
True
>>> matrices.dim == 3
True
Initializing in different start coordinate system
>>> cyl = tfields.Tensors([[5, np.arctan(4. / 3.), 42]],
... coord_sys='cylinder')
>>> assert cyl.coord_sys == 'cylinder'
>>> cyl.transform('cartesian')
>>> assert cyl.coord_sys == 'cartesian'
>>> cart = cyl
>>> assert round(cart[0, 0], 10) == 3.
>>> assert round(cart[0, 1], 10) == 4.
>>> assert cart[0, 2] == 42
Initialize with copy constructor keeps the coordinate system
>>> with vectors.tmp_transform('cylinder'):
... vect_cyl = tfields.Tensors(vectors)
... assert vect_cyl.coord_sys == vectors.coord_sys
>>> assert vect_cyl.coord_sys == 'cylinder'
You can demand a special dimension.
>>> _ = tfields.Tensors([[1, 2, 3]], dim=3)
>>> _ = tfields.Tensors([[1, 2, 3]], dim=2) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Incorrect dimension: 3 given, 2 demanded.
The dimension argument (dim) becomes necessary if you want to initialize
an empty array
>>> _ = tfields.Tensors([]) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Empty tensors need dimension parameter 'dim'.
>>> tfields.Tensors([], dim=7)
Tensors([], shape=(0, 7), dtype=float64)
"""
__slots__ = ["coord_sys", "name"]
__slot_defaults__ = ["cartesian"]
__slot_setters__ = [tfields.bases.get_coord_system_name]
def __new__(cls, tensors, **kwargs): # pylint: disable=too-many-branches
dtype = kwargs.pop("dtype", None)
order = kwargs.pop("order", None)
dim_ = kwargs.pop("dim", None)
# copy constructor extracts the kwargs from tensors
if issubclass(type(tensors), Tensors):
if dim_ is not None:
dim_ = tensors.dim
coord_sys = kwargs.pop("coord_sys", tensors.coord_sys)
tensors = tensors.copy()
tensors.transform(coord_sys)
kwargs["coord_sys"] = coord_sys
kwargs["name"] = kwargs.pop("name", tensors.name)
if dtype is None:
dtype = tensors.dtype
else:
if dtype is None:
if hasattr(tensors, "dtype"):
dtype = tensors.dtype
else:
dtype = np.float64
# demand iterable structure
try:
len(tensors)
except TypeError as err:
raise TypeError(
"Iterable structure necessary." " Got {tensors}".format(**locals())
) from err
# process empty inputs
if len(tensors) == 0:
if issubclass(type(tensors), tfields.Tensors):
tensors = np.empty(tensors.shape, dtype=tensors.dtype)
elif dim_ is not None:
tensors = np.empty((0, dim_))
if issubclass(type(tensors), np.ndarray):
# np.empty
pass
elif hasattr(tensors, "shape"):
dim_ = dim_(tensors)
else:
raise ValueError("Empty tensors need dimension parameter 'dim'.")
tensors = np.asarray(tensors, dtype=dtype, order=order)
obj = tensors.view(cls)
if dim_ is not None:
if dim_ != obj.dim:
raise ValueError(
"Incorrect dimension: {obj.dim} given,"
" {dim_} demanded.".format(**locals())
)
# update kwargs with defaults from slots
cls._update_slot_kwargs(kwargs)
# set kwargs to slots attributes
# pylint:disable=consider-using-dict-items
for attr in kwargs:
if attr not in cls._iter_slots():
raise AttributeError(
"Keyword argument {attr} not accepted "
"for class {cls}".format(**locals())
)
setattr(obj, attr, kwargs[attr])
return obj
def __iter__(self):
"""
Forwarding iterations to the bulk array. Otherwise __getitem__ would
kick in and slow down imensely.
Examples:
>>> import tfields
>>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> scalar_field = tfields.TensorFields(
... vectors, [42, 21, 10.5], [1, 2, 3])
>>> [(point.rank, point.dim) for point in scalar_field]
[(0, 1), (0, 1), (0, 1)]
"""
for index in range(len(self)):
yield super(Tensors, self).__getitem__(index).view(Tensors)
@classmethod
def _load_txt(cls, path, set_header: bool = False, **load_kwargs):
"""
Factory method
Given a path to a txt file, construct the object
Args:
path: see :meth:`Tensors.load`
set_header: if True, set the header to the `name` attribute
(the type of the name attribute will be a list of strings
(header separated by delimiter)
)
**loadkwargs: see :meth:`np.loadtxt`
"""
load_txt_keys = [
k
for k, v in inspect.signature(np.loadtxt).parameters.items()
if v.default is not inspect._empty # pylint:disable=protected-access
]
load_txt_kwargs = {}
for key in load_txt_keys:
if key in load_kwargs:
load_txt_kwargs[key] = load_kwargs.pop(key)
# use the same defaults as np.savetxt
load_txt_kwargs.setdefault("comments", "# ") # default is "#"
comments = load_txt_kwargs.get("comments")
load_txt_kwargs.setdefault("delimiter", " ")
skiprows = 0
header = []
with open(rna.path.resolve(path)) as file_:
while True:
line = file_.readline()
if line.startswith(comments):
header.append(line.lstrip(comments).rstrip("\n"))
else:
file_.seek(0)
break
skiprows += 1
load_txt_kwargs["skiprows"] = max(skiprows, load_txt_kwargs.pop("skiprows", 0))
arr = np.loadtxt(path, **load_txt_kwargs)
obj = cls(arr, **load_kwargs)
i = 0
for key, line in zip(cls._iter_slots(), header):
slot, rest = line.split(": ")
tpe, val_str = rest.split(" = ")
if tpe == "NoneType":
val = None
else:
tpe = __builtins__[tpe]
val = tpe(val_str)
setattr(obj, slot, val)
i += 1
header = header[i:]
if set_header:
obj.name = (
obj.name,
header,
) # pylint:disable=attribute-defined-outside-init
return obj
def _save_txt(self, path, **kwargs):
"""
Save as text file.
Args:
**kwargs passed to np.savetxt.
"""
header = kwargs.get("header", [])
if isinstance(header, dict):
header = [
f"{key}: {type(value).__name__} = {value}"
for key, value in header.items()
]
if isinstance(header, list):
# statictyping like attribute saving
header = [
f"{key}: {type(getattr(self, key)).__name__} = {getattr(self, key)}"
for key in self._iter_slots()
] + header
kwargs["header"] = "\n".join(header)
np.savetxt(path, self, **kwargs)
@classmethod
def merged(cls, *objects, **kwargs):
"""
Factory method
Merges all input arguments to one object
Args:
return_templates (bool): return the templates which can be used
together with cut to retrieve the original objects
dim (int):
**kwargs: passed to cls
Examples:
>>> import numpy as np
>>> import tfields
>>> import tfields.bases
The new object with turn out in the most frequent coordinate
system if not specified explicitly
>>> vec_a = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
>>> vec_b = tfields.Tensors([[5, 4, 1]],
... coord_sys=tfields.bases.cylinder)
>>> vec_c = tfields.Tensors([[4, 2, 3]],
... coord_sys=tfields.bases.cylinder)
>>> merge = tfields.Tensors.merged(
... vec_a, vec_b, vec_c, [[2, 0, 1]])
>>> assert merge.coord_sys == 'cylinder'
>>> assert merge.equal([[0, 0, 0],
... [0, 0, 1],
... [1, -np.pi / 2, 0],
... [5, 4, 1],
... [4, 2, 3],
... [2, 0, 1]])
Merge also shifts the maps to still refer to the same tensors
>>> tm_a = tfields.TensorMaps(merge, maps=[[[0, 1, 2]]])
>>> tm_b = tm_a.copy()
>>> assert tm_a.coord_sys == 'cylinder'
>>> tm_merge = tfields.TensorMaps.merged(tm_a, tm_b)
>>> assert tm_merge.coord_sys == 'cylinder'
>>> assert tm_merge.maps[3].equal([[0, 1, 2],
... list(range(len(merge),
... len(merge) + 3,
... 1))])
>>> obj_list = [tfields.Tensors([[1, 2, 3]],
... coord_sys=tfields.bases.CYLINDER),
... tfields.Tensors([[3] * 3]),
... tfields.Tensors([[5, 1, 3]])]
>>> merge2 = tfields.Tensors.merged(
... *obj_list, coord_sys=tfields.bases.CARTESIAN)
>>> assert merge2.equal([[-0.41614684, 0.90929743, 3.],
... [3, 3, 3], [5, 1, 3]], atol=1e-8)
The return_templates argument allows to retrieve a template which
can be used with the cut method.
>>> merge, templates = tfields.Tensors.merged(
... vec_a, vec_b, vec_c, return_templates=True)
>>> assert merge.cut(templates[0]).equal(vec_a)
>>> assert merge.cut(templates[1]).equal(vec_b)
>>> assert merge.cut(templates[2]).equal(vec_c)
"""
# get most frequent coord_sys or predefined coord_sys
coord_sys = kwargs.get("coord_sys", None)
return_templates = kwargs.pop("return_templates", False)
if coord_sys is None:
bases = []
for tensors in objects:
try:
bases.append(tensors.coord_sys)
except AttributeError:
pass
if bases:
# get most frequent coord_sys
coord_sys = sorted(bases, key=Counter(bases).get, reverse=True)[0]
kwargs["coord_sys"] = coord_sys
else:
default = cls.__slot_defaults__[cls.__slots__.index("coord_sys")]
kwargs["coord_sys"] = default
# transform all raw inputs to cls type with correct coord_sys. Also
# automatically make a copy of those instances that are of the correct
# type already.
objects = [cls.__new__(cls, t, **kwargs) for t in objects]
# check rank and dimension equality
if not len(set(t.rank for t in objects)) == 1:
raise TypeError("Tensors must have the same rank for merging.")
if not len(set(t.dim for t in objects)) == 1:
raise TypeError("Tensors must have the same dimension for merging.")
# merge all objects
remaining_objects = objects[1:] or []
tensors = objects[0]
for i, obj in enumerate(remaining_objects):
tensors = np.append(tensors, obj, axis=0)
if len(tensors) == 0 and not kwargs.get("dim", None):
# if you can not determine the tensor dimension, search for the
# first object with some entries
kwargs["dim"] = dim(objects[0])
inst = cls.__new__(cls, tensors, **kwargs)
if not return_templates: # pylint: disable=no-else-return
return inst
else:
tensor_lengths = [len(o) for o in objects]
cum_tensor_lengths = [sum(tensor_lengths[:i]) for i in range(len(objects))]
templates = [
tfields.TensorFields(
np.empty((len(obj), 0)),
np.arange(tensor_lengths[i]) + cum_tensor_lengths[i],
)
for i, obj in enumerate(objects)
]
return inst, templates
@classmethod
def grid(cls, *base_vectors, **kwargs):
"""
Args:
*base_vectors (Iterable): base coordinates. The amount of base
vectors defines the dimension
**kwargs:
iter_order (list): order in which the iteration will be done.
Frequency rises with position in list. default is [0, 1, 2]
iteration will be done like::
for v0 in base_vectors[iter_order[0]]:
for v1 in base_vectors[iter_order[1]]:
for v2 in base_vectors[iter_order[2]]:
coords0.append(locals()['v%i' % iter_order[0]])
coords1.append(locals()['v%i' % iter_order[1]])
coords2.append(locals()['v%i' % iter_order[2]])
Examples:
Initilaize using the mgrid notation
>>> import numpy as np
>>> import tfields
>>> mgrid = tfields.Tensors.grid((0, 1, 2j), (3, 4, 2j), (6, 7, 2j))
>>> mgrid.equal([[0, 3, 6],
... [0, 3, 7],
... [0, 4, 6],
... [0, 4, 7],
... [1, 3, 6],
... [1, 3, 7],
... [1, 4, 6],
... [1, 4, 7]])
True
Lists or arrays are accepted also.
Furthermore, the iteration order can be changed
>>> lins = tfields.Tensors.grid(
... np.linspace(3, 4, 2), np.linspace(0, 1, 2),
... np.linspace(6, 7, 2), iter_order=[1, 0, 2])
>>> lins.equal([[3, 0, 6],
... [3, 0, 7],
... [4, 0, 6],
... [4, 0, 7],
... [3, 1, 6],
... [3, 1, 7],
... [4, 1, 6],
... [4, 1, 7]])
True
>>> lins2 = tfields.Tensors.grid(np.linspace(0, 1, 2),
... np.linspace(3, 4, 2),
... np.linspace(6, 7, 2),
... iter_order=[2, 0, 1])
>>> lins2.equal([[0, 3, 6],
... [0, 4, 6],
... [1, 3, 6],
... [1, 4, 6],
... [0, 3, 7],
... [0, 4, 7],
... [1, 3, 7],
... [1, 4, 7]])
True
When given the coord_sys argument, the grid is performed in the
given coorinate system:
>>> lins3 = tfields.Tensors.grid(np.linspace(4, 9, 2),
... np.linspace(np.pi/2, np.pi/2, 1),
... np.linspace(4, 4, 1),
... iter_order=[2, 0, 1],
... coord_sys=tfields.bases.CYLINDER)
>>> assert lins3.coord_sys == 'cylinder'
>>> lins3.transform('cartesian')
>>> assert np.array_equal(lins3[:, 1], [4, 9])
"""
cls_kwargs = {
attr: kwargs.pop(attr) for attr in list(kwargs) if attr in cls.__slots__
}
inst = cls.__new__(
cls, tfields.lib.grid.igrid(*base_vectors, **kwargs), **cls_kwargs
)
return inst
@property
def rank(self):
"""
Tensor rank
"""
return rank(self)
@property
def dim(self):
"""
Manifold dimension
"""
return dim(self)
def transform(self, coord_sys, **kwargs):
"""
Args:
coord_sys (str)
Examples:
>>> import numpy as np
>>> import tfields
CARTESIAN to SPHERICAL
>>> t = tfields.Tensors([[1, 2, 2], [1, 0, 0], [0, 0, -1],
... [0, 0, 1], [0, 0, 0]])
>>> t.transform('spherical')
r
>>> assert t[0, 0] == 3
phi
>>> assert t[1, 1] == 0.
>>> assert t[2, 1] == 0.
theta is 0 at (0, 0, 1) and pi / 2 at (0, 0, -1)
>>> assert round(t[1, 2], 10) == round(0, 10)
>>> assert t[2, 2] == -np.pi / 2
>>> assert t[3, 2] == np.pi / 2
theta is defined 0 for R == 0
>>> assert t[4, 0] == 0.
>>> assert t[4, 2] == 0.
CARTESIAN to CYLINDER
>>> tCart = tfields.Tensors([[3, 4, 42], [1, 0, 0], [0, 1, -1],
... [-1, 0, 1], [0, 0, 0]])
>>> t_cyl = tCart.copy()
>>> t_cyl.transform('cylinder')
>>> assert t_cyl.coord_sys == 'cylinder'
R
>>> assert t_cyl[0, 0] == 5
>>> assert t_cyl[1, 0] == 1
>>> assert t_cyl[2, 0] == 1
>>> assert t_cyl[4, 0] == 0
Phi
>>> assert round(t_cyl[0, 1], 10) == round(np.arctan(4. / 3), 10)
>>> assert t_cyl[1, 1] == 0
>>> assert round(t_cyl[2, 1], 10) == round(np.pi / 2, 10)
>>> assert t_cyl[1, 1] == 0
Z
>>> assert t_cyl[0, 2] == 42
>>> assert t_cyl[2, 2] == -1
>>> t_cyl.transform('cartesian')
>>> assert t_cyl.coord_sys == 'cartesian'
>>> assert round(t_cyl[0, 0], 10) == 3
"""
if self.rank == 0 or any(s == 0 for s in self.shape):
# scalar or empty
self.coord_sys = coord_sys # pylint: disable=attribute-defined-outside-init
return
if self.coord_sys == coord_sys:
# already correct
return
tfields.bases.transform(self, self.coord_sys, coord_sys, **kwargs)
# self[:] = tfields.bases.transform(self, self.coord_sys, coord_sys)
self.coord_sys = coord_sys # pylint: disable=attribute-defined-outside-init
@contextmanager
def tmp_transform(self, coord_sys):
"""
Temporarily change the coord_sys to another coord_sys and change it back at exit
This method is for cleaner code only.
No speed improvements go with this.
Args:
see transform
Examples:
>>> import tfields
>>> p = tfields.Tensors([[1,2,3]], coord_sys=tfields.bases.SPHERICAL)
>>> with p.tmp_transform(tfields.bases.CYLINDER):
... assert p.coord_sys == tfields.bases.CYLINDER
>>> assert p.coord_sys == tfields.bases.SPHERICAL
"""
base_before = self.coord_sys
if base_before == coord_sys:
yield
else:
self.transform(coord_sys)
yield
self.transform(base_before)
def mirror(self, coordinate, condition=None):
"""
Reflect/Mirror the entries meeting <condition> at <coordinate> = 0
Args:
coordinate (int): coordinate index
Examples:
>>> import tfields
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
>>> p.mirror(1)
>>> assert p.equal([[1, -2, 3], [4, -5, 6], [1, -2, -6]])
multiple coordinates can be mirrored at the same time
i.e. a point mirrorion would be
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
>>> p.mirror([0,2])
>>> assert p.equal([[-1, 2, -3], [-4, 5, -6], [-1, 2., 6.]])
You can give a condition as mask or as str.
The mirroring will only be applied to the points meeting the
condition.
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> p.mirror([0, 2], y > 3)
>>> p.equal([[-1, 2, -3], [4, 5, 6], [-1, 2, 6]])
True
"""
if condition is None:
condition = np.array([True for i in range(len(self))])
elif isinstance(condition, sympy.Basic):
condition = self.evalf(condition)
if isinstance(coordinate, (list, tuple)):
for coord in coordinate:
self.mirror(coord, condition=condition)
elif isinstance(coordinate, int):
self[:, coordinate][condition] *= -1
else:
raise TypeError()
def to_segment( # pylint: disable=too-many-arguments
self,
segment,
num_segments,
coordinate,
periodicity=2 * np.pi,
offset=0.0,
coord_sys=None,
):
"""
For circular (close into themself after
<periodicity>) coordinates at index <coordinate> assume
<num_segments> segments and transform all values to
segment number <segment>
Args:
segment (int): segment index (starting at 0)
num_segments (int): number of segments
coordinate (int): coordinate index
periodicity (float): after what lenght, the coordiante repeats
offset (float): offset in the mapping
coord_sys (str or sympy.CoordinateSystem): in which coord sys the
transformation should be done
Examples:
>>> import tfields
>>> import numpy as np
>>> pStart = tfields.Points3D([[6, 2 * np.pi, 1],
... [6, 2 * np.pi / 5 * 3, 1]],
... coord_sys='cylinder')
>>> p = tfields.Points3D(pStart)
>>> p.to_segment(0, 5, 1, offset=-2 * np.pi / 10)
>>> assert np.array_equal(p[:, 1], [0, 0])
>>> p2 = tfields.Points3D(pStart)
>>> p2.to_segment(1, 5, 1, offset=-2 * np.pi / 10)
>>> assert np.array_equal(np.round(p2[:, 1], 4), [1.2566] * 2)
"""
if segment > num_segments - 1:
raise ValueError("Segment {0} not existent.".format(segment))
if coord_sys is None:
coord_sys = self.coord_sys
with self.tmp_transform(coord_sys):
# map all values to first segment
self[:, coordinate] = (
(self[:, coordinate] - offset) % (periodicity / num_segments)
+ offset
+ segment * periodicity / num_segments
)
def equal(
self, other, rtol=None, atol=None, equal_nan=False, return_bool=True
): # noqa: E501 pylint: disable=too-many-arguments
"""
Evaluate, whether the instance has the same content as other.
Args:
optional:
rtol (float)
atol (float)
equal_nan (bool)
see numpy.isclose
"""
if issubclass(type(other), Tensors) and self.coord_sys != other.coord_sys:
other = other.copy()
other.transform(self.coord_sys)
self_array, other_array = np.asarray(self), np.asarray(other)
if rtol is None and atol is None:
mask = self_array == other_array
if equal_nan:
both_nan = np.isnan(self_array) & np.isnan(other_array)
mask[both_nan] = both_nan[both_nan]
else:
if rtol is None:
rtol = 0.0
if atol is None:
atol = 0.0
mask = np.isclose(
self_array, other_array, rtol=rtol, atol=atol, equal_nan=equal_nan
)
if return_bool:
return bool(np.all(mask))
return mask
def contains(self, other):
"""
Inspired by a speed argument @
stackoverflow.com/questions/14766194/testing-whether-a-numpy-array-contains-a-given-row
Examples:
>>> import tfields
>>> p = tfields.Tensors([[1,2,3], [4,5,6], [6,7,8]])
>>> p.contains([4,5,6])
True
"""
return any(self.equal(other, return_bool=False).all(1))
def indices(self, tensor, rtol=None, atol=None):
"""
Returns:
list of int: indices of tensor occuring
Examples:
Rank 1 Tensors
>>> import tfields
>>> p = tfields.Tensors([[1,2,3], [4,5,6], [6,7,8], [4,5,6],
... [4.1, 5, 6]])
>>> p.indices([4,5,6])
array([1, 3])
>>> p.indices([4,5,6.1], rtol=1e-5, atol=1e-1)
array([1, 3, 4])
Rank 0 Tensors
>>> p = tfields.Tensors([2, 3, 6, 3.01])
>>> p.indices(3)
array([1])
>>> p.indices(3, rtol=1e-5, atol=1e-1)
array([1, 3])
"""
self_array, other_array = np.asarray(self), np.asarray(tensor)
if rtol is None and atol is None:
equal_method = np.equal
else:
equal_method = lambda a, b: np.isclose(a, b, rtol=rtol, atol=atol) # NOQA
# inspired by
# https://stackoverflow.com/questions/19228295/find-ordered-vector-in-numpy-array
if self.rank == 0:
indices = np.where(equal_method((self_array - other_array), 0))[0]
elif self.rank == 1:
indices = np.where(
np.all(equal_method((self_array - other_array), 0), axis=1)
)[0]
else:
raise NotImplementedError()
return indices
def index(self, tensor, **kwargs):
"""
Args:
tensor
Returns:
int: index of tensor occuring
"""
indices = self.indices(tensor, **kwargs)
if not indices:
return None
if len(indices) == 1:
return indices[0]
raise ValueError("Multiple occurences of value {}".format(tensor))
def moment(self, moment, weights=None):
"""
Returns:
Moments of the distribution.
Args:
moment (int): n-th moment
Examples:
>>> import tfields
Skalars
>>> t = tfields.Tensors(range(1, 6))
>>> assert t.moment(1) == 0
>>> assert t.moment(1, weights=[-2, -1, 20, 1, 2]) == 0.5
>>> assert t.moment(2, weights=[0.25, 1, 17.5, 1, 0.25]) == 0.2
Vectors
>>> t = tfields.Tensors(list(zip(range(1, 6), range(1, 6))))
>>> assert tfields.Tensors([0.5, 0.5]).equal(
... t.moment(1, weights=[-2, -1, 20, 1, 2]))
>>> assert tfields.Tensors([1. , 0.5]).equal(
... t.moment(1, weights=list(zip([-2, -1, 10, 1, 2],
... [-2, -1, 20, 1, 2]))))
"""
array = tfields.lib.stats.moment(self, moment, weights=weights)
if self.rank == 0: # scalar
array = [array]
return Tensors(array, coord_sys=self.coord_sys)
def closest(self, other, **kwargs):
"""
Args:
other (Tensors): closest points to what? -> other
**kwargs: forwarded to scipy.spatial.cKDTree.query
Returns:
array shape(len(self)): Indices of other points that are closest to
own points
Examples:
>>> import tfields
>>> m = tfields.Tensors([[1,0,0], [0,1,0], [1,1,0], [0,0,1],
... [1,0,1]])
>>> p = tfields.Tensors([[1.1,1,0], [0,0.1,1], [1,0,1.1]])
>>> p.closest(m)
array([2, 3, 4])
"""
with other.tmp_transform(self.coord_sys):
# balanced_tree option gives huge speedup!
kd_tree = scipy.spatial.cKDTree( # noqa: E501 pylint: disable=no-member
other, 1000, balanced_tree=False
)
res = kd_tree.query(self, **kwargs)
array = res[1]
return array
def evalf(self, expression=None, coord_sys=None):
"""
Args:
expression (sympy logical expression)
coord_sys (str): coord_sys to evalfuate the expression in.
Returns:
np.ndarray: mask of dtype bool with lenght of number of points in
self. This array is True, where expression evalfuates True.
Examples:
>>> import tfields
>>> import numpy as np
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> np.array_equal(p.evalf(x > 0),
... [True, True, True, False, True, False])
True
>>> np.array_equal(p.evalf(x >= 0),
... [True, True, True, False, True, True])
True
And combination
>>> np.array_equal(p.evalf((x > 0) & (y < 3)),
... [True, False, True, False, True, False])
True
Or combination
>>> np.array_equal(p.evalf((x > 0) | (y > 3)),
... [True, True, True, False, True, False])
True
"""
coords = sympy.symbols("x y z")
with self.tmp_transform(coord_sys or self.coord_sys):
mask = tfields.evalf(np.array(self), expression, coords=coords)
return mask
def _cut_sympy(self, expression):
if len(self) == 0:
return self.copy()
mask = self.evalf(expression) # coord_sys is handled by tmp_transform
mask.astype(bool)
inst = self[mask].copy()
# template
indices = np.arange(len(self))[mask]
template = tfields.TensorFields(np.empty((len(indices), 0)), indices)
return inst, template
def _cut_template(self, template):
"""
In principle, what we do is returning
self[template.fields[0]]
If the templates tensors is given (has no dimension 0), 0))), we switch
to only extruding the field entries according to the indices provided
by template.fields[0]. This allows the template to define additional
points, extending the object it should cut. This becomes relevant for
Mesh3D when adding vertices at the edge of the cut is necessary.
"""
# Redirect fields
fields = []
if template.fields and issubclass(type(self), TensorFields):
template_field = np.array(template.fields[0])
if len(self) > 0:
# if new vertices have been created in the template, it is in principle unclear
# what fields we have to refer to. Thus in creating the template, we gave np.nan.
# To make it fast, we replace nan with 0 as a dummy and correct the field entries
# afterwards with np.nan.
nan_mask = np.isnan(template_field)
template_field[nan_mask] = 0 # dummy reference to index 0.
template_field = template_field.astype(int)
for field in self.fields:
projected_field = field[template_field]
projected_field[nan_mask] = np.nan # correction for nan
fields.append(projected_field)
if dim(template) == 0:
# for speed circumvent __getitem__ of the complexer subclasses
tensors = Tensors(self)[template.fields[0]]
else:
tensors = template
return type(self)(tensors, *fields)
def cut(self, expression, coord_sys=None, return_template=False, **kwargs):
"""
Extract a part of the object according to the logic given
by <expression>.
Args:
expression (sympy logical expression|tfields.TensorFields): logical
expression which will be evaluated. use symbols x, y and z.
If tfields.TensorFields or subclass is given, the expression
refers to a template.
coord_sys (str): coord_sys to evaluate the expression in. Only
active for template expression
Examples:
>>> import tfields
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> p.cut(x > 0).equal([[1, 2, 3],
... [4, 5, 6],
... [1, 2, -6],
... [1, 0, -1]])
True
combinations of cuts
>>> cut_expression = (x > 0) & (z < 0)
>>> combi_cut = p.cut(cut_expression)
>>> combi_cut.equal([[1, 2, -6], [1, 0, -1]])
True
Templates can be used to speed up the repeated cuts on the same
underlying tensor with the same expression but new fields.
First let us cut a but request the template on return:
>>> field1 = list(range(len(p)))
>>> tf = tfields.TensorFields(p, field1)
>>> tf_cut, template = tf.cut(cut_expression,
... return_template=True)
Now repeat the cut with a new field:
>>> field2 = p
>>> tf.fields.append(field2)
>>> tf_template_cut = tf.cut(template)
>>> tf_template_cut.equal(combi_cut)
True
>>> tf_template_cut.fields[0].equal([2, 4])
True
>>> tf_template_cut.fields[1].equal(combi_cut)
True
Returns:
copy of self with cut applied
[optional: template - requires <return_template> switch]
"""
with self.tmp_transform(coord_sys or self.coord_sys):
if issubclass(type(expression), TensorFields):
template = expression
obj = self._cut_template(template)
else:
obj, template = self._cut_sympy(expression, **kwargs)
if return_template:
return obj, template
return obj
def distances(self, other, **kwargs):
"""
Args:
other(Iterable)
**kwargs:
... is forwarded to scipy.spatial.distance.cdist
Examples:
>>> import tfields
>>> p = tfields.Tensors.grid((0, 2, 3j),
... (0, 2, 3j),
... (0, 0, 1j))
>>> p[4,2] = 1
>>> p.distances(p)[0,0]
0.0
>>> p.distances(p)[5,1]
1.4142135623730951
>>> p.distances([[0,1,2]])[-1][0] == 3
True
"""
if issubclass(type(other), Tensors) and self.coord_sys != other.coord_sys:
other = other.copy()
other.transform(self.coord_sys)
return scipy.spatial.distance.cdist(self, other, **kwargs)
def min_dists(self, other=None, **kwargs):
"""
Args:
other(array | None): if None: closest distance to self
**kwargs:
memory_saving (bool): for very large array comparisons
default False
... rest is forwarded to scipy.spatial.distance.cdist
Returns:
np.array: minimal distances of self to other
Examples:
>>> import tfields
>>> import numpy as np
>>> p = tfields.Tensors.grid((0, 2, 3),
... (0, 2, 3),
... (0, 0, 1))
>>> p[4,2] = 1
>>> dMin = p.min_dists()
>>> expected = [1] * 9
>>> expected[4] = np.sqrt(2)
>>> np.array_equal(dMin, expected)
True
>>> dMin2 = p.min_dists(memory_saving=True)
>>> bool((dMin2 == dMin).all())
True
"""
memory_saving = kwargs.pop("memory_saving", False)
if other is None:
other = self
else:
raise NotImplementedError(
"Should be easy but make shure not to remove diagonal"
)
try:
if memory_saving:
raise MemoryError()
dists = self.distances(other, **kwargs)
return dists[dists > 0].reshape(dists.shape[0], -1).min(axis=1)
except MemoryError:
min_dists = np.empty(self.shape[0])
for i, point in enumerate(np.array(other)):
dists = self.distances([point], **kwargs)
min_dists[i] = dists[dists > 0].reshape(-1).min()
return min_dists
def epsilon_neighbourhood(self, epsilon):
"""
Returns:
indices for those sets of points that lie within epsilon around the
other
Examples:
Create mesh grid with one extra point that will have 8 neighbours
within epsilon
>>> import tfields
>>> p = tfields.Tensors.grid((0, 1, 2j),
... (0, 1, 2j),
... (0, 1, 2j))
>>> p = tfields.Tensors.merged(p, [[0.5, 0.5, 0.5]])
>>> [len(en) for en in p.epsilon_neighbourhood(0.9)]
[2, 2, 2, 2, 2, 2, 2, 2, 9]
"""
indices = np.arange(self.shape[0])
dists = self.distances(self) # this takes long
dists_in_epsilon = dists <= epsilon
indices = [indices[die] for die in dists_in_epsilon] # this takes long
return indices
def _weights(self, weights, rigid=True):
"""
transformer method for weights inputs.
Args:
weights (np.ndarray | None):
If weights is None, use np.ones
Otherwise just pass the weights.
rigid (bool): demand equal weights and tensor length
Returns:
weight array
"""
# set weights to 1.0 if weights is None
if weights is None:
weights = np.ones(len(self))
if rigid:
if not len(weights) == len(self):
raise ValueError("Equal number of weights as tensors demanded.")
return weights
def cov_eig(self, weights=None):
"""
Calculate the covariance eigenvectors with lenghts of eigenvalues
Args:
weights (np.array | int | None): index to scalars to weight with
"""
# weights = self.getNormedWeightedAreas(weights=weights)
weights = self._weights(weights)
cov = np.cov(self.T, ddof=0, aweights=weights)
# calculate eigenvalues and eigenvectors of covariance
evalfs, evecs = np.linalg.eigh(cov)
idx = evalfs.argsort()[::-1]
evalfs = evalfs[idx]
evecs = evecs[:, idx]
res = np.concatenate((evecs, evalfs.reshape(1, 3)))
return res.T.reshape(
12,
)
def main_axes(self, weights=None):
"""
Returns:
Main Axes eigen-vectors
"""
# weights = self.getNormedWeightedAreas(weights=weights)
weights = self._weights(weights)
mean = np.array(self).mean(axis=0)
relative_coords = self - mean
cov = np.cov(relative_coords.T, ddof=0, aweights=weights)
# calculate eigenvalues and eigenvectors of covariance
evalfs, evecs = np.linalg.eigh(cov)
return (evecs * evalfs.T).T
@property
# pylint:disable=invalid-name
def t(self):
"""
Same as self.T but for tensor dimension only. Keeping the order of stacked tensors.
Examples:
>>> import tfields
>>> a = tfields.Tensors([[[1,2,3,4],[5,6,7,8]]])
>>> assert a.t.equal([a[0].T])
"""
return self.transpose(0, *range(self.ndim)[-1:0:-1])
def dot(self, b, out=None):
# pylint:disable=line-too-long
"""
Computes the n-d dot product between self and other defined as in
`mathematica <https://reference.wolfram.com/legacy/v5/Built-inFunctions/
AdvancedDocumentation/LinearAlgebra/2.7.html>`_
by summing over the last dimension.
When self and b are both one-dimensional vectors, this is just the "usual" dot product;
when self and b are 2D matrices, this is matrix multiplication.
Note:
* This is not the same as the numpy.dot function.
Examples:
>>> import tfields
>>> import numpy as np
Scalar product by transposed dot product
>>> a = tfields.Tensors([[4, 0, 4]])
>>> b = tfields.Tensors([[10, 0, 0.5]])
>>> c = a.t.dot(b)
>>> assert c.equal([42])
>>> assert c.equal(np.dot(a[0], b[0]))
>>> assert c.rank == 0
To get the angle between a and b you now just need
>>> angle = np.arccos(c)
Matrix vector multiplication
>>> a = tfields.Tensors([[[1, 20, 0], [2, 18, 1], [1, 5, 10]]])
>>> b = tfields.Tensors([[1, 2, 3]])
>>> c = a.dot(b)
>>> assert c.equal([[41,41,41]])
TODO: generalize dot product to inner
# Matrix matrix multiplication can not be done like this. It requires
# >>> a = tfields.Tensors([[[1, 8], [2, 4]]])
# >>> b = tfields.Tensors([[[1, 2], [1/2, 1/4]]])
# >>> c = a.dot(b)
# >>> c
# >>> assert c.equal([[[5, 4], [4, 5]]])
TODO: handle types, fields and maps (which fields etc to choose for the output?)
"""
if out is not None:
raise NotImplementedError("performance feature 'out' not yet implemented")
return Tensors(np.einsum("t...i,t...i->t...", self, b))
# pylint:disable=redefined-builtin
def norm(self, ord=None, axis=None, keepdims=False):
"""
Calculate the norm up to rank 2
Args:
See numpy.linal.norm except redefinition in axis
axis: by default omitting first axis
Examples:
>>> import tfields
>>> a = tfields.Tensors([[1, 0, 0]])
>>> assert a.norm().equal([1])
"""
if axis is None:
axis = tuple(range(self.ndim)[1:])
return Tensors(np.linalg.norm(self, ord=ord, axis=axis, keepdims=keepdims))
def normalized(self, *args, **kwargs):
"""
Return the self / norm(self)
Args:
forwarded to :meth:norm
Examples:
>>> import tfields
>>> a = tfields.Tensors([[1, 4, 3]])
>>> assert not a.norm().equal([1])
>>> a = a.normalized()
>>> assert a.norm().equal([1])
>>> a = tfields.Tensors([[1, 0, 0],
... [0, 2, 0],
... [0, 0, 3]])
>>> assert a.norm().equal([1, 2, 3])
>>> a = a.normalized()
>>> assert a.equal([
... [1, 0, 0],
... [0, 1, 0],
... [0, 0, 1],
... ])
>>> assert a.norm().equal([1, 1, 1])
"""
# return np.divide(self.T, self.norm(*args, **kwargs)).T
return np.divide(self, self.norm(*args, **kwargs)[:, None])
def plot(self, *args, **kwargs):
"""
Generic plotting method of Tensors.
Forwarding to rna.plotting.plot_tensor
"""
artist = rna.plotting.plot_tensor(
self, *args, **kwargs
) # pylint: disable=no-member
return artist
| (tensors, **kwargs) |
21,397 | tfields.core | __new__ | null | def __new__(cls, tensors, **kwargs): # pylint: disable=too-many-branches
dtype = kwargs.pop("dtype", None)
order = kwargs.pop("order", None)
dim_ = kwargs.pop("dim", None)
# copy constructor extracts the kwargs from tensors
if issubclass(type(tensors), Tensors):
if dim_ is not None:
dim_ = tensors.dim
coord_sys = kwargs.pop("coord_sys", tensors.coord_sys)
tensors = tensors.copy()
tensors.transform(coord_sys)
kwargs["coord_sys"] = coord_sys
kwargs["name"] = kwargs.pop("name", tensors.name)
if dtype is None:
dtype = tensors.dtype
else:
if dtype is None:
if hasattr(tensors, "dtype"):
dtype = tensors.dtype
else:
dtype = np.float64
# demand iterable structure
try:
len(tensors)
except TypeError as err:
raise TypeError(
"Iterable structure necessary." " Got {tensors}".format(**locals())
) from err
# process empty inputs
if len(tensors) == 0:
if issubclass(type(tensors), tfields.Tensors):
tensors = np.empty(tensors.shape, dtype=tensors.dtype)
elif dim_ is not None:
tensors = np.empty((0, dim_))
if issubclass(type(tensors), np.ndarray):
# np.empty
pass
elif hasattr(tensors, "shape"):
dim_ = dim_(tensors)
else:
raise ValueError("Empty tensors need dimension parameter 'dim'.")
tensors = np.asarray(tensors, dtype=dtype, order=order)
obj = tensors.view(cls)
if dim_ is not None:
if dim_ != obj.dim:
raise ValueError(
"Incorrect dimension: {obj.dim} given,"
" {dim_} demanded.".format(**locals())
)
# update kwargs with defaults from slots
cls._update_slot_kwargs(kwargs)
# set kwargs to slots attributes
# pylint:disable=consider-using-dict-items
for attr in kwargs:
if attr not in cls._iter_slots():
raise AttributeError(
"Keyword argument {attr} not accepted "
"for class {cls}".format(**locals())
)
setattr(obj, attr, kwargs[attr])
return obj
| (cls, tensors, **kwargs) |
21,435 | tfields.triangles_3d | Triangles3D |
Points3D child restricted to n * 3 Points.
Three Points always group together to one triangle.
Args:
tensors (Iterable | tfields.TensorFields)
*fields (Iterable | tfields.Tensors): Fields with the same length as tensors
**kwargs: passed to base class
Attributes:
see :class:`~tfields.TensorFields`
Examples:
>>> import tfields
>>> t = tfields.Triangles3D([[1,2,3], [3,3,3], [0,0,0]])
You can add fields to each triangle
>>> t = tfields.Triangles3D(t, tfields.Tensors([42]))
>>> assert t.fields[0].equal([42])
| class Triangles3D(tfields.TensorFields):
# pylint: disable=R0904
"""
Points3D child restricted to n * 3 Points.
Three Points always group together to one triangle.
Args:
tensors (Iterable | tfields.TensorFields)
*fields (Iterable | tfields.Tensors): Fields with the same length as tensors
**kwargs: passed to base class
Attributes:
see :class:`~tfields.TensorFields`
Examples:
>>> import tfields
>>> t = tfields.Triangles3D([[1,2,3], [3,3,3], [0,0,0]])
You can add fields to each triangle
>>> t = tfields.Triangles3D(t, tfields.Tensors([42]))
>>> assert t.fields[0].equal([42])
"""
def __new__(cls, tensors, *fields, **kwargs):
kwargs["dim"] = 3
kwargs["rigid"] = False
obj = super(Triangles3D, cls).__new__(cls, tensors, *fields, **kwargs)
if not len(obj) % 3 == 0:
warnings.warn(
"Input object of size({0}) has no divider 3 and"
" does not describe triangles.".format(len(obj))
)
return obj
def ntriangles(self):
"""
Returns:
int: number of triangles
"""
return len(self) // 3
def _to_triangles_mask(self, mask):
mask = np.array(mask)
mask = mask.reshape((self.ntriangles(), 3))
mask = mask.all(axis=1)
return mask
def __getitem__(self, index):
"""
In addition to the usual, also slice fields
Examples:
>>> import numpy as np
>>> import tfields
>>> vectors = tfields.Tensors(np.array([range(30)] * 3).T)
>>> triangles = tfields.Triangles3D(vectors, range(10))
>>> assert np.array_equal(triangles[3:6],
... [[3] * 3,
... [4] * 3,
... [5] * 3])
>>> assert triangles[3:6].fields[0][0] == 1
"""
item = super(tfields.TensorFields, self).__getitem__(index)
try: # __iter__ will try except __getitem__(i) until IndexError
if issubclass(type(item), Triangles3D): # block int, float, ...
if len(item) % 3 != 0:
item = tfields.Tensors(item)
elif item.fields:
# build triangle index / indices / mask when possible
tri_index = None
if isinstance(index, tuple):
index = index[0]
if isinstance(index, int):
pass
elif isinstance(index, slice):
start = index.start or 0
stop = index.stop or len(self)
step = index.step
if start % 3 == 0 and (stop - start) % 3 == 0 and step is None:
tri_index = slice(start // 3, stop // 3)
else:
try:
tri_index = self._to_triangles_mask(index)
except ValueError:
pass
# apply triangle index to fields
if tri_index is not None:
item.fields = [
field.__getitem__(tri_index) for field in item.fields
]
else:
item = tfields.Tensors(item)
except IndexError as err:
logging.warning(
"Index error occured for field.__getitem__. Error message: %s", err
)
return item
def _save_stl(self, path, **kwargs):
"""
Save the object to a stl file
"""
import stl
shape = stl.Mesh(np.zeros(self.ntriangles(), dtype=stl.Mesh.dtype))
shape.vectors = self.bulk.reshape((self.ntriangles(), 3, 3))
shape.save(path, **kwargs)
@classmethod
def _load_stl(cls, path):
"""
Factory method
Given a path to a stl file, construct the object
"""
import stl.mesh
triangles = stl.mesh.Mesh.from_file(path)
obj = cls(triangles.vectors.reshape(-1, 3))
return obj
@classmethod
def merged(cls, *objects, **kwargs):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
obj = super(Triangles3D, cls).merged(*objects, **kwargs)
if not len(obj) % 3 == 0:
warnings.warn(
"Input object of size({0}) has no divider 3 and"
" does not describe triangles.".format(len(obj))
)
return obj
def evalf(self, expression=None, coord_sys=None):
"""
Triangle3D implementation
Examples:
>>> from sympy.abc import x
>>> import numpy as np
>>> import tfields
>>> t = tfields.Triangles3D([[1., 2., 3.], [-4., 5., 6.], [1, 2, -6],
... [5, -5, -5], [1,0,-1], [0,1,-1],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> mask = t.evalf(x >= 0)
>>> assert np.array_equal(t[mask],
... tfields.Triangles3D([[ 5., -5., -5.],
... [ 1., 0., -1.],
... [ 0., 1., -1.]]))
Returns:
np.array: mask which is True, where expression evaluates True
"""
mask = super(Triangles3D, self).evalf(expression, coord_sys=coord_sys)
mask = self._to_triangles_mask(mask)
mask = np.array([mask] * 3).T.reshape((len(self)))
return mask
def cut(self, expression, coord_sys=None):
"""
Default cut method for Triangles3D
Examples:
>>> import sympy
>>> import numpy as np
>>> import tfields
>>> x, y, z = sympy.symbols('x y z')
>>> t = tfields.Triangles3D([[1., 2., 3.], [-4., 5., 6.], [1, 2, -6],
... [5, -5, -5], [1, 0, -1], [0, 1, -1],
... [-5, -5, -5], [1, 0, -1], [0, 1, -1]])
>>> tc = t.cut(x >= 0)
>>> assert tc.equal(tfields.Triangles3D([[ 5., -5., -5.],
... [ 1., 0., -1.],
... [ 0., 1., -1.]]))
>>> t.fields.append(tfields.Tensors([1,2,3]))
>>> tc2 = t.cut(x >= 0)
>>> assert np.array_equal(tc2.fields[-1], np.array([2.]))
"""
# mask = self.evalf(expression, coord_sys=coord_sys)
# inst = self[mask].copy()
# return inst
return super().cut(expression, coord_sys)
def mesh(self):
"""
Returns:
tfields.Mesh3D
"""
mp = tfields.TensorFields(np.arange(len(self)).reshape((-1, 3)), *self.fields)
mesh = tfields.Mesh3D(self, maps=[mp])
return mesh.cleaned(stale=False) # stale vertices can not occure here
@cached_property()
def _areas(self):
"""
Cached method to retrieve areas of triangles
"""
transform = np.eye(3)
return self.areas(transform=transform)
def areas(self, transform=None):
"""
Calculate area with "heron's formula"
Args:
transform (np.ndarray): optional transformation matrix
The triangle points are transformed with transform if given
before calclulating the area
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[1,0,0], [0,0,1], [0,0,0]],
... faces=[[0, 1, 2]])
>>> assert np.allclose(m.triangles().areas(), np.array([0.5]))
>>> m = tfields.Mesh3D([[1,0,0], [0,1,0], [0,0,0], [0,0,1]],
... faces=[[0, 1, 2], [1, 2, 3]])
>>> assert np.allclose(m.triangles().areas(), np.array([0.5, 0.5]))
>>> m = tfields.Mesh3D([[1,0,0], [0,1,0], [1,1,0], [0,0,1], [1,0,1]],
... faces=[[0, 1, 2], [0, 3, 4]])
>>> assert np.allclose(m.triangles().areas(), np.array([0.5, 0.5]))
"""
if transform is None:
return self._areas
else:
indices = range(self.ntriangles())
aIndices = [i * 3 for i in indices]
bIndices = [i * 3 + 1 for i in indices]
cIndices = [i * 3 + 2 for i in indices]
# define 3 vectors building the triangle, transform it back and take their norm
if not np.array_equal(transform, np.eye(3)):
a = np.linalg.norm(
np.linalg.solve(
transform.T, (self[aIndices, :] - self[bIndices, :]).T
),
axis=0,
)
b = np.linalg.norm(
np.linalg.solve(
transform.T, (self[aIndices, :] - self[cIndices, :]).T
),
axis=0,
)
c = np.linalg.norm(
np.linalg.solve(
transform.T, (self[bIndices, :] - self[cIndices, :]).T
),
axis=0,
)
else:
a = np.linalg.norm(self[aIndices, :] - self[bIndices, :], axis=1)
b = np.linalg.norm(self[aIndices, :] - self[cIndices, :], axis=1)
c = np.linalg.norm(self[bIndices, :] - self[cIndices, :], axis=1)
# sort by length for numerical stability
lengths = np.concatenate(
(a.reshape(-1, 1), b.reshape(-1, 1), c.reshape(-1, 1)), axis=1
)
lengths.sort()
a, b, c = lengths.T
return 0.25 * np.sqrt(
(a + (b + c)) * (c - (a - b)) * (c + (a - b)) * (a + (b - c))
)
def corners(self):
"""
Returns:
three np.arrays with corner points of triangles
"""
indices = range(self.ntriangles())
aIndices = [i * 3 for i in indices]
bIndices = [i * 3 + 1 for i in indices]
cIndices = [i * 3 + 2 for i in indices]
a = self.bulk[aIndices, :]
b = self.bulk[bIndices, :]
c = self.bulk[cIndices, :]
return a, b, c
def circumcenters(self):
"""
Semi baricentric method to calculate circumcenter points of the
triangles
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4], [1, 3, 4]]);
>>> assert np.allclose(
... m.triangles().circumcenters(),
... [[0.5, 0.5, 0.0],
... [-0.5, 0.5, 0.0],
... [0.0, 0.0, 0.0],
... [1.0 / 3, 1.0 / 3, 1.0 / 3]])
"""
pointA, pointB, pointC = self.corners()
a = np.linalg.norm(
pointC - pointB, axis=1
) # side length of side opposite to pointA
b = np.linalg.norm(pointC - pointA, axis=1)
c = np.linalg.norm(pointB - pointA, axis=1)
bary1 = a**2 * (b**2 + c**2 - a**2)
bary2 = b**2 * (a**2 + c**2 - b**2)
bary3 = c**2 * (a**2 + b**2 - c**2)
matrices = np.concatenate((pointA, pointB, pointC), axis=1).reshape(
pointA.shape + (3,)
)
# transpose the inner matrix
matrices = np.einsum("...ji", matrices)
vectors = np.array((bary1, bary2, bary3)).T
# matrix vector product for matrices and vectors
P = np.einsum("...ji,...i", matrices, vectors)
P /= vectors.sum(axis=1).reshape((len(vectors), 1))
return tfields.Points3D(P)
@cached_property()
def _centroids(self):
"""
this version is faster but takes much more ram also.
So much that i get memory error with a 32 GB RAM
"""
nT = self.ntriangles()
mat = np.ones((1, 3)) / 3.0
# matrix product calculatesq center of all triangles
return tfields.Points3D(
np.dot(mat, self.reshape(nT, 3, 3))[0], coord_sys=self.coord_sys
)
"""
Old version:
pointA, pointB, pointC = self.corners()
return Points3D(1. / 3 * (pointA + pointB + pointC)), coord_sys=self.coord_sys
This versioin was slightly slower (110 % of new version)
Memory usage of new version is better for a factor of 4 or so.
Not really reliable method of measurement
"""
def centroids(self):
"""
Returns:
:func:`~tfields.Triangles3D._centroids`
Examples:
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4], [1, 3, 4]]);
>>> assert m.triangles().centroids().equal(
... [[1./3, 1./3, 0.],
... [-1./3, 1./3, 0.],
... [0., 0., 1./3],
... [1./3, 1./3, 1./3]])
"""
return self._centroids
def edges(self):
"""
Retrieve two of the three edge vectors
Returns:
two np.ndarrays: vectors ab and ac, where a, b, c are corners (see
self.corners)
"""
a, b, c = self.corners()
ab = b - a
ac = c - a
return ab, ac
def norms(self):
"""
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4], [1, 3, 4]]);
>>> assert np.allclose(m.triangles().norms(),
... [[0.0, 0.0, 1.0],
... [0.0, 0.0, -1.0],
... [0.0, 1.0, 0.0],
... [0.57735027] * 3],
... atol=1e-8)
"""
ab, ac = self.edges()
vectors = np.cross(ab, ac)
norms = np.apply_along_axis(np.linalg.norm, 0, vectors.T).reshape(-1, 1)
# cross product may be zero, so replace zero norms by ones to divide vectors by norms
np.place(norms, norms == 0.0, 1.0)
return vectors / norms
def _baricentric(self, point, delta=0.0):
"""
Determine baricentric coordinates like
[u,v,w] = [ab, ac, ab x ac]^-1 * ap
where ax is vector from point a to point x
Examples:
empty Meshes return right formatted array
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([], faces=[])
>>> m.triangles()._baricentric(np.array([0.2, 0.2, 0]))
array([], dtype=float64)
>>> m2 = tfields.Mesh3D([[0,0,0], [2,0,0], [0,2,0], [0,0,2]],
... faces=[[0, 1, 2], [0, 2, 3]]);
>>> assert np.array_equal(
... m2.triangles()._baricentric(np.array([0.2, 0.2, 0]),
... delta=2.),
... [[0.1, 0.1, 0.0],
... [0.1, 0.0, 0.1]])
if point lies in the plane, return np.nan, else inf for w if delta
is exactly 0.
>>> baric = m2.triangles()._baricentric(np.array([0.2, 0.2, 0]),
... delta=0.),
>>> baric_expected = np.array([[0.1, 0.1, np.nan],
... [0.1, 0.0, np.inf]])
>>> assert ((baric == baric_expected) | (np.isnan(baric) &
... np.isnan(baric_expected))).all()
Raises:
If you define triangles that have colinear side vectors or in general lead to
not invertable matrices [ab, ac, ab x ac] the values will be nan and
a warning will be triggered:
>>> import warnings
>>> import numpy as np
>>> import tfields
>>> m3 = tfields.Mesh3D([[0,0,0], [2,0,0], [4,0,0], [0,1,0]],
... maps=[[[0, 1, 2], [0, 1, 3]]]);
>>> with warnings.catch_warnings(record=True) as wrn:
... warnings.simplefilter("ignore")
... bc = m3.triangles()._baricentric(np.array([0.2, 0.2, 0]), delta=0.3)
>>> bc_exp = np.array([[ np.nan, np.nan, np.nan], [ 0.1, 0.2, 0. ]])
>>> assert ((bc == bc_exp) | (np.isnan(bc) &
... np.isnan(bc_exp))).all()
The warning would be:
UserWarning('Singular matrix: Could not invert matrix ...
... [[ 2. 4. 0.], [ 0. 0. 0.], [ 0. 0. 0.]]. Return nan matrix.',)
Returns:
np.ndarray: barycentric coordinates u, v, w of point with respect to each triangle
"""
if self.ntriangles() == 0:
return np.array([])
a, _, _ = self.corners()
ap = point - a
# matrix vector product for matrices and vectors
barCoords = np.einsum("...ji,...i", self._baricentric_matrix, ap)
with warnings.catch_warnings():
# python2.7
warnings.filterwarnings(
"ignore", message="invalid value encountered in divide"
)
warnings.filterwarnings(
"ignore", message="divide by zero encountered in divide"
)
# python3.x
warnings.filterwarnings(
"ignore", message="invalid value encountered in true_divide"
)
warnings.filterwarnings(
"ignore", message="divide by zero encountered in true_divide"
)
barCoords[:, 2] /= delta # allow devide by 0.
return barCoords
@cached_property()
def _baricentric_matrix(self):
"""
cached barycentric matrix for faster calculations
"""
ab, ac = self.edges()
# get norm vector TODO: replace by norm = self.norms()
norm = np.cross(ab, ac)
normLen = np.linalg.norm(norm, axis=1)
normLen = normLen.reshape((1,) + normLen.shape)
colinear_mask = normLen == 0
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
# prevent divide by 0
norm[np.where(~colinear_mask.T)] = (
norm[np.where(~colinear_mask.T)] / normLen.T[np.where(~colinear_mask.T)]
)
matrix = np.concatenate((ab, ac, norm), axis=1).reshape(ab.shape + (3,))
matrix = np.einsum("...ji", matrix) # transpose the inner matrix
# invert matrix if possible
# matrixI = np.linalg.inv(matrix) # one line variant without exception
matrixI = []
for mat in matrix:
try:
matrixI.append(np.linalg.inv(mat))
except np.linalg.linalg.LinAlgError as e:
if str(e) == "Singular matrix":
warnings.warn(
"Singular matrix: Could not invert matrix "
"{0}. Return nan matrix.".format(str(mat).replace("\n", ","))
)
matrixI.append(np.full((3, 3), np.nan))
return np.array(matrixI)
def _in_triangles(self, point, delta=0.0):
"""
Barycentric method to optain, wheter a point is in any of the triangles
Args:
point (list of len 3)
delta (float / None):
float: acceptance in +- norm vector direction
None: accept the face with the minimum distance to the point
Returns:
np.array: boolean mask, True where point in a triangle within delta
Examples:
see tests/test_triangles_3d.py
"""
if self.ntriangles() == 0:
return np.array([], dtype=bool)
try:
point = np.reshape(point, 3)
except ValueError:
raise ValueError(
"point must be castable to shape 3 but is of shape {0}".format(
point.shape
)
)
# min_dist_method switch if delta is None
if delta is None:
delta = 1.0
min_dist_method = True
else:
min_dist_method = False
u, v, w = self._baricentric(point, delta=delta).T
if delta == 0.0:
w[np.isnan(w)] = 0.0 # division by 0 in baricentric makes w = 0 nan.
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", message="invalid value encountered in less_equal"
)
barycentric_bools = (
((v <= 1.0) & (v >= 0.0)) & ((u <= 1.0) & (u >= 0.0)) & ((v + u <= 1.0))
)
if all(~barycentric_bools):
return barycentric_bools
if min_dist_method:
orthogonal_acceptance = np.full(
barycentric_bools.shape, False, dtype=bool
)
closest_indices = np.argmin(abs(w)[barycentric_bools])
# transform the indices to the whole array, not only the
# barycentric_bools selection
closest_indices = np.arange(len(barycentric_bools))[barycentric_bools][
closest_indices
]
orthogonal_acceptance[closest_indices] = True
else:
orthogonal_acceptance = abs(w) <= 1
return np.array(barycentric_bools & orthogonal_acceptance)
def in_triangles(
self,
tensors,
delta: typing.Optional[float] = 0.0,
assign_multiple: bool = False,
) -> typing.Union[typing.List[typing.List[int]], np.array]:
"""
Barycentric method to obtain, which tensors are containes in any of the triangles
Args:
tensors (Points3D instance)
optional:
delta:
:obj:`float`: Normal distance to a triangle, that the points
are concidered to be contained in the triangle.
:obj:`None`: Find the minimum distance.
Default is 0.
assign_multiple: If True, one point may belong to multiple
triangles at the same time. In the other case the first
occurence will be True the other False
Returns:
list: [index(or indices if assign_multiple) of triangle for point in tensors]
"""
indices = np.full(tensors.shape[0], -1, dtype=int)
if self.ntriangles() == 0:
if assign_multiple:
return [[-1] * len(indices)]
else:
return indices
with tensors.tmp_transform(self.coord_sys):
for i, point in enumerate(iter(tensors)):
mask = self._in_triangles(point, delta)
if np.any(mask):
if assign_multiple:
index = np.argwhere(mask == np.amax(mask))
index.flatten().tolist()
indices.append(index)
else:
indices[i] = np.argmax(mask)
else:
if assign_multiple:
indices.append([-1])
else:
indices[i] = -1
return indices
def _on_edges(self, point):
"""
Determine whether a point is on the edge / side ray of a triangle
TODO:
on_edges like in_triangles
Returns:
np.array: boolean mask which is true, if point is on one side ray
of a triangle
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4]]);
Corner points are found
>>> assert np.array_equal(
... m.triangles()._on_edges(tfields.Points3D([[0,1,0]])),
... np.array([ True, True, False], dtype=bool))
Side points are found, too
>>> assert np.array_equal(
... m.triangles()._on_edges(tfields.Points3D([[0.5,0,0.5]])),
... np.array([False, False, True], dtype=bool))
"""
u, v, w = self._baricentric(point, 1.0).T
orthogonal_acceptance = w == 0 # point should lie in triangle
barycentric_bools = (
(((0.0 <= v) & (v <= 1.0)) & (u == 0.0))
| (((0.0 <= u) & (u <= 1.0)) & (v == 0.0))
| (v + u == 1.0)
)
return np.array(barycentric_bools & orthogonal_acceptance)
def _weights(self, weights, rigid=False):
"""
transformer method for weights inputs.
Args:
weights (np.ndarray | int | None):
If weights is integer it will be used as index for fields and fields are
used as weights.
If weights is None it will
Otherwise just pass the weights.
Returns:
TODO: Better docs
"""
# set weights to 1.0 if weights is None
if weights is None:
weights = np.ones(self.ntriangles())
return super(Triangles3D, self)._weights(weights, rigid=rigid)
| (tensors, *fields, **kwargs) |
21,438 | tfields.triangles_3d | __getitem__ |
In addition to the usual, also slice fields
Examples:
>>> import numpy as np
>>> import tfields
>>> vectors = tfields.Tensors(np.array([range(30)] * 3).T)
>>> triangles = tfields.Triangles3D(vectors, range(10))
>>> assert np.array_equal(triangles[3:6],
... [[3] * 3,
... [4] * 3,
... [5] * 3])
>>> assert triangles[3:6].fields[0][0] == 1
| def __getitem__(self, index):
"""
In addition to the usual, also slice fields
Examples:
>>> import numpy as np
>>> import tfields
>>> vectors = tfields.Tensors(np.array([range(30)] * 3).T)
>>> triangles = tfields.Triangles3D(vectors, range(10))
>>> assert np.array_equal(triangles[3:6],
... [[3] * 3,
... [4] * 3,
... [5] * 3])
>>> assert triangles[3:6].fields[0][0] == 1
"""
item = super(tfields.TensorFields, self).__getitem__(index)
try: # __iter__ will try except __getitem__(i) until IndexError
if issubclass(type(item), Triangles3D): # block int, float, ...
if len(item) % 3 != 0:
item = tfields.Tensors(item)
elif item.fields:
# build triangle index / indices / mask when possible
tri_index = None
if isinstance(index, tuple):
index = index[0]
if isinstance(index, int):
pass
elif isinstance(index, slice):
start = index.start or 0
stop = index.stop or len(self)
step = index.step
if start % 3 == 0 and (stop - start) % 3 == 0 and step is None:
tri_index = slice(start // 3, stop // 3)
else:
try:
tri_index = self._to_triangles_mask(index)
except ValueError:
pass
# apply triangle index to fields
if tri_index is not None:
item.fields = [
field.__getitem__(tri_index) for field in item.fields
]
else:
item = tfields.Tensors(item)
except IndexError as err:
logging.warning(
"Index error occured for field.__getitem__. Error message: %s", err
)
return item
| (self, index) |
21,440 | tfields.triangles_3d | __new__ | null | def __new__(cls, tensors, *fields, **kwargs):
kwargs["dim"] = 3
kwargs["rigid"] = False
obj = super(Triangles3D, cls).__new__(cls, tensors, *fields, **kwargs)
if not len(obj) % 3 == 0:
warnings.warn(
"Input object of size({0}) has no divider 3 and"
" does not describe triangles.".format(len(obj))
)
return obj
| (cls, tensors, *fields, **kwargs) |
21,447 | tfields.triangles_3d | _baricentric |
Determine baricentric coordinates like
[u,v,w] = [ab, ac, ab x ac]^-1 * ap
where ax is vector from point a to point x
Examples:
empty Meshes return right formatted array
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([], faces=[])
>>> m.triangles()._baricentric(np.array([0.2, 0.2, 0]))
array([], dtype=float64)
>>> m2 = tfields.Mesh3D([[0,0,0], [2,0,0], [0,2,0], [0,0,2]],
... faces=[[0, 1, 2], [0, 2, 3]]);
>>> assert np.array_equal(
... m2.triangles()._baricentric(np.array([0.2, 0.2, 0]),
... delta=2.),
... [[0.1, 0.1, 0.0],
... [0.1, 0.0, 0.1]])
if point lies in the plane, return np.nan, else inf for w if delta
is exactly 0.
>>> baric = m2.triangles()._baricentric(np.array([0.2, 0.2, 0]),
... delta=0.),
>>> baric_expected = np.array([[0.1, 0.1, np.nan],
... [0.1, 0.0, np.inf]])
>>> assert ((baric == baric_expected) | (np.isnan(baric) &
... np.isnan(baric_expected))).all()
Raises:
If you define triangles that have colinear side vectors or in general lead to
not invertable matrices [ab, ac, ab x ac] the values will be nan and
a warning will be triggered:
>>> import warnings
>>> import numpy as np
>>> import tfields
>>> m3 = tfields.Mesh3D([[0,0,0], [2,0,0], [4,0,0], [0,1,0]],
... maps=[[[0, 1, 2], [0, 1, 3]]]);
>>> with warnings.catch_warnings(record=True) as wrn:
... warnings.simplefilter("ignore")
... bc = m3.triangles()._baricentric(np.array([0.2, 0.2, 0]), delta=0.3)
>>> bc_exp = np.array([[ np.nan, np.nan, np.nan], [ 0.1, 0.2, 0. ]])
>>> assert ((bc == bc_exp) | (np.isnan(bc) &
... np.isnan(bc_exp))).all()
The warning would be:
UserWarning('Singular matrix: Could not invert matrix ...
... [[ 2. 4. 0.], [ 0. 0. 0.], [ 0. 0. 0.]]. Return nan matrix.',)
Returns:
np.ndarray: barycentric coordinates u, v, w of point with respect to each triangle
| def _baricentric(self, point, delta=0.0):
"""
Determine baricentric coordinates like
[u,v,w] = [ab, ac, ab x ac]^-1 * ap
where ax is vector from point a to point x
Examples:
empty Meshes return right formatted array
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([], faces=[])
>>> m.triangles()._baricentric(np.array([0.2, 0.2, 0]))
array([], dtype=float64)
>>> m2 = tfields.Mesh3D([[0,0,0], [2,0,0], [0,2,0], [0,0,2]],
... faces=[[0, 1, 2], [0, 2, 3]]);
>>> assert np.array_equal(
... m2.triangles()._baricentric(np.array([0.2, 0.2, 0]),
... delta=2.),
... [[0.1, 0.1, 0.0],
... [0.1, 0.0, 0.1]])
if point lies in the plane, return np.nan, else inf for w if delta
is exactly 0.
>>> baric = m2.triangles()._baricentric(np.array([0.2, 0.2, 0]),
... delta=0.),
>>> baric_expected = np.array([[0.1, 0.1, np.nan],
... [0.1, 0.0, np.inf]])
>>> assert ((baric == baric_expected) | (np.isnan(baric) &
... np.isnan(baric_expected))).all()
Raises:
If you define triangles that have colinear side vectors or in general lead to
not invertable matrices [ab, ac, ab x ac] the values will be nan and
a warning will be triggered:
>>> import warnings
>>> import numpy as np
>>> import tfields
>>> m3 = tfields.Mesh3D([[0,0,0], [2,0,0], [4,0,0], [0,1,0]],
... maps=[[[0, 1, 2], [0, 1, 3]]]);
>>> with warnings.catch_warnings(record=True) as wrn:
... warnings.simplefilter("ignore")
... bc = m3.triangles()._baricentric(np.array([0.2, 0.2, 0]), delta=0.3)
>>> bc_exp = np.array([[ np.nan, np.nan, np.nan], [ 0.1, 0.2, 0. ]])
>>> assert ((bc == bc_exp) | (np.isnan(bc) &
... np.isnan(bc_exp))).all()
The warning would be:
UserWarning('Singular matrix: Could not invert matrix ...
... [[ 2. 4. 0.], [ 0. 0. 0.], [ 0. 0. 0.]]. Return nan matrix.',)
Returns:
np.ndarray: barycentric coordinates u, v, w of point with respect to each triangle
"""
if self.ntriangles() == 0:
return np.array([])
a, _, _ = self.corners()
ap = point - a
# matrix vector product for matrices and vectors
barCoords = np.einsum("...ji,...i", self._baricentric_matrix, ap)
with warnings.catch_warnings():
# python2.7
warnings.filterwarnings(
"ignore", message="invalid value encountered in divide"
)
warnings.filterwarnings(
"ignore", message="divide by zero encountered in divide"
)
# python3.x
warnings.filterwarnings(
"ignore", message="invalid value encountered in true_divide"
)
warnings.filterwarnings(
"ignore", message="divide by zero encountered in true_divide"
)
barCoords[:, 2] /= delta # allow devide by 0.
return barCoords
| (self, point, delta=0.0) |
21,450 | tfields.triangles_3d | _in_triangles |
Barycentric method to optain, wheter a point is in any of the triangles
Args:
point (list of len 3)
delta (float / None):
float: acceptance in +- norm vector direction
None: accept the face with the minimum distance to the point
Returns:
np.array: boolean mask, True where point in a triangle within delta
Examples:
see tests/test_triangles_3d.py
| def _in_triangles(self, point, delta=0.0):
"""
Barycentric method to optain, wheter a point is in any of the triangles
Args:
point (list of len 3)
delta (float / None):
float: acceptance in +- norm vector direction
None: accept the face with the minimum distance to the point
Returns:
np.array: boolean mask, True where point in a triangle within delta
Examples:
see tests/test_triangles_3d.py
"""
if self.ntriangles() == 0:
return np.array([], dtype=bool)
try:
point = np.reshape(point, 3)
except ValueError:
raise ValueError(
"point must be castable to shape 3 but is of shape {0}".format(
point.shape
)
)
# min_dist_method switch if delta is None
if delta is None:
delta = 1.0
min_dist_method = True
else:
min_dist_method = False
u, v, w = self._baricentric(point, delta=delta).T
if delta == 0.0:
w[np.isnan(w)] = 0.0 # division by 0 in baricentric makes w = 0 nan.
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", message="invalid value encountered in less_equal"
)
barycentric_bools = (
((v <= 1.0) & (v >= 0.0)) & ((u <= 1.0) & (u >= 0.0)) & ((v + u <= 1.0))
)
if all(~barycentric_bools):
return barycentric_bools
if min_dist_method:
orthogonal_acceptance = np.full(
barycentric_bools.shape, False, dtype=bool
)
closest_indices = np.argmin(abs(w)[barycentric_bools])
# transform the indices to the whole array, not only the
# barycentric_bools selection
closest_indices = np.arange(len(barycentric_bools))[barycentric_bools][
closest_indices
]
orthogonal_acceptance[closest_indices] = True
else:
orthogonal_acceptance = abs(w) <= 1
return np.array(barycentric_bools & orthogonal_acceptance)
| (self, point, delta=0.0) |
21,452 | tfields.triangles_3d | _on_edges |
Determine whether a point is on the edge / side ray of a triangle
TODO:
on_edges like in_triangles
Returns:
np.array: boolean mask which is true, if point is on one side ray
of a triangle
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4]]);
Corner points are found
>>> assert np.array_equal(
... m.triangles()._on_edges(tfields.Points3D([[0,1,0]])),
... np.array([ True, True, False], dtype=bool))
Side points are found, too
>>> assert np.array_equal(
... m.triangles()._on_edges(tfields.Points3D([[0.5,0,0.5]])),
... np.array([False, False, True], dtype=bool))
| def _on_edges(self, point):
"""
Determine whether a point is on the edge / side ray of a triangle
TODO:
on_edges like in_triangles
Returns:
np.array: boolean mask which is true, if point is on one side ray
of a triangle
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4]]);
Corner points are found
>>> assert np.array_equal(
... m.triangles()._on_edges(tfields.Points3D([[0,1,0]])),
... np.array([ True, True, False], dtype=bool))
Side points are found, too
>>> assert np.array_equal(
... m.triangles()._on_edges(tfields.Points3D([[0.5,0,0.5]])),
... np.array([False, False, True], dtype=bool))
"""
u, v, w = self._baricentric(point, 1.0).T
orthogonal_acceptance = w == 0 # point should lie in triangle
barycentric_bools = (
(((0.0 <= v) & (v <= 1.0)) & (u == 0.0))
| (((0.0 <= u) & (u <= 1.0)) & (v == 0.0))
| (v + u == 1.0)
)
return np.array(barycentric_bools & orthogonal_acceptance)
| (self, point) |
21,456 | tfields.triangles_3d | _save_stl |
Save the object to a stl file
| def _save_stl(self, path, **kwargs):
"""
Save the object to a stl file
"""
import stl
shape = stl.Mesh(np.zeros(self.ntriangles(), dtype=stl.Mesh.dtype))
shape.vectors = self.bulk.reshape((self.ntriangles(), 3, 3))
shape.save(path, **kwargs)
| (self, path, **kwargs) |
21,458 | tfields.triangles_3d | _to_triangles_mask | null | def _to_triangles_mask(self, mask):
mask = np.array(mask)
mask = mask.reshape((self.ntriangles(), 3))
mask = mask.all(axis=1)
return mask
| (self, mask) |
21,459 | tfields.triangles_3d | _weights |
transformer method for weights inputs.
Args:
weights (np.ndarray | int | None):
If weights is integer it will be used as index for fields and fields are
used as weights.
If weights is None it will
Otherwise just pass the weights.
Returns:
TODO: Better docs
| def _weights(self, weights, rigid=False):
"""
transformer method for weights inputs.
Args:
weights (np.ndarray | int | None):
If weights is integer it will be used as index for fields and fields are
used as weights.
If weights is None it will
Otherwise just pass the weights.
Returns:
TODO: Better docs
"""
# set weights to 1.0 if weights is None
if weights is None:
weights = np.ones(self.ntriangles())
return super(Triangles3D, self)._weights(weights, rigid=rigid)
| (self, weights, rigid=False) |
21,460 | tfields.triangles_3d | areas |
Calculate area with "heron's formula"
Args:
transform (np.ndarray): optional transformation matrix
The triangle points are transformed with transform if given
before calclulating the area
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[1,0,0], [0,0,1], [0,0,0]],
... faces=[[0, 1, 2]])
>>> assert np.allclose(m.triangles().areas(), np.array([0.5]))
>>> m = tfields.Mesh3D([[1,0,0], [0,1,0], [0,0,0], [0,0,1]],
... faces=[[0, 1, 2], [1, 2, 3]])
>>> assert np.allclose(m.triangles().areas(), np.array([0.5, 0.5]))
>>> m = tfields.Mesh3D([[1,0,0], [0,1,0], [1,1,0], [0,0,1], [1,0,1]],
... faces=[[0, 1, 2], [0, 3, 4]])
>>> assert np.allclose(m.triangles().areas(), np.array([0.5, 0.5]))
| def areas(self, transform=None):
"""
Calculate area with "heron's formula"
Args:
transform (np.ndarray): optional transformation matrix
The triangle points are transformed with transform if given
before calclulating the area
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[1,0,0], [0,0,1], [0,0,0]],
... faces=[[0, 1, 2]])
>>> assert np.allclose(m.triangles().areas(), np.array([0.5]))
>>> m = tfields.Mesh3D([[1,0,0], [0,1,0], [0,0,0], [0,0,1]],
... faces=[[0, 1, 2], [1, 2, 3]])
>>> assert np.allclose(m.triangles().areas(), np.array([0.5, 0.5]))
>>> m = tfields.Mesh3D([[1,0,0], [0,1,0], [1,1,0], [0,0,1], [1,0,1]],
... faces=[[0, 1, 2], [0, 3, 4]])
>>> assert np.allclose(m.triangles().areas(), np.array([0.5, 0.5]))
"""
if transform is None:
return self._areas
else:
indices = range(self.ntriangles())
aIndices = [i * 3 for i in indices]
bIndices = [i * 3 + 1 for i in indices]
cIndices = [i * 3 + 2 for i in indices]
# define 3 vectors building the triangle, transform it back and take their norm
if not np.array_equal(transform, np.eye(3)):
a = np.linalg.norm(
np.linalg.solve(
transform.T, (self[aIndices, :] - self[bIndices, :]).T
),
axis=0,
)
b = np.linalg.norm(
np.linalg.solve(
transform.T, (self[aIndices, :] - self[cIndices, :]).T
),
axis=0,
)
c = np.linalg.norm(
np.linalg.solve(
transform.T, (self[bIndices, :] - self[cIndices, :]).T
),
axis=0,
)
else:
a = np.linalg.norm(self[aIndices, :] - self[bIndices, :], axis=1)
b = np.linalg.norm(self[aIndices, :] - self[cIndices, :], axis=1)
c = np.linalg.norm(self[bIndices, :] - self[cIndices, :], axis=1)
# sort by length for numerical stability
lengths = np.concatenate(
(a.reshape(-1, 1), b.reshape(-1, 1), c.reshape(-1, 1)), axis=1
)
lengths.sort()
a, b, c = lengths.T
return 0.25 * np.sqrt(
(a + (b + c)) * (c - (a - b)) * (c + (a - b)) * (a + (b - c))
)
| (self, transform=None) |
21,461 | tfields.triangles_3d | centroids |
Returns:
:func:`~tfields.Triangles3D._centroids`
Examples:
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4], [1, 3, 4]]);
>>> assert m.triangles().centroids().equal(
... [[1./3, 1./3, 0.],
... [-1./3, 1./3, 0.],
... [0., 0., 1./3],
... [1./3, 1./3, 1./3]])
| def centroids(self):
"""
Returns:
:func:`~tfields.Triangles3D._centroids`
Examples:
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4], [1, 3, 4]]);
>>> assert m.triangles().centroids().equal(
... [[1./3, 1./3, 0.],
... [-1./3, 1./3, 0.],
... [0., 0., 1./3],
... [1./3, 1./3, 1./3]])
"""
return self._centroids
| (self) |
21,462 | tfields.triangles_3d | circumcenters |
Semi baricentric method to calculate circumcenter points of the
triangles
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4], [1, 3, 4]]);
>>> assert np.allclose(
... m.triangles().circumcenters(),
... [[0.5, 0.5, 0.0],
... [-0.5, 0.5, 0.0],
... [0.0, 0.0, 0.0],
... [1.0 / 3, 1.0 / 3, 1.0 / 3]])
| def circumcenters(self):
"""
Semi baricentric method to calculate circumcenter points of the
triangles
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4], [1, 3, 4]]);
>>> assert np.allclose(
... m.triangles().circumcenters(),
... [[0.5, 0.5, 0.0],
... [-0.5, 0.5, 0.0],
... [0.0, 0.0, 0.0],
... [1.0 / 3, 1.0 / 3, 1.0 / 3]])
"""
pointA, pointB, pointC = self.corners()
a = np.linalg.norm(
pointC - pointB, axis=1
) # side length of side opposite to pointA
b = np.linalg.norm(pointC - pointA, axis=1)
c = np.linalg.norm(pointB - pointA, axis=1)
bary1 = a**2 * (b**2 + c**2 - a**2)
bary2 = b**2 * (a**2 + c**2 - b**2)
bary3 = c**2 * (a**2 + b**2 - c**2)
matrices = np.concatenate((pointA, pointB, pointC), axis=1).reshape(
pointA.shape + (3,)
)
# transpose the inner matrix
matrices = np.einsum("...ji", matrices)
vectors = np.array((bary1, bary2, bary3)).T
# matrix vector product for matrices and vectors
P = np.einsum("...ji,...i", matrices, vectors)
P /= vectors.sum(axis=1).reshape((len(vectors), 1))
return tfields.Points3D(P)
| (self) |
21,466 | tfields.triangles_3d | corners |
Returns:
three np.arrays with corner points of triangles
| def corners(self):
"""
Returns:
three np.arrays with corner points of triangles
"""
indices = range(self.ntriangles())
aIndices = [i * 3 for i in indices]
bIndices = [i * 3 + 1 for i in indices]
cIndices = [i * 3 + 2 for i in indices]
a = self.bulk[aIndices, :]
b = self.bulk[bIndices, :]
c = self.bulk[cIndices, :]
return a, b, c
| (self) |
21,468 | tfields.triangles_3d | cut |
Default cut method for Triangles3D
Examples:
>>> import sympy
>>> import numpy as np
>>> import tfields
>>> x, y, z = sympy.symbols('x y z')
>>> t = tfields.Triangles3D([[1., 2., 3.], [-4., 5., 6.], [1, 2, -6],
... [5, -5, -5], [1, 0, -1], [0, 1, -1],
... [-5, -5, -5], [1, 0, -1], [0, 1, -1]])
>>> tc = t.cut(x >= 0)
>>> assert tc.equal(tfields.Triangles3D([[ 5., -5., -5.],
... [ 1., 0., -1.],
... [ 0., 1., -1.]]))
>>> t.fields.append(tfields.Tensors([1,2,3]))
>>> tc2 = t.cut(x >= 0)
>>> assert np.array_equal(tc2.fields[-1], np.array([2.]))
| def cut(self, expression, coord_sys=None):
"""
Default cut method for Triangles3D
Examples:
>>> import sympy
>>> import numpy as np
>>> import tfields
>>> x, y, z = sympy.symbols('x y z')
>>> t = tfields.Triangles3D([[1., 2., 3.], [-4., 5., 6.], [1, 2, -6],
... [5, -5, -5], [1, 0, -1], [0, 1, -1],
... [-5, -5, -5], [1, 0, -1], [0, 1, -1]])
>>> tc = t.cut(x >= 0)
>>> assert tc.equal(tfields.Triangles3D([[ 5., -5., -5.],
... [ 1., 0., -1.],
... [ 0., 1., -1.]]))
>>> t.fields.append(tfields.Tensors([1,2,3]))
>>> tc2 = t.cut(x >= 0)
>>> assert np.array_equal(tc2.fields[-1], np.array([2.]))
"""
# mask = self.evalf(expression, coord_sys=coord_sys)
# inst = self[mask].copy()
# return inst
return super().cut(expression, coord_sys)
| (self, expression, coord_sys=None) |
21,471 | tfields.triangles_3d | edges |
Retrieve two of the three edge vectors
Returns:
two np.ndarrays: vectors ab and ac, where a, b, c are corners (see
self.corners)
| def edges(self):
"""
Retrieve two of the three edge vectors
Returns:
two np.ndarrays: vectors ab and ac, where a, b, c are corners (see
self.corners)
"""
a, b, c = self.corners()
ab = b - a
ac = c - a
return ab, ac
| (self) |
21,474 | tfields.triangles_3d | evalf |
Triangle3D implementation
Examples:
>>> from sympy.abc import x
>>> import numpy as np
>>> import tfields
>>> t = tfields.Triangles3D([[1., 2., 3.], [-4., 5., 6.], [1, 2, -6],
... [5, -5, -5], [1,0,-1], [0,1,-1],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> mask = t.evalf(x >= 0)
>>> assert np.array_equal(t[mask],
... tfields.Triangles3D([[ 5., -5., -5.],
... [ 1., 0., -1.],
... [ 0., 1., -1.]]))
Returns:
np.array: mask which is True, where expression evaluates True
| def evalf(self, expression=None, coord_sys=None):
"""
Triangle3D implementation
Examples:
>>> from sympy.abc import x
>>> import numpy as np
>>> import tfields
>>> t = tfields.Triangles3D([[1., 2., 3.], [-4., 5., 6.], [1, 2, -6],
... [5, -5, -5], [1,0,-1], [0,1,-1],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> mask = t.evalf(x >= 0)
>>> assert np.array_equal(t[mask],
... tfields.Triangles3D([[ 5., -5., -5.],
... [ 1., 0., -1.],
... [ 0., 1., -1.]]))
Returns:
np.array: mask which is True, where expression evaluates True
"""
mask = super(Triangles3D, self).evalf(expression, coord_sys=coord_sys)
mask = self._to_triangles_mask(mask)
mask = np.array([mask] * 3).T.reshape((len(self)))
return mask
| (self, expression=None, coord_sys=None) |
21,475 | tfields.triangles_3d | in_triangles |
Barycentric method to obtain, which tensors are containes in any of the triangles
Args:
tensors (Points3D instance)
optional:
delta:
:obj:`float`: Normal distance to a triangle, that the points
are concidered to be contained in the triangle.
:obj:`None`: Find the minimum distance.
Default is 0.
assign_multiple: If True, one point may belong to multiple
triangles at the same time. In the other case the first
occurence will be True the other False
Returns:
list: [index(or indices if assign_multiple) of triangle for point in tensors]
| def in_triangles(
self,
tensors,
delta: typing.Optional[float] = 0.0,
assign_multiple: bool = False,
) -> typing.Union[typing.List[typing.List[int]], np.array]:
"""
Barycentric method to obtain, which tensors are containes in any of the triangles
Args:
tensors (Points3D instance)
optional:
delta:
:obj:`float`: Normal distance to a triangle, that the points
are concidered to be contained in the triangle.
:obj:`None`: Find the minimum distance.
Default is 0.
assign_multiple: If True, one point may belong to multiple
triangles at the same time. In the other case the first
occurence will be True the other False
Returns:
list: [index(or indices if assign_multiple) of triangle for point in tensors]
"""
indices = np.full(tensors.shape[0], -1, dtype=int)
if self.ntriangles() == 0:
if assign_multiple:
return [[-1] * len(indices)]
else:
return indices
with tensors.tmp_transform(self.coord_sys):
for i, point in enumerate(iter(tensors)):
mask = self._in_triangles(point, delta)
if np.any(mask):
if assign_multiple:
index = np.argwhere(mask == np.amax(mask))
index.flatten().tolist()
indices.append(index)
else:
indices[i] = np.argmax(mask)
else:
if assign_multiple:
indices.append([-1])
else:
indices[i] = -1
return indices
| (self, tensors, delta: Optional[float] = 0.0, assign_multiple: bool = False) -> Union[List[List[int]], <built-in function array>] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.