scallop dome pyformex logo

Previous topic

pyFormex reference manual

Next topic

2. formex — Formex algebra in Python

[FSF Associate Member]

Valid XHTML 1.0 Transitional

1. coords — A structured collection of 3D coordinates.

The coords module defines the Coords class, which is the basic data structure in pyFormex to store the coordinates of points in a 3D space.

This module implements a data class for storing large sets of 3D coordinates and provides an extensive set of methods for transforming these coordinates. Most of pyFormex’s classes which represent geometry (e.g. Geometry, Formex, Mesh, TriSurface, Curve) use a Coords object to store their coordinates, and thus inherit all the transformation methods of this class.

While the user will mostly use the higher level classes, he might occasionally find good reason to use the Coords class directly as well.

Classes defined in module coords

class coords.Coords

A structured collection of points in a 3D cartesian space.

The Coords class is the basic data structure used throughout pyFormex to store coordinates of points in a 3D space. It is used by other classes, such as Formex and Surface, which thus inherit the same transformation capabilities. Applications will mostly use the higher level classes, which usually have more elaborated consistency checking and error handling.

Coords is implemented as a subclass of numpy.ndarray, and thus inherits all its methods. The last axis of the Coords always has a length equal to 3. Each set of 3 values along the last axis represents a single point in 3D cartesian space. The float datatype is only checked at creation time. It is the responsibility of the user to keep this consistent throughout the lifetime of the object.

A new Coords object is created with the following syntax

Coords(data=None,dtyp=Float,copy=False)

Parameters:

  • data: array_like of type float. The last axis should have a length of 1, 2 or 3, bu will always be expanded to 3. If no data are specified, an empty Coords with shape (0,3) is created.
  • dtyp: the float datatype to be used. It not specified, the datatype of data is used, or the default Float (which is equivalent to numpy.float32).
  • copy: boolean. If True, the data are copied. The default setting will try to use the original data if possible, e.g. if data is a correctly shaped and typed numpy.ndarray.

Example:

>>> Coords([1.,0.])
Coords([ 1.,  0.,  0.], dtype=float32)
points()

Returns the Coords object as a simple set of points.

This reshapes the array to a 2-dimensional array, flattening the structure of the points.

pshape()

Returns the shape of the Coords object.

This is the shape of the NumPy array with the last axis removed. The full shape of the Coords array can be obtained from its shape attribute.

npoints()

Return the total number of points.

ncoords()

Return the total number of points.

x()

Return the X-coordinates of all points.

Returns an array with all the X-coordinates in the Coords. The returned array has the same shape as the Coords array along its first ndim-1 axes. This is equivalent with

self[...,0]
y()

Return the Y-coordinates of all points.

Returns an array with all the Y-coordinates in the Coords. The returned array has the same shape as the Coords array along its first ndim-1 axes. This is equivalent with

self[...,1]
z()

Return the Z-coordinates of all points.

Returns an array with all the Z-coordinates in the Coords. The returned array has the same shape as the Coords array along its first ndim-1 axes. This is equivalent with

self[...,0]
bbox()

Return the bounding box of a set of points.

The bounding box is the smallest rectangular volume in the global coordinates, such that no point of the Coords are outside that volume.

Returns:

A Coords object with shape(2,3): the first point contains the minimal coordinates, the second has the maximal ones.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).bbox()
[[ 0.  0.  0.]
 [ 3.  3.  0.]]
center()

Return the center of the Coords.

The center of a Coords is the center of its bbox(). The return value is a (3,) shaped Coords object.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).center()
[ 1.5  1.5  0. ]

See also: centroid()

average(wts=None, axis=0)

Return a (weighted) average of the Coords.

The average of a Coords is a Coords with one axis less than the original, obtained by averaging all the points along that axis. The weights array can either be 1-D (in which case its length must be the size along the given axis) or of the same shape as a. Weights can be specified as a 1-D array with the length of that axis, or as an array with the same shape as the Coords. The sum of the weights (along the specified axis if not 1-D) will generally be equal to 1.0. If wts=None, then all points are assumed to have a weight equal to one divided by the length of the specified axis.

Example:

>>> print Coords([[[0.,0.,0.],[1.,0.,0.],[2.,0.,0.]],                  [[4.,0.,0.],[5.,0.,0.],[6.,0.,0.]]]).average()
[[ 2.  0.  0.]
 [ 3.  0.  0.]
 [ 4.  0.  0.]]
>>> print Coords([[[0.,0.,0.],[1.,0.,0.],[2.,0.,0.]],                  [[4.,0.,0.],[5.,0.,0.],[6.,0.,0.]]]).average(axis=1)
[[ 1.  0.  0.]
 [ 5.  0.  0.]]
>>> print Coords([[[0.,0.,0.],[1.,0.,0.],[2.,0.,0.]],                  [[4.,0.,0.],[5.,0.,0.],[6.,0.,0.]]]).average(wts=[0.5,0.25,0.25],axis=1)
[[ 0.75  0.    0.  ]
 [ 4.75  0.    0.  ]]
centroid()

Return the centroid of the Coords.

The centroid of a Coords is the point whose coordinates are the mean values of all points. The return value is a (3,) shaped Coords object.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).centroid()
[ 1.  1.  0.]

See also: center()

sizes()

Return the sizes of the Coords.

Return an array with the length of the bbox along the 3 axes.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).sizes()
[ 3.  3.  0.]
dsize()

Return an estimate of the global size of the Coords.

This estimate is the length of the diagonal of the bbox().

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).dsize()
4.24264
bsphere()

Return the diameter of the bounding sphere of the Coords.

The bounding sphere is the smallest sphere with center in the center() of the Coords, and such that no points of the Coords are lying outside the sphere.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).bsphere()
2.12132
inertia(mass=None)

Return inertia related quantities of the Coords.

This returns the center of gravity, the principal axes of inertia, the principal moments of inertia and the inertia tensor.

distanceFromPlane(p, n)

Return the distance of all points from the plane (p,n).

p is a point specified by 3 coordinates. n is the normal vector to a plane, specified by 3 components.

The return value is a float array with shape self.pshape() with the distance of each point to the plane through p and having normal n. Distance values are positive if the point is on the side of the plane indicated by the positive normal.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).distanceFromPlane([0.,0.,0.],[1.,0.,0.])
[[ 0.  3.  0.]]
distanceFromLine(p, n)

Return the distance of all points from the line (p,n).

p,n are (1,3) or (npts,3) arrays defining 1 or npts lines p is a point on the line specified by 3 coordinates. n is a vector specifying the direction of the line through p.

The return value is a [...] shaped array with the distance of each point to the line through p with direction n. All distance values are positive or zero.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).distanceFromLine([0.,0.,0.],[1.,0.,0.])
[[ 0.  0.  3.]]
distanceFromPoint(p)

Return the distance of all points from the point p.

p is a single point specified by 3 coordinates.

The return value is a [...] shaped array with the distance of each point to point p. All distance values are positive or zero. Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).distanceFromPoint([0.,0.,0.])
[[ 0.  3.  3.]]
closestToPoint(p)

Return the point closest to point p.

directionalSize(n, p=None, _points=False)

Return the extreme distances from the plane p,n.

The direction n can be specified by a 3 component vector or by a single integer 0..2 designing one of the coordinate axes.

p is any point in space. If not specified, it is taken as the center() of the Coords.

The return value is a tuple of two float values specifying the extreme distances from the plane p,n.

directionalExtremes(n, p=None)

Return extremal planes in the direction n.

n and p have the same meaning as in directionalSize.

The return value is a list of two points on the line (p,n), such that the planes with normal n through these points define the extremal planes of the Coords.

directionalWidth(n)

Return the width of a Coords in the given direction.

The direction can be specified by a 3 component vector or by a single integer 0..2 designating one of the coordinate axes.

The return value is the thickness of the object in the direction n.

test(dir=0, min=None, max=None, atol=0.0)

Flag points having coordinates between min and max.

This function is very convenient in clipping a Coords in a specified direction. It returns a 1D integer array flagging (with a value 1 or True) the elements having nodal coordinates in the required range. Use where(result) to get a list of element numbers passing the test. Or directly use clip() or cclip() to create the clipped Coords.

The test plane can be define in two ways depending on the value of dir. If dir == 0, 1 or 2, it specifies a global axis and min and max are the minimum and maximum values for the coordinates along that axis. Default is the 0 (or x) direction.

Else, dir should be compatible with a (3,) shaped array and specifies the direction of the normal on the planes. In this case, min and max are points and should also evaluate to (3,) shaped arrays.

One of the two clipping planes may be left unspecified.

fprint(fmt='%10.3e %10.3e %10.3e')

Formatted printing of a Coords object.

The supplied format should contain 3 formatting sequences for the three coordinates of a point.

set(f)

Set the coordinates from those in the given array.

scale(scale, dir=None, center=None, inplace=False)

Return a copy scaled with scale[i] in direction i.

The scale should be a list of 3 scaling factors for the 3 axis directions, or a single scaling factor. In the latter case, dir (a single axis number or a list) may be given to specify the direction(s) to scale. The default is to produce a homothetic scaling. The center of the scaling, if not specified, is the global origin. If a center is specified, the result is equivalent to:

self.translate(-center).scale(scale,dir).translate(center)

Example:

>>> print Coords([1.,1.,1.]).scale(2)
[ 2.  2.  2.]
>>> print Coords([1.,1.,1.]).scale([2,3,4])
[ 2.  3.  4.]
translate(dir, step=None, inplace=False)

Translate a Coords object.

Translates the Coords in the direction dir over a distance step * length(dir).

Parameters:

  • dir: specifies the direction and distance of the translation. It can be either
    • an axis number (0,1,2), specifying a unit vector in the direction of one of the coordinate axes.
    • a single translation vector,
    • an array of translation vectors, compatible with the Coords shape.
  • step: If specified, the translation vector specified by dir will be multiplied with this value. It is commonly used with unit dir vectors to set the translation distance.

Example:

>>> x = Coords([1.,1.,1.])
>>> print x.translate(1)
[ 1.  2.  1.]
>>> print x.translate(1,1.)
[ 1.  2.  1.]
>>> print x.translate([0,1,0])
[ 1.  2.  1.]
>>> print x.translate([0,2,0],0.5)
[ 1.  2.  1.]
centered()

Return a centered copy of the Coords.

Returns a Coords which is a translation thus that the center coincides with the origin. This is equivalent with:

self.trl(-self.center())
align(alignment='---')

Align the Coords along the global axes.

Alignment involves a translation such that the bounding box of the Coords object becomes aligned on the origin of the global axes. The requested alignment is determined by a string of three characters, one for each of the coordinate axes. The character determines how the structure is aligned in the corresponding direction:

  • ‘-‘: aligned on the minimal value of the bounding box,
  • ‘+’: aligned on the maximal value of the bounding box,
  • ‘0’: aligned on the middle value of the bounding box.

Any other value will make the alignment in that direction unchanged.

The default alignment string ‘—’ results in a translation which puts all the points in the octant with all positive coordinate values. A string ‘000’ will center the object around the origin, just like the (slightly faster) centered() method, which is .

rotate(angle, axis=2, around=None)

Return a copy rotated over angle around axis.

The angle is specified in degrees. The axis is either one of (0,1,2) designating the global axes, or a vector specifying an axis through the origin. If no axis is specified, rotation is around the 2(z)-axis. This is convenient for working on 2D-structures.

As a convenience, the user may also specify a 3x3 rotation matrix, in which case the function rotate(mat) is equivalent to affine(mat).

All rotations are performed around the point [0,0,0], unless a rotation origin is specified in the argument ‘around’.

shear(dir, dir1, skew, inplace=False)

Return a copy skewed in the direction dir of plane (dir,dir1).

The coordinate dir is replaced with (dir + skew * dir1).

reflect(dir=0, pos=0.0, inplace=False)

Reflect the coordinates in direction dir against plane at pos.

Parameters:

  • dir: int: direction of the reflection (default 0)
  • pos: float: offset of the mirror plane from origin (default 0.0)
  • inplace: boolean: change the coordinates inplace (default False)
affine(mat, vec=None)

Returns a general affine transform of the Coords object.

mat: a 3x3 float matrix

vec: a length 3 list or array of floats

The returned object has coordinates given by self * mat + vec.

cylindrical(dir=[0, 1, 2], scale=[1.0, 1.0, 1.0], angle_spec=0.017453292519943295)

Converts from cylindrical to cartesian after scaling.

dir specifies which coordinates are interpreted as resp. distance(r), angle(theta) and height(z). Default order is [r,theta,z]. scale will scale the coordinate values prior to the transformation. (scale is given in order r,theta,z). The resulting angle is interpreted in degrees.

toCylindrical(dir=[0, 1, 2], angle_spec=0.017453292519943295)

Converts from cartesian to cylindrical coordinates.

dir specifies which coordinates axes are parallel to respectively the cylindrical axes distance(r), angle(theta) and height(z). Default order is [x,y,z]. The angle value is given in degrees.

spherical(dir=[0, 1, 2], scale=[1.0, 1.0, 1.0], angle_spec=0.017453292519943295, colat=False)

Converts from spherical to cartesian after scaling.

  • dir specifies which coordinates are interpreted as resp. longitude(theta), latitude(phi) and distance(r).
  • scale will scale the coordinate values prior to the transformation.

Angles are interpreted in degrees. Latitude, i.e. the elevation angle, is measured from equator in direction of north pole(90). South pole is -90.

If colat=True, the third coordinate is the colatitude (90-lat) instead.

superSpherical(n=1.0, e=1.0, k=0.0, dir=[0, 1, 2], scale=[1.0, 1.0, 1.0], angle_spec=0.017453292519943295, colat=False)

Performs a superspherical transformation.

superSpherical is much like spherical, but adds some extra parameters to enable the creation of virtually any surface.

Just like with spherical(), the input coordinates are interpreted as the longitude, latitude and distance in a spherical coordinate system.

dir specifies which coordinates are interpreted as resp. longitude(theta), latitude(phi) and distance(r). Angles are then interpreted in degrees. Latitude, i.e. the elevation angle, is measured from equator in direction of north pole(90). South pole is -90. If colat=True, the third coordinate is the colatitude (90-lat) instead.

scale will scale the coordinate values prior to the transformation.

The n and e parameters define exponential transformations of the north_south (latitude), resp. the east_west (longitude) coordinates. Default values of 1 result in a circle.

k adds ‘eggness’ to the shape: a difference between the northern and southern hemisphere. Values > 0 enlarge the southern hemishpere and shrink the northern.

toSpherical(dir=[0, 1, 2], angle_spec=0.017453292519943295)

Converts from cartesian to spherical coordinates.

dir specifies which coordinates axes are parallel to respectively the spherical axes distance(r), longitude(theta) and latitude(phi). Latitude is the elevation angle measured from equator in direction of north pole(90). South pole is -90. Default order is [0,1,2], thus the equator plane is the (x,y)-plane.

The returned angle values are given in degrees.

bump1(dir, a, func, dist)

Return a Coords with a one-dimensional bump.

  • dir specifies the axis of the modified coordinates;
  • a is the point that forces the bumping;
  • dist specifies the direction in which the distance is measured;
  • func is a function that calculates the bump intensity from distance and should be such that func(0) != 0.
bump2(dir, a, func)

Return a Coords with a two-dimensional bump.

dir specifies the axis of the modified coordinates; a is the point that forces the bumping; func is a function that calculates the bump intensity from distance !! func(0) should be different from 0.

bump(dir, a, func, dist=None)

Return a Coords with a bump.

A bump is a modification of a set of coordinates by a non-matching point. It can produce various effects, but one of the most common uses is to force a surface to be indented by some point.

dir specifies the axis of the modified coordinates; a is the point that forces the bumping; func is a function that calculates the bump intensity from distance (!! func(0) should be different from 0) dist is the direction in which the distance is measured : this can be one of the axes, or a list of one or more axes. If only 1 axis is specified, the effect is like function bump1 If 2 axes are specified, the effect is like bump2 This function can take 3 axes however. Default value is the set of 3 axes minus the direction of modification. This function is then equivalent to bump2.

flare(xf, f, dir=[0, 2], end=0, exp=1.0)

Create a flare at the end of a Coords block.

The flare extends over a distance xf at the start (end=0) or end (end=1) in direction dir[0] of the coords block, and has a maximum amplitude of f in the dir[1] direction.

map(func)

Return a Coords mapped by a 3-D function.

This is one of the versatile mapping functions. func is a numerical function which takes three arguments and produces a list of three output values. The coordinates [x,y,z] will be replaced by func(x,y,z). The function must be applicable to arrays, so it should only include numerical operations and functions understood by the numpy module. This method is one of several mapping methods. See also map1 and mapd.

Example:

>>> print Coords([[1.,1.,1.]]).map(lambda x,y,z: [2*x,3*y,4*z])
[[ 2.  3.  4.]]
map1(dir, func, x=None)

Return a Coords where coordinate i is mapped by a 1-D function.

func is a numerical function which takes one argument and produces one result. The coordinate dir will be replaced by func(coord[x]). If no x is specified, x is taken equal to dir. The function must be applicable on arrays, so it should only include numerical operations and functions understood by the numpy module. This method is one of several mapping methods. See also map and mapd.

mapd(dir, func, point, dist=None)

Maps one coordinate by a function of the distance to a point.

func a numerical function which takes one argument and produces one result. The coordinate dir will be replaced by func(d), where d is calculated as the distance to point. The function must be applicable on arrays, so it should only include numerical operations and functions understood by the numpy module. By default, the distance d is calculated in 3-D, but one can specify a limited set of axes to calculate a 2-D or 1-D distance. This method is one of several mapping methods. See also map3() and map1().

Example:

E.mapd(2,lambda d:sqrt(10**2-d**2),f.center(),[0,1])

maps E on a sphere with radius 10.

egg(k)

Maps the coordinates to an egg-shape

replace(i, j, other=None)

Replace the coordinates along the axes i by those along j.

i and j are lists of axis numbers or single axis numbers. replace ([0,1,2],[1,2,0]) will roll the axes by 1. replace ([0,1],[1,0]) will swap axes 0 and 1. An optionally third argument may specify another Coords object to take the coordinates from. It should have the same dimensions.

swapAxes(i, j)

Swap coordinate axes i and j.

Beware! This is different from numpy’s swapaxes() method !

rollAxes(n=1)

Roll the axes over the given amount.

Default is 1, thus axis 0 becomes the new 1 axis, 1 becomes 2 and 2 becomes 0.

projectOnPlane(n=2, P=[0.0, 0.0, 0.0])

Project a Coords on a plane (or planes).

Parameters:

  • n: the normal direction to the plane. It can be specified either by a list of three floats, or by a single integer (0, 1 or 2) to use one of the global axes.
  • P: a point on the plane, by default the global origin. If an int, the plane is the coordinate plane perpendicular to the
..note: For planes parallel to a coordinate plane, it is far more
efficient to specify the normal by an axis number than by a three component vector.

Returns: a Coords with same shape as original, with all the points projected on the specified plane(s).

projectOnSphere(radius=1.0, center=[0.0, 0.0, 0.0])

Project Coords on a sphere.

The default sphere is a unit sphere at the origin. The center of the sphere should not be part of the Coords.

projectOnCylinder(radius=1.0, dir=0, center=[0.0, 0.0, 0.0])

Project Coords on a cylinder with axis parallel to a global axis.

The default cylinder has its axis along the x-axis and a unit radius. No points of the Coords should belong to the axis..

projectOnSurface(S, n, ignore_errors=False)

Project the Coords on a triangulated surface.

The points of the Coords are projected in the direction of the vector n onto the surface S.

Parameters:

  • S: TriSurface: any triangulated surface
  • n: int or vector: specifies the direction of the projection
  • ignore_errors: if True, projective lines not cutting the surface will result in NaN values. The default is to raise an error.

If successful, a Coords with the same structure as the input is returned.

isopar(eltype, coords, oldcoords)

Perform an isoparametric transformation on a Coords.

This is a convenience method to transform a Coords object through an isoparametric transformation. It is equivalent to:

Isopar(eltype,coords,oldcoords).transform(self)

See plugins.isopar for more details.

transformCS(currentCS, initialCS=None)

Perform a CoordinateSystem transformation on the Coords.

This method transforms the Coords object by the transformation that turns the initial CoordinateSystem into the currentCoordinateSystem.

currentCS and initialCS are CoordinateSystem or (4,3) shaped Coords instances. If initialCS is None, the global (x,y,z) axes are used.

E.g. the default initialCS and currentCS equal to:

 0.  1.  0.
-1.  0.  0.
 0.  0.  1.
 0.  0.  0.

result in a rotation of 90 degrees around the z-axis.

This is a convenience function equivalent to:

self.isopar('tet4',currentCS,initialCS)
addNoise(rsize=0.10000000000000001, asize=0.0)

Add random noise to a Coords.

A random amount is added to eacho individual coordinate in the Coords. The difference of any coordinate from its original value will not be maximally asize + rsize * self.sizes().max(). The default is to set it to 0.1 times the geometrical size of the structure.

replicate(n, dir=0, step=None)

Replicate a Coords n times with fixed step in any direction.

Returns a Coords object with shape (n,) + self.shape, thus having an extra first axis. Each component along the axis 0 is equal to the previous component translated over (dir,step), where dir and step are interpreted just like in the translate() method. The first component along the axis 0 is identical to the original Coords.

split()

Split the coordinate array in blocks along first axis.

The result is a sequence of arrays with shape self.shape[1:]. Raises an error if self.ndim < 2.

fuse(nodesperbox=1, shift=0.5, rtol=1.0000000000000001e-05, atol=1.0000000000000001e-05, repeat=True)

Find (almost) identical nodes and return a compressed set.

This method finds the points that are very close and replaces them with a single point. The return value is a tuple of two arrays:

  • the unique points as a Coords object with shape (npoints,3)
  • an integer (nnod) array holding an index in the unique coordinates array for each of the original nodes. This index will have the same shape as the pshape() of the coords array.

The procedure works by first dividing the 3D space in a number of equally sized boxes, with a mean population of nodesperbox. The boxes are numbered in the 3 directions and a unique integer scalar is computed, that is then used to sort the nodes. Then only nodes inside the same box are compared on almost equal coordinates, using the numpy allclose() function. Two coordinates are considered close if they are within a relative tolerance rtol or absolute tolerance atol. See numpy for detail. The default atol is set larger than in numpy, because pyformex typically runs with single precision. Close nodes are replaced by a single one.

Running the procedure once does not guarantee to find all close nodes: two close nodes might be in adjacent boxes. The performance hit for testing adjacent boxes is rather high, and the probability of separating two close nodes with the computed box limits is very small. Therefore, the most sensible way is to run the procedure twice, with a different shift value (they should differ more than the tolerance). Specifying repeat=True will automatically do this.

match(coords, **kargs)

Match points form another Coords object.

This method finds the points from coords that coincide with (or are very close to) points of self.

Parameters:

  • coords: a Coords object
  • **kargs: keyword arguments that you want to pass to the fuse() method.

This method works by concatenating the serialized point sets of both Coords and then fusing them.

Returns:

  • matches: an Int array with shape (nmatches,2)
  • coords: a Coords with the fused coordinate set
  • index: an index with the position of each of the serialized points of the concatenation in the fused coordinate set. To find the index of the points of the orginal coordinate sets, split this index at the position self.npoints() and reshape the resulting parts to self.pshape(), resp. coords.pshape().
append(coords)

Append coords to a Coords object.

The appended coords should have matching dimensions in all but the first axis.

Returns the concatenated Coords object, without changing the current.

This is comparable to numpy.append(), but the result is a Coords object, the default axis is the first one instead of the last, and it is a method rather than a function.

classmethod concatenate(clas, L, axis=0)

Concatenate a list of Coords object.

All Coords object in the list L should have the same shape except for the length of the specified axis. This function is equivalent to the numpy concatenate, but makes sure the result is a Coords object,and the default axis is the first one instead of the last.

classmethod fromstring(clas, fil, sep=' ', ndim=3, count=-1)

Create a Coords object with data from a string.

This convenience function uses the numpy.fromstring() function to read coordinates from a string.

fil: a string containing a single sequence of float numbers separated by whitespace and a possible separator string.

sep: the separator used between the coordinates. If not a space, all extra whitespace is ignored.

ndim: number of coordinates per point. Should be 1, 2 or 3 (default). If 1, resp. 2, the coordinate string only holds x, resp. x,y values.

count: total number of coordinates to read. This should be a multiple of 3. The default is to read all the coordinates in the string. count can be used to force an error condition if the string does not contain the expected number of values.

The return value is Coords object.

classmethod fromfile(clas, fil, **kargs)

Read a Coords from file.

This convenience function uses the numpy fromfile function to read the coordinates from file. You just have to make sure that the coordinates are read in order (X,Y,Z) for subsequent points, and that the total number of coordinates read is a multiple of 3.

interpolate(X, div)

Create interpolations between two Coords.

Parameters:

  • X: a Coords with same shape as self.
  • div: a list of floating point values, or an int. If an int is specified, a list with (div+1) values for div is created by dividing the interval [0..1] into div equal distances.

Returns:

A Coords with an extra (first) axis, containing the concatenation of the interpolations of self and X at all values in div. Its shape is (n,) + self.shape, where n is the number of values in div.

An interpolation of F and G at value v is a Coords H where each coordinate Hijk is obtained from: Fijk = Fijk + v * (Gijk-Fijk). Thus, X.interpolate(Y,[0.,0.5,1.0]) will contain all points of X and Y and all points with mean coordinates between those of X and Y.

F.interpolate(G,n) is equivalent with F.interpolate(G,arange(0,n+1)/float(n))

rot(angle, axis=2, around=None)

Return a copy rotated over angle around axis.

The angle is specified in degrees. The axis is either one of (0,1,2) designating the global axes, or a vector specifying an axis through the origin. If no axis is specified, rotation is around the 2(z)-axis. This is convenient for working on 2D-structures.

As a convenience, the user may also specify a 3x3 rotation matrix, in which case the function rotate(mat) is equivalent to affine(mat).

All rotations are performed around the point [0,0,0], unless a rotation origin is specified in the argument ‘around’.

trl(dir, step=None, inplace=False)

Translate a Coords object.

Translates the Coords in the direction dir over a distance step * length(dir).

Parameters:

  • dir: specifies the direction and distance of the translation. It can be either
    • an axis number (0,1,2), specifying a unit vector in the direction of one of the coordinate axes.
    • a single translation vector,
    • an array of translation vectors, compatible with the Coords shape.
  • step: If specified, the translation vector specified by dir will be multiplied with this value. It is commonly used with unit dir vectors to set the translation distance.

Example:

>>> x = Coords([1.,1.,1.])
>>> print x.translate(1)
[ 1.  2.  1.]
>>> print x.translate(1,1.)
[ 1.  2.  1.]
>>> print x.translate([0,1,0])
[ 1.  2.  1.]
>>> print x.translate([0,2,0],0.5)
[ 1.  2.  1.]
rep(n, dir=0, step=None)

Replicate a Coords n times with fixed step in any direction.

Returns a Coords object with shape (n,) + self.shape, thus having an extra first axis. Each component along the axis 0 is equal to the previous component translated over (dir,step), where dir and step are interpreted just like in the translate() method. The first component along the axis 0 is identical to the original Coords.

class coords.BoundVectors

A collection of bound vectors in a 3D Cartesian space.

Parameters:

  • coords: a (...,2,3) shaped array of bound vectors defined by their initial and terminal points.
  • origins,`vectors`: (...,3) shaped arrays defining the initial points and vectors from initial to terminal points.

The default constructs a unit vector along the global x-axis.

origins()

Return the initial points of the BoundVectors.

heads()

Return the endpoints of the BoundVectors.

vectors()

Return the vectors of the BoundVectors.

points()

Returns the Coords object as a simple set of points.

This reshapes the array to a 2-dimensional array, flattening the structure of the points.

pshape()

Returns the shape of the Coords object.

This is the shape of the NumPy array with the last axis removed. The full shape of the Coords array can be obtained from its shape attribute.

ncoords()

Return the total number of points.

npoints()

Return the total number of points.

x()

Return the X-coordinates of all points.

Returns an array with all the X-coordinates in the Coords. The returned array has the same shape as the Coords array along its first ndim-1 axes. This is equivalent with

self[...,0]
y()

Return the Y-coordinates of all points.

Returns an array with all the Y-coordinates in the Coords. The returned array has the same shape as the Coords array along its first ndim-1 axes. This is equivalent with

self[...,1]
z()

Return the Z-coordinates of all points.

Returns an array with all the Z-coordinates in the Coords. The returned array has the same shape as the Coords array along its first ndim-1 axes. This is equivalent with

self[...,0]
bbox()

Return the bounding box of a set of points.

The bounding box is the smallest rectangular volume in the global coordinates, such that no point of the Coords are outside that volume.

Returns:

A Coords object with shape(2,3): the first point contains the minimal coordinates, the second has the maximal ones.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).bbox()
[[ 0.  0.  0.]
 [ 3.  3.  0.]]
center()

Return the center of the Coords.

The center of a Coords is the center of its bbox(). The return value is a (3,) shaped Coords object.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).center()
[ 1.5  1.5  0. ]

See also: centroid()

average(wts=None, axis=0)

Return a (weighted) average of the Coords.

The average of a Coords is a Coords with one axis less than the original, obtained by averaging all the points along that axis. The weights array can either be 1-D (in which case its length must be the size along the given axis) or of the same shape as a. Weights can be specified as a 1-D array with the length of that axis, or as an array with the same shape as the Coords. The sum of the weights (along the specified axis if not 1-D) will generally be equal to 1.0. If wts=None, then all points are assumed to have a weight equal to one divided by the length of the specified axis.

Example:

>>> print Coords([[[0.,0.,0.],[1.,0.,0.],[2.,0.,0.]],                  [[4.,0.,0.],[5.,0.,0.],[6.,0.,0.]]]).average()
[[ 2.  0.  0.]
 [ 3.  0.  0.]
 [ 4.  0.  0.]]
>>> print Coords([[[0.,0.,0.],[1.,0.,0.],[2.,0.,0.]],                  [[4.,0.,0.],[5.,0.,0.],[6.,0.,0.]]]).average(axis=1)
[[ 1.  0.  0.]
 [ 5.  0.  0.]]
>>> print Coords([[[0.,0.,0.],[1.,0.,0.],[2.,0.,0.]],                  [[4.,0.,0.],[5.,0.,0.],[6.,0.,0.]]]).average(wts=[0.5,0.25,0.25],axis=1)
[[ 0.75  0.    0.  ]
 [ 4.75  0.    0.  ]]
centroid()

Return the centroid of the Coords.

The centroid of a Coords is the point whose coordinates are the mean values of all points. The return value is a (3,) shaped Coords object.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).centroid()
[ 1.  1.  0.]

See also: center()

sizes()

Return the sizes of the Coords.

Return an array with the length of the bbox along the 3 axes.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).sizes()
[ 3.  3.  0.]
dsize()

Return an estimate of the global size of the Coords.

This estimate is the length of the diagonal of the bbox().

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).dsize()
4.24264
bsphere()

Return the diameter of the bounding sphere of the Coords.

The bounding sphere is the smallest sphere with center in the center() of the Coords, and such that no points of the Coords are lying outside the sphere.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).bsphere()
2.12132
inertia(mass=None)

Return inertia related quantities of the Coords.

This returns the center of gravity, the principal axes of inertia, the principal moments of inertia and the inertia tensor.

distanceFromPlane(p, n)

Return the distance of all points from the plane (p,n).

p is a point specified by 3 coordinates. n is the normal vector to a plane, specified by 3 components.

The return value is a float array with shape self.pshape() with the distance of each point to the plane through p and having normal n. Distance values are positive if the point is on the side of the plane indicated by the positive normal.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).distanceFromPlane([0.,0.,0.],[1.,0.,0.])
[[ 0.  3.  0.]]
distanceFromLine(p, n)

Return the distance of all points from the line (p,n).

p,n are (1,3) or (npts,3) arrays defining 1 or npts lines p is a point on the line specified by 3 coordinates. n is a vector specifying the direction of the line through p.

The return value is a [...] shaped array with the distance of each point to the line through p with direction n. All distance values are positive or zero.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).distanceFromLine([0.,0.,0.],[1.,0.,0.])
[[ 0.  0.  3.]]
distanceFromPoint(p)

Return the distance of all points from the point p.

p is a single point specified by 3 coordinates.

The return value is a [...] shaped array with the distance of each point to point p. All distance values are positive or zero. Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).distanceFromPoint([0.,0.,0.])
[[ 0.  3.  3.]]
closestToPoint(p)

Return the point closest to point p.

directionalSize(n, p=None, _points=False)

Return the extreme distances from the plane p,n.

The direction n can be specified by a 3 component vector or by a single integer 0..2 designing one of the coordinate axes.

p is any point in space. If not specified, it is taken as the center() of the Coords.

The return value is a tuple of two float values specifying the extreme distances from the plane p,n.

directionalExtremes(n, p=None)

Return extremal planes in the direction n.

n and p have the same meaning as in directionalSize.

The return value is a list of two points on the line (p,n), such that the planes with normal n through these points define the extremal planes of the Coords.

directionalWidth(n)

Return the width of a Coords in the given direction.

The direction can be specified by a 3 component vector or by a single integer 0..2 designating one of the coordinate axes.

The return value is the thickness of the object in the direction n.

test(dir=0, min=None, max=None, atol=0.0)

Flag points having coordinates between min and max.

This function is very convenient in clipping a Coords in a specified direction. It returns a 1D integer array flagging (with a value 1 or True) the elements having nodal coordinates in the required range. Use where(result) to get a list of element numbers passing the test. Or directly use clip() or cclip() to create the clipped Coords.

The test plane can be define in two ways depending on the value of dir. If dir == 0, 1 or 2, it specifies a global axis and min and max are the minimum and maximum values for the coordinates along that axis. Default is the 0 (or x) direction.

Else, dir should be compatible with a (3,) shaped array and specifies the direction of the normal on the planes. In this case, min and max are points and should also evaluate to (3,) shaped arrays.

One of the two clipping planes may be left unspecified.

fprint(fmt='%10.3e %10.3e %10.3e')

Formatted printing of a Coords object.

The supplied format should contain 3 formatting sequences for the three coordinates of a point.

set(f)

Set the coordinates from those in the given array.

scale(scale, dir=None, center=None, inplace=False)

Return a copy scaled with scale[i] in direction i.

The scale should be a list of 3 scaling factors for the 3 axis directions, or a single scaling factor. In the latter case, dir (a single axis number or a list) may be given to specify the direction(s) to scale. The default is to produce a homothetic scaling. The center of the scaling, if not specified, is the global origin. If a center is specified, the result is equivalent to:

self.translate(-center).scale(scale,dir).translate(center)

Example:

>>> print Coords([1.,1.,1.]).scale(2)
[ 2.  2.  2.]
>>> print Coords([1.,1.,1.]).scale([2,3,4])
[ 2.  3.  4.]
translate(dir, step=None, inplace=False)

Translate a Coords object.

Translates the Coords in the direction dir over a distance step * length(dir).

Parameters:

  • dir: specifies the direction and distance of the translation. It can be either
    • an axis number (0,1,2), specifying a unit vector in the direction of one of the coordinate axes.
    • a single translation vector,
    • an array of translation vectors, compatible with the Coords shape.
  • step: If specified, the translation vector specified by dir will be multiplied with this value. It is commonly used with unit dir vectors to set the translation distance.

Example:

>>> x = Coords([1.,1.,1.])
>>> print x.translate(1)
[ 1.  2.  1.]
>>> print x.translate(1,1.)
[ 1.  2.  1.]
>>> print x.translate([0,1,0])
[ 1.  2.  1.]
>>> print x.translate([0,2,0],0.5)
[ 1.  2.  1.]
trl(dir, step=None, inplace=False)

Translate a Coords object.

Translates the Coords in the direction dir over a distance step * length(dir).

Parameters:

  • dir: specifies the direction and distance of the translation. It can be either
    • an axis number (0,1,2), specifying a unit vector in the direction of one of the coordinate axes.
    • a single translation vector,
    • an array of translation vectors, compatible with the Coords shape.
  • step: If specified, the translation vector specified by dir will be multiplied with this value. It is commonly used with unit dir vectors to set the translation distance.

Example:

>>> x = Coords([1.,1.,1.])
>>> print x.translate(1)
[ 1.  2.  1.]
>>> print x.translate(1,1.)
[ 1.  2.  1.]
>>> print x.translate([0,1,0])
[ 1.  2.  1.]
>>> print x.translate([0,2,0],0.5)
[ 1.  2.  1.]
centered()

Return a centered copy of the Coords.

Returns a Coords which is a translation thus that the center coincides with the origin. This is equivalent with:

self.trl(-self.center())
align(alignment='---')

Align the Coords along the global axes.

Alignment involves a translation such that the bounding box of the Coords object becomes aligned on the origin of the global axes. The requested alignment is determined by a string of three characters, one for each of the coordinate axes. The character determines how the structure is aligned in the corresponding direction:

  • ‘-‘: aligned on the minimal value of the bounding box,
  • ‘+’: aligned on the maximal value of the bounding box,
  • ‘0’: aligned on the middle value of the bounding box.

Any other value will make the alignment in that direction unchanged.

The default alignment string ‘—’ results in a translation which puts all the points in the octant with all positive coordinate values. A string ‘000’ will center the object around the origin, just like the (slightly faster) centered() method, which is .

rot(angle, axis=2, around=None)

Return a copy rotated over angle around axis.

The angle is specified in degrees. The axis is either one of (0,1,2) designating the global axes, or a vector specifying an axis through the origin. If no axis is specified, rotation is around the 2(z)-axis. This is convenient for working on 2D-structures.

As a convenience, the user may also specify a 3x3 rotation matrix, in which case the function rotate(mat) is equivalent to affine(mat).

All rotations are performed around the point [0,0,0], unless a rotation origin is specified in the argument ‘around’.

rotate(angle, axis=2, around=None)

Return a copy rotated over angle around axis.

The angle is specified in degrees. The axis is either one of (0,1,2) designating the global axes, or a vector specifying an axis through the origin. If no axis is specified, rotation is around the 2(z)-axis. This is convenient for working on 2D-structures.

As a convenience, the user may also specify a 3x3 rotation matrix, in which case the function rotate(mat) is equivalent to affine(mat).

All rotations are performed around the point [0,0,0], unless a rotation origin is specified in the argument ‘around’.

shear(dir, dir1, skew, inplace=False)

Return a copy skewed in the direction dir of plane (dir,dir1).

The coordinate dir is replaced with (dir + skew * dir1).

reflect(dir=0, pos=0.0, inplace=False)

Reflect the coordinates in direction dir against plane at pos.

Parameters:

  • dir: int: direction of the reflection (default 0)
  • pos: float: offset of the mirror plane from origin (default 0.0)
  • inplace: boolean: change the coordinates inplace (default False)
affine(mat, vec=None)

Returns a general affine transform of the Coords object.

mat: a 3x3 float matrix

vec: a length 3 list or array of floats

The returned object has coordinates given by self * mat + vec.

cylindrical(dir=[0, 1, 2], scale=[1.0, 1.0, 1.0], angle_spec=0.017453292519943295)

Converts from cylindrical to cartesian after scaling.

dir specifies which coordinates are interpreted as resp. distance(r), angle(theta) and height(z). Default order is [r,theta,z]. scale will scale the coordinate values prior to the transformation. (scale is given in order r,theta,z). The resulting angle is interpreted in degrees.

toCylindrical(dir=[0, 1, 2], angle_spec=0.017453292519943295)

Converts from cartesian to cylindrical coordinates.

dir specifies which coordinates axes are parallel to respectively the cylindrical axes distance(r), angle(theta) and height(z). Default order is [x,y,z]. The angle value is given in degrees.

spherical(dir=[0, 1, 2], scale=[1.0, 1.0, 1.0], angle_spec=0.017453292519943295, colat=False)

Converts from spherical to cartesian after scaling.

  • dir specifies which coordinates are interpreted as resp. longitude(theta), latitude(phi) and distance(r).
  • scale will scale the coordinate values prior to the transformation.

Angles are interpreted in degrees. Latitude, i.e. the elevation angle, is measured from equator in direction of north pole(90). South pole is -90.

If colat=True, the third coordinate is the colatitude (90-lat) instead.

superSpherical(n=1.0, e=1.0, k=0.0, dir=[0, 1, 2], scale=[1.0, 1.0, 1.0], angle_spec=0.017453292519943295, colat=False)

Performs a superspherical transformation.

superSpherical is much like spherical, but adds some extra parameters to enable the creation of virtually any surface.

Just like with spherical(), the input coordinates are interpreted as the longitude, latitude and distance in a spherical coordinate system.

dir specifies which coordinates are interpreted as resp. longitude(theta), latitude(phi) and distance(r). Angles are then interpreted in degrees. Latitude, i.e. the elevation angle, is measured from equator in direction of north pole(90). South pole is -90. If colat=True, the third coordinate is the colatitude (90-lat) instead.

scale will scale the coordinate values prior to the transformation.

The n and e parameters define exponential transformations of the north_south (latitude), resp. the east_west (longitude) coordinates. Default values of 1 result in a circle.

k adds ‘eggness’ to the shape: a difference between the northern and southern hemisphere. Values > 0 enlarge the southern hemishpere and shrink the northern.

toSpherical(dir=[0, 1, 2], angle_spec=0.017453292519943295)

Converts from cartesian to spherical coordinates.

dir specifies which coordinates axes are parallel to respectively the spherical axes distance(r), longitude(theta) and latitude(phi). Latitude is the elevation angle measured from equator in direction of north pole(90). South pole is -90. Default order is [0,1,2], thus the equator plane is the (x,y)-plane.

The returned angle values are given in degrees.

bump1(dir, a, func, dist)

Return a Coords with a one-dimensional bump.

  • dir specifies the axis of the modified coordinates;
  • a is the point that forces the bumping;
  • dist specifies the direction in which the distance is measured;
  • func is a function that calculates the bump intensity from distance and should be such that func(0) != 0.
bump2(dir, a, func)

Return a Coords with a two-dimensional bump.

dir specifies the axis of the modified coordinates; a is the point that forces the bumping; func is a function that calculates the bump intensity from distance !! func(0) should be different from 0.

bump(dir, a, func, dist=None)

Return a Coords with a bump.

A bump is a modification of a set of coordinates by a non-matching point. It can produce various effects, but one of the most common uses is to force a surface to be indented by some point.

dir specifies the axis of the modified coordinates; a is the point that forces the bumping; func is a function that calculates the bump intensity from distance (!! func(0) should be different from 0) dist is the direction in which the distance is measured : this can be one of the axes, or a list of one or more axes. If only 1 axis is specified, the effect is like function bump1 If 2 axes are specified, the effect is like bump2 This function can take 3 axes however. Default value is the set of 3 axes minus the direction of modification. This function is then equivalent to bump2.

flare(xf, f, dir=[0, 2], end=0, exp=1.0)

Create a flare at the end of a Coords block.

The flare extends over a distance xf at the start (end=0) or end (end=1) in direction dir[0] of the coords block, and has a maximum amplitude of f in the dir[1] direction.

map(func)

Return a Coords mapped by a 3-D function.

This is one of the versatile mapping functions. func is a numerical function which takes three arguments and produces a list of three output values. The coordinates [x,y,z] will be replaced by func(x,y,z). The function must be applicable to arrays, so it should only include numerical operations and functions understood by the numpy module. This method is one of several mapping methods. See also map1 and mapd.

Example:

>>> print Coords([[1.,1.,1.]]).map(lambda x,y,z: [2*x,3*y,4*z])
[[ 2.  3.  4.]]
map1(dir, func, x=None)

Return a Coords where coordinate i is mapped by a 1-D function.

func is a numerical function which takes one argument and produces one result. The coordinate dir will be replaced by func(coord[x]). If no x is specified, x is taken equal to dir. The function must be applicable on arrays, so it should only include numerical operations and functions understood by the numpy module. This method is one of several mapping methods. See also map and mapd.

mapd(dir, func, point, dist=None)

Maps one coordinate by a function of the distance to a point.

func a numerical function which takes one argument and produces one result. The coordinate dir will be replaced by func(d), where d is calculated as the distance to point. The function must be applicable on arrays, so it should only include numerical operations and functions understood by the numpy module. By default, the distance d is calculated in 3-D, but one can specify a limited set of axes to calculate a 2-D or 1-D distance. This method is one of several mapping methods. See also map3() and map1().

Example:

E.mapd(2,lambda d:sqrt(10**2-d**2),f.center(),[0,1])

maps E on a sphere with radius 10.

egg(k)

Maps the coordinates to an egg-shape

replace(i, j, other=None)

Replace the coordinates along the axes i by those along j.

i and j are lists of axis numbers or single axis numbers. replace ([0,1,2],[1,2,0]) will roll the axes by 1. replace ([0,1],[1,0]) will swap axes 0 and 1. An optionally third argument may specify another Coords object to take the coordinates from. It should have the same dimensions.

swapAxes(i, j)

Swap coordinate axes i and j.

Beware! This is different from numpy’s swapaxes() method !

rollAxes(n=1)

Roll the axes over the given amount.

Default is 1, thus axis 0 becomes the new 1 axis, 1 becomes 2 and 2 becomes 0.

projectOnPlane(n=2, P=[0.0, 0.0, 0.0])

Project a Coords on a plane (or planes).

Parameters:

  • n: the normal direction to the plane. It can be specified either by a list of three floats, or by a single integer (0, 1 or 2) to use one of the global axes.
  • P: a point on the plane, by default the global origin. If an int, the plane is the coordinate plane perpendicular to the
..note: For planes parallel to a coordinate plane, it is far more
efficient to specify the normal by an axis number than by a three component vector.

Returns: a Coords with same shape as original, with all the points projected on the specified plane(s).

projectOnSphere(radius=1.0, center=[0.0, 0.0, 0.0])

Project Coords on a sphere.

The default sphere is a unit sphere at the origin. The center of the sphere should not be part of the Coords.

projectOnCylinder(radius=1.0, dir=0, center=[0.0, 0.0, 0.0])

Project Coords on a cylinder with axis parallel to a global axis.

The default cylinder has its axis along the x-axis and a unit radius. No points of the Coords should belong to the axis..

projectOnSurface(S, n, ignore_errors=False)

Project the Coords on a triangulated surface.

The points of the Coords are projected in the direction of the vector n onto the surface S.

Parameters:

  • S: TriSurface: any triangulated surface
  • n: int or vector: specifies the direction of the projection
  • ignore_errors: if True, projective lines not cutting the surface will result in NaN values. The default is to raise an error.

If successful, a Coords with the same structure as the input is returned.

isopar(eltype, coords, oldcoords)

Perform an isoparametric transformation on a Coords.

This is a convenience method to transform a Coords object through an isoparametric transformation. It is equivalent to:

Isopar(eltype,coords,oldcoords).transform(self)

See plugins.isopar for more details.

transformCS(currentCS, initialCS=None)

Perform a CoordinateSystem transformation on the Coords.

This method transforms the Coords object by the transformation that turns the initial CoordinateSystem into the currentCoordinateSystem.

currentCS and initialCS are CoordinateSystem or (4,3) shaped Coords instances. If initialCS is None, the global (x,y,z) axes are used.

E.g. the default initialCS and currentCS equal to:

 0.  1.  0.
-1.  0.  0.
 0.  0.  1.
 0.  0.  0.

result in a rotation of 90 degrees around the z-axis.

This is a convenience function equivalent to:

self.isopar('tet4',currentCS,initialCS)
addNoise(rsize=0.10000000000000001, asize=0.0)

Add random noise to a Coords.

A random amount is added to eacho individual coordinate in the Coords. The difference of any coordinate from its original value will not be maximally asize + rsize * self.sizes().max(). The default is to set it to 0.1 times the geometrical size of the structure.

rep(n, dir=0, step=None)

Replicate a Coords n times with fixed step in any direction.

Returns a Coords object with shape (n,) + self.shape, thus having an extra first axis. Each component along the axis 0 is equal to the previous component translated over (dir,step), where dir and step are interpreted just like in the translate() method. The first component along the axis 0 is identical to the original Coords.

replicate(n, dir=0, step=None)

Replicate a Coords n times with fixed step in any direction.

Returns a Coords object with shape (n,) + self.shape, thus having an extra first axis. Each component along the axis 0 is equal to the previous component translated over (dir,step), where dir and step are interpreted just like in the translate() method. The first component along the axis 0 is identical to the original Coords.

split()

Split the coordinate array in blocks along first axis.

The result is a sequence of arrays with shape self.shape[1:]. Raises an error if self.ndim < 2.

fuse(nodesperbox=1, shift=0.5, rtol=1.0000000000000001e-05, atol=1.0000000000000001e-05, repeat=True)

Find (almost) identical nodes and return a compressed set.

This method finds the points that are very close and replaces them with a single point. The return value is a tuple of two arrays:

  • the unique points as a Coords object with shape (npoints,3)
  • an integer (nnod) array holding an index in the unique coordinates array for each of the original nodes. This index will have the same shape as the pshape() of the coords array.

The procedure works by first dividing the 3D space in a number of equally sized boxes, with a mean population of nodesperbox. The boxes are numbered in the 3 directions and a unique integer scalar is computed, that is then used to sort the nodes. Then only nodes inside the same box are compared on almost equal coordinates, using the numpy allclose() function. Two coordinates are considered close if they are within a relative tolerance rtol or absolute tolerance atol. See numpy for detail. The default atol is set larger than in numpy, because pyformex typically runs with single precision. Close nodes are replaced by a single one.

Running the procedure once does not guarantee to find all close nodes: two close nodes might be in adjacent boxes. The performance hit for testing adjacent boxes is rather high, and the probability of separating two close nodes with the computed box limits is very small. Therefore, the most sensible way is to run the procedure twice, with a different shift value (they should differ more than the tolerance). Specifying repeat=True will automatically do this.

match(coords, **kargs)

Match points form another Coords object.

This method finds the points from coords that coincide with (or are very close to) points of self.

Parameters:

  • coords: a Coords object
  • **kargs: keyword arguments that you want to pass to the fuse() method.

This method works by concatenating the serialized point sets of both Coords and then fusing them.

Returns:

  • matches: an Int array with shape (nmatches,2)
  • coords: a Coords with the fused coordinate set
  • index: an index with the position of each of the serialized points of the concatenation in the fused coordinate set. To find the index of the points of the orginal coordinate sets, split this index at the position self.npoints() and reshape the resulting parts to self.pshape(), resp. coords.pshape().
append(coords)

Append coords to a Coords object.

The appended coords should have matching dimensions in all but the first axis.

Returns the concatenated Coords object, without changing the current.

This is comparable to numpy.append(), but the result is a Coords object, the default axis is the first one instead of the last, and it is a method rather than a function.

classmethod concatenate(clas, L, axis=0)

Concatenate a list of Coords object.

All Coords object in the list L should have the same shape except for the length of the specified axis. This function is equivalent to the numpy concatenate, but makes sure the result is a Coords object,and the default axis is the first one instead of the last.

classmethod fromstring(clas, fil, sep=' ', ndim=3, count=-1)

Create a Coords object with data from a string.

This convenience function uses the numpy.fromstring() function to read coordinates from a string.

fil: a string containing a single sequence of float numbers separated by whitespace and a possible separator string.

sep: the separator used between the coordinates. If not a space, all extra whitespace is ignored.

ndim: number of coordinates per point. Should be 1, 2 or 3 (default). If 1, resp. 2, the coordinate string only holds x, resp. x,y values.

count: total number of coordinates to read. This should be a multiple of 3. The default is to read all the coordinates in the string. count can be used to force an error condition if the string does not contain the expected number of values.

The return value is Coords object.

classmethod fromfile(clas, fil, **kargs)

Read a Coords from file.

This convenience function uses the numpy fromfile function to read the coordinates from file. You just have to make sure that the coordinates are read in order (X,Y,Z) for subsequent points, and that the total number of coordinates read is a multiple of 3.

interpolate(X, div)

Create interpolations between two Coords.

Parameters:

  • X: a Coords with same shape as self.
  • div: a list of floating point values, or an int. If an int is specified, a list with (div+1) values for div is created by dividing the interval [0..1] into div equal distances.

Returns:

A Coords with an extra (first) axis, containing the concatenation of the interpolations of self and X at all values in div. Its shape is (n,) + self.shape, where n is the number of values in div.

An interpolation of F and G at value v is a Coords H where each coordinate Hijk is obtained from: Fijk = Fijk + v * (Gijk-Fijk). Thus, X.interpolate(Y,[0.,0.5,1.0]) will contain all points of X and Y and all points with mean coordinates between those of X and Y.

F.interpolate(G,n) is equivalent with F.interpolate(G,arange(0,n+1)/float(n))

class coords.CoordinateSystem

A CoordinateSystem defines a coordinate system in 3D space.

The coordinate system is defined by and stored as a set of four points: three endpoints of the unit vectors along the axes at the origin, and the origin itself as fourth point.

The constructor takes a (4,3) array as input. The default constructs the standard global Cartesian axes system:

1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0.
origin()

Return the origin of the CoordinateSystem.

axes()

Return the axes of the CoordinateSystem.

points()

Returns the Coords object as a simple set of points.

This reshapes the array to a 2-dimensional array, flattening the structure of the points.

pshape()

Returns the shape of the Coords object.

This is the shape of the NumPy array with the last axis removed. The full shape of the Coords array can be obtained from its shape attribute.

ncoords()

Return the total number of points.

npoints()

Return the total number of points.

x()

Return the X-coordinates of all points.

Returns an array with all the X-coordinates in the Coords. The returned array has the same shape as the Coords array along its first ndim-1 axes. This is equivalent with

self[...,0]
y()

Return the Y-coordinates of all points.

Returns an array with all the Y-coordinates in the Coords. The returned array has the same shape as the Coords array along its first ndim-1 axes. This is equivalent with

self[...,1]
z()

Return the Z-coordinates of all points.

Returns an array with all the Z-coordinates in the Coords. The returned array has the same shape as the Coords array along its first ndim-1 axes. This is equivalent with

self[...,0]
bbox()

Return the bounding box of a set of points.

The bounding box is the smallest rectangular volume in the global coordinates, such that no point of the Coords are outside that volume.

Returns:

A Coords object with shape(2,3): the first point contains the minimal coordinates, the second has the maximal ones.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).bbox()
[[ 0.  0.  0.]
 [ 3.  3.  0.]]
center()

Return the center of the Coords.

The center of a Coords is the center of its bbox(). The return value is a (3,) shaped Coords object.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).center()
[ 1.5  1.5  0. ]

See also: centroid()

average(wts=None, axis=0)

Return a (weighted) average of the Coords.

The average of a Coords is a Coords with one axis less than the original, obtained by averaging all the points along that axis. The weights array can either be 1-D (in which case its length must be the size along the given axis) or of the same shape as a. Weights can be specified as a 1-D array with the length of that axis, or as an array with the same shape as the Coords. The sum of the weights (along the specified axis if not 1-D) will generally be equal to 1.0. If wts=None, then all points are assumed to have a weight equal to one divided by the length of the specified axis.

Example:

>>> print Coords([[[0.,0.,0.],[1.,0.,0.],[2.,0.,0.]],                  [[4.,0.,0.],[5.,0.,0.],[6.,0.,0.]]]).average()
[[ 2.  0.  0.]
 [ 3.  0.  0.]
 [ 4.  0.  0.]]
>>> print Coords([[[0.,0.,0.],[1.,0.,0.],[2.,0.,0.]],                  [[4.,0.,0.],[5.,0.,0.],[6.,0.,0.]]]).average(axis=1)
[[ 1.  0.  0.]
 [ 5.  0.  0.]]
>>> print Coords([[[0.,0.,0.],[1.,0.,0.],[2.,0.,0.]],                  [[4.,0.,0.],[5.,0.,0.],[6.,0.,0.]]]).average(wts=[0.5,0.25,0.25],axis=1)
[[ 0.75  0.    0.  ]
 [ 4.75  0.    0.  ]]
centroid()

Return the centroid of the Coords.

The centroid of a Coords is the point whose coordinates are the mean values of all points. The return value is a (3,) shaped Coords object.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).centroid()
[ 1.  1.  0.]

See also: center()

sizes()

Return the sizes of the Coords.

Return an array with the length of the bbox along the 3 axes.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).sizes()
[ 3.  3.  0.]
dsize()

Return an estimate of the global size of the Coords.

This estimate is the length of the diagonal of the bbox().

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).dsize()
4.24264
bsphere()

Return the diameter of the bounding sphere of the Coords.

The bounding sphere is the smallest sphere with center in the center() of the Coords, and such that no points of the Coords are lying outside the sphere.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).bsphere()
2.12132
inertia(mass=None)

Return inertia related quantities of the Coords.

This returns the center of gravity, the principal axes of inertia, the principal moments of inertia and the inertia tensor.

distanceFromPlane(p, n)

Return the distance of all points from the plane (p,n).

p is a point specified by 3 coordinates. n is the normal vector to a plane, specified by 3 components.

The return value is a float array with shape self.pshape() with the distance of each point to the plane through p and having normal n. Distance values are positive if the point is on the side of the plane indicated by the positive normal.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).distanceFromPlane([0.,0.,0.],[1.,0.,0.])
[[ 0.  3.  0.]]
distanceFromLine(p, n)

Return the distance of all points from the line (p,n).

p,n are (1,3) or (npts,3) arrays defining 1 or npts lines p is a point on the line specified by 3 coordinates. n is a vector specifying the direction of the line through p.

The return value is a [...] shaped array with the distance of each point to the line through p with direction n. All distance values are positive or zero.

Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).distanceFromLine([0.,0.,0.],[1.,0.,0.])
[[ 0.  0.  3.]]
distanceFromPoint(p)

Return the distance of all points from the point p.

p is a single point specified by 3 coordinates.

The return value is a [...] shaped array with the distance of each point to point p. All distance values are positive or zero. Example:

>>> print Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]]).distanceFromPoint([0.,0.,0.])
[[ 0.  3.  3.]]
closestToPoint(p)

Return the point closest to point p.

directionalSize(n, p=None, _points=False)

Return the extreme distances from the plane p,n.

The direction n can be specified by a 3 component vector or by a single integer 0..2 designing one of the coordinate axes.

p is any point in space. If not specified, it is taken as the center() of the Coords.

The return value is a tuple of two float values specifying the extreme distances from the plane p,n.

directionalExtremes(n, p=None)

Return extremal planes in the direction n.

n and p have the same meaning as in directionalSize.

The return value is a list of two points on the line (p,n), such that the planes with normal n through these points define the extremal planes of the Coords.

directionalWidth(n)

Return the width of a Coords in the given direction.

The direction can be specified by a 3 component vector or by a single integer 0..2 designating one of the coordinate axes.

The return value is the thickness of the object in the direction n.

test(dir=0, min=None, max=None, atol=0.0)

Flag points having coordinates between min and max.

This function is very convenient in clipping a Coords in a specified direction. It returns a 1D integer array flagging (with a value 1 or True) the elements having nodal coordinates in the required range. Use where(result) to get a list of element numbers passing the test. Or directly use clip() or cclip() to create the clipped Coords.

The test plane can be define in two ways depending on the value of dir. If dir == 0, 1 or 2, it specifies a global axis and min and max are the minimum and maximum values for the coordinates along that axis. Default is the 0 (or x) direction.

Else, dir should be compatible with a (3,) shaped array and specifies the direction of the normal on the planes. In this case, min and max are points and should also evaluate to (3,) shaped arrays.

One of the two clipping planes may be left unspecified.

fprint(fmt='%10.3e %10.3e %10.3e')

Formatted printing of a Coords object.

The supplied format should contain 3 formatting sequences for the three coordinates of a point.

set(f)

Set the coordinates from those in the given array.

scale(scale, dir=None, center=None, inplace=False)

Return a copy scaled with scale[i] in direction i.

The scale should be a list of 3 scaling factors for the 3 axis directions, or a single scaling factor. In the latter case, dir (a single axis number or a list) may be given to specify the direction(s) to scale. The default is to produce a homothetic scaling. The center of the scaling, if not specified, is the global origin. If a center is specified, the result is equivalent to:

self.translate(-center).scale(scale,dir).translate(center)

Example:

>>> print Coords([1.,1.,1.]).scale(2)
[ 2.  2.  2.]
>>> print Coords([1.,1.,1.]).scale([2,3,4])
[ 2.  3.  4.]
translate(dir, step=None, inplace=False)

Translate a Coords object.

Translates the Coords in the direction dir over a distance step * length(dir).

Parameters:

  • dir: specifies the direction and distance of the translation. It can be either
    • an axis number (0,1,2), specifying a unit vector in the direction of one of the coordinate axes.
    • a single translation vector,
    • an array of translation vectors, compatible with the Coords shape.
  • step: If specified, the translation vector specified by dir will be multiplied with this value. It is commonly used with unit dir vectors to set the translation distance.

Example:

>>> x = Coords([1.,1.,1.])
>>> print x.translate(1)
[ 1.  2.  1.]
>>> print x.translate(1,1.)
[ 1.  2.  1.]
>>> print x.translate([0,1,0])
[ 1.  2.  1.]
>>> print x.translate([0,2,0],0.5)
[ 1.  2.  1.]
trl(dir, step=None, inplace=False)

Translate a Coords object.

Translates the Coords in the direction dir over a distance step * length(dir).

Parameters:

  • dir: specifies the direction and distance of the translation. It can be either
    • an axis number (0,1,2), specifying a unit vector in the direction of one of the coordinate axes.
    • a single translation vector,
    • an array of translation vectors, compatible with the Coords shape.
  • step: If specified, the translation vector specified by dir will be multiplied with this value. It is commonly used with unit dir vectors to set the translation distance.

Example:

>>> x = Coords([1.,1.,1.])
>>> print x.translate(1)
[ 1.  2.  1.]
>>> print x.translate(1,1.)
[ 1.  2.  1.]
>>> print x.translate([0,1,0])
[ 1.  2.  1.]
>>> print x.translate([0,2,0],0.5)
[ 1.  2.  1.]
centered()

Return a centered copy of the Coords.

Returns a Coords which is a translation thus that the center coincides with the origin. This is equivalent with:

self.trl(-self.center())
align(alignment='---')

Align the Coords along the global axes.

Alignment involves a translation such that the bounding box of the Coords object becomes aligned on the origin of the global axes. The requested alignment is determined by a string of three characters, one for each of the coordinate axes. The character determines how the structure is aligned in the corresponding direction:

  • ‘-‘: aligned on the minimal value of the bounding box,
  • ‘+’: aligned on the maximal value of the bounding box,
  • ‘0’: aligned on the middle value of the bounding box.

Any other value will make the alignment in that direction unchanged.

The default alignment string ‘—’ results in a translation which puts all the points in the octant with all positive coordinate values. A string ‘000’ will center the object around the origin, just like the (slightly faster) centered() method, which is .

rot(angle, axis=2, around=None)

Return a copy rotated over angle around axis.

The angle is specified in degrees. The axis is either one of (0,1,2) designating the global axes, or a vector specifying an axis through the origin. If no axis is specified, rotation is around the 2(z)-axis. This is convenient for working on 2D-structures.

As a convenience, the user may also specify a 3x3 rotation matrix, in which case the function rotate(mat) is equivalent to affine(mat).

All rotations are performed around the point [0,0,0], unless a rotation origin is specified in the argument ‘around’.

rotate(angle, axis=2, around=None)

Return a copy rotated over angle around axis.

The angle is specified in degrees. The axis is either one of (0,1,2) designating the global axes, or a vector specifying an axis through the origin. If no axis is specified, rotation is around the 2(z)-axis. This is convenient for working on 2D-structures.

As a convenience, the user may also specify a 3x3 rotation matrix, in which case the function rotate(mat) is equivalent to affine(mat).

All rotations are performed around the point [0,0,0], unless a rotation origin is specified in the argument ‘around’.

shear(dir, dir1, skew, inplace=False)

Return a copy skewed in the direction dir of plane (dir,dir1).

The coordinate dir is replaced with (dir + skew * dir1).

reflect(dir=0, pos=0.0, inplace=False)

Reflect the coordinates in direction dir against plane at pos.

Parameters:

  • dir: int: direction of the reflection (default 0)
  • pos: float: offset of the mirror plane from origin (default 0.0)
  • inplace: boolean: change the coordinates inplace (default False)
affine(mat, vec=None)

Returns a general affine transform of the Coords object.

mat: a 3x3 float matrix

vec: a length 3 list or array of floats

The returned object has coordinates given by self * mat + vec.

cylindrical(dir=[0, 1, 2], scale=[1.0, 1.0, 1.0], angle_spec=0.017453292519943295)

Converts from cylindrical to cartesian after scaling.

dir specifies which coordinates are interpreted as resp. distance(r), angle(theta) and height(z). Default order is [r,theta,z]. scale will scale the coordinate values prior to the transformation. (scale is given in order r,theta,z). The resulting angle is interpreted in degrees.

toCylindrical(dir=[0, 1, 2], angle_spec=0.017453292519943295)

Converts from cartesian to cylindrical coordinates.

dir specifies which coordinates axes are parallel to respectively the cylindrical axes distance(r), angle(theta) and height(z). Default order is [x,y,z]. The angle value is given in degrees.

spherical(dir=[0, 1, 2], scale=[1.0, 1.0, 1.0], angle_spec=0.017453292519943295, colat=False)

Converts from spherical to cartesian after scaling.

  • dir specifies which coordinates are interpreted as resp. longitude(theta), latitude(phi) and distance(r).
  • scale will scale the coordinate values prior to the transformation.

Angles are interpreted in degrees. Latitude, i.e. the elevation angle, is measured from equator in direction of north pole(90). South pole is -90.

If colat=True, the third coordinate is the colatitude (90-lat) instead.

superSpherical(n=1.0, e=1.0, k=0.0, dir=[0, 1, 2], scale=[1.0, 1.0, 1.0], angle_spec=0.017453292519943295, colat=False)

Performs a superspherical transformation.

superSpherical is much like spherical, but adds some extra parameters to enable the creation of virtually any surface.

Just like with spherical(), the input coordinates are interpreted as the longitude, latitude and distance in a spherical coordinate system.

dir specifies which coordinates are interpreted as resp. longitude(theta), latitude(phi) and distance(r). Angles are then interpreted in degrees. Latitude, i.e. the elevation angle, is measured from equator in direction of north pole(90). South pole is -90. If colat=True, the third coordinate is the colatitude (90-lat) instead.

scale will scale the coordinate values prior to the transformation.

The n and e parameters define exponential transformations of the north_south (latitude), resp. the east_west (longitude) coordinates. Default values of 1 result in a circle.

k adds ‘eggness’ to the shape: a difference between the northern and southern hemisphere. Values > 0 enlarge the southern hemishpere and shrink the northern.

toSpherical(dir=[0, 1, 2], angle_spec=0.017453292519943295)

Converts from cartesian to spherical coordinates.

dir specifies which coordinates axes are parallel to respectively the spherical axes distance(r), longitude(theta) and latitude(phi). Latitude is the elevation angle measured from equator in direction of north pole(90). South pole is -90. Default order is [0,1,2], thus the equator plane is the (x,y)-plane.

The returned angle values are given in degrees.

bump1(dir, a, func, dist)

Return a Coords with a one-dimensional bump.

  • dir specifies the axis of the modified coordinates;
  • a is the point that forces the bumping;
  • dist specifies the direction in which the distance is measured;
  • func is a function that calculates the bump intensity from distance and should be such that func(0) != 0.
bump2(dir, a, func)

Return a Coords with a two-dimensional bump.

dir specifies the axis of the modified coordinates; a is the point that forces the bumping; func is a function that calculates the bump intensity from distance !! func(0) should be different from 0.

bump(dir, a, func, dist=None)

Return a Coords with a bump.

A bump is a modification of a set of coordinates by a non-matching point. It can produce various effects, but one of the most common uses is to force a surface to be indented by some point.

dir specifies the axis of the modified coordinates; a is the point that forces the bumping; func is a function that calculates the bump intensity from distance (!! func(0) should be different from 0) dist is the direction in which the distance is measured : this can be one of the axes, or a list of one or more axes. If only 1 axis is specified, the effect is like function bump1 If 2 axes are specified, the effect is like bump2 This function can take 3 axes however. Default value is the set of 3 axes minus the direction of modification. This function is then equivalent to bump2.

flare(xf, f, dir=[0, 2], end=0, exp=1.0)

Create a flare at the end of a Coords block.

The flare extends over a distance xf at the start (end=0) or end (end=1) in direction dir[0] of the coords block, and has a maximum amplitude of f in the dir[1] direction.

map(func)

Return a Coords mapped by a 3-D function.

This is one of the versatile mapping functions. func is a numerical function which takes three arguments and produces a list of three output values. The coordinates [x,y,z] will be replaced by func(x,y,z). The function must be applicable to arrays, so it should only include numerical operations and functions understood by the numpy module. This method is one of several mapping methods. See also map1 and mapd.

Example:

>>> print Coords([[1.,1.,1.]]).map(lambda x,y,z: [2*x,3*y,4*z])
[[ 2.  3.  4.]]
map1(dir, func, x=None)

Return a Coords where coordinate i is mapped by a 1-D function.

func is a numerical function which takes one argument and produces one result. The coordinate dir will be replaced by func(coord[x]). If no x is specified, x is taken equal to dir. The function must be applicable on arrays, so it should only include numerical operations and functions understood by the numpy module. This method is one of several mapping methods. See also map and mapd.

mapd(dir, func, point, dist=None)

Maps one coordinate by a function of the distance to a point.

func a numerical function which takes one argument and produces one result. The coordinate dir will be replaced by func(d), where d is calculated as the distance to point. The function must be applicable on arrays, so it should only include numerical operations and functions understood by the numpy module. By default, the distance d is calculated in 3-D, but one can specify a limited set of axes to calculate a 2-D or 1-D distance. This method is one of several mapping methods. See also map3() and map1().

Example:

E.mapd(2,lambda d:sqrt(10**2-d**2),f.center(),[0,1])

maps E on a sphere with radius 10.

egg(k)

Maps the coordinates to an egg-shape

replace(i, j, other=None)

Replace the coordinates along the axes i by those along j.

i and j are lists of axis numbers or single axis numbers. replace ([0,1,2],[1,2,0]) will roll the axes by 1. replace ([0,1],[1,0]) will swap axes 0 and 1. An optionally third argument may specify another Coords object to take the coordinates from. It should have the same dimensions.

swapAxes(i, j)

Swap coordinate axes i and j.

Beware! This is different from numpy’s swapaxes() method !

rollAxes(n=1)

Roll the axes over the given amount.

Default is 1, thus axis 0 becomes the new 1 axis, 1 becomes 2 and 2 becomes 0.

projectOnPlane(n=2, P=[0.0, 0.0, 0.0])

Project a Coords on a plane (or planes).

Parameters:

  • n: the normal direction to the plane. It can be specified either by a list of three floats, or by a single integer (0, 1 or 2) to use one of the global axes.
  • P: a point on the plane, by default the global origin. If an int, the plane is the coordinate plane perpendicular to the
..note: For planes parallel to a coordinate plane, it is far more
efficient to specify the normal by an axis number than by a three component vector.

Returns: a Coords with same shape as original, with all the points projected on the specified plane(s).

projectOnSphere(radius=1.0, center=[0.0, 0.0, 0.0])

Project Coords on a sphere.

The default sphere is a unit sphere at the origin. The center of the sphere should not be part of the Coords.

projectOnCylinder(radius=1.0, dir=0, center=[0.0, 0.0, 0.0])

Project Coords on a cylinder with axis parallel to a global axis.

The default cylinder has its axis along the x-axis and a unit radius. No points of the Coords should belong to the axis..

projectOnSurface(S, n, ignore_errors=False)

Project the Coords on a triangulated surface.

The points of the Coords are projected in the direction of the vector n onto the surface S.

Parameters:

  • S: TriSurface: any triangulated surface
  • n: int or vector: specifies the direction of the projection
  • ignore_errors: if True, projective lines not cutting the surface will result in NaN values. The default is to raise an error.

If successful, a Coords with the same structure as the input is returned.

isopar(eltype, coords, oldcoords)

Perform an isoparametric transformation on a Coords.

This is a convenience method to transform a Coords object through an isoparametric transformation. It is equivalent to:

Isopar(eltype,coords,oldcoords).transform(self)

See plugins.isopar for more details.

transformCS(currentCS, initialCS=None)

Perform a CoordinateSystem transformation on the Coords.

This method transforms the Coords object by the transformation that turns the initial CoordinateSystem into the currentCoordinateSystem.

currentCS and initialCS are CoordinateSystem or (4,3) shaped Coords instances. If initialCS is None, the global (x,y,z) axes are used.

E.g. the default initialCS and currentCS equal to:

 0.  1.  0.
-1.  0.  0.
 0.  0.  1.
 0.  0.  0.

result in a rotation of 90 degrees around the z-axis.

This is a convenience function equivalent to:

self.isopar('tet4',currentCS,initialCS)
addNoise(rsize=0.10000000000000001, asize=0.0)

Add random noise to a Coords.

A random amount is added to eacho individual coordinate in the Coords. The difference of any coordinate from its original value will not be maximally asize + rsize * self.sizes().max(). The default is to set it to 0.1 times the geometrical size of the structure.

rep(n, dir=0, step=None)

Replicate a Coords n times with fixed step in any direction.

Returns a Coords object with shape (n,) + self.shape, thus having an extra first axis. Each component along the axis 0 is equal to the previous component translated over (dir,step), where dir and step are interpreted just like in the translate() method. The first component along the axis 0 is identical to the original Coords.

replicate(n, dir=0, step=None)

Replicate a Coords n times with fixed step in any direction.

Returns a Coords object with shape (n,) + self.shape, thus having an extra first axis. Each component along the axis 0 is equal to the previous component translated over (dir,step), where dir and step are interpreted just like in the translate() method. The first component along the axis 0 is identical to the original Coords.

split()

Split the coordinate array in blocks along first axis.

The result is a sequence of arrays with shape self.shape[1:]. Raises an error if self.ndim < 2.

fuse(nodesperbox=1, shift=0.5, rtol=1.0000000000000001e-05, atol=1.0000000000000001e-05, repeat=True)

Find (almost) identical nodes and return a compressed set.

This method finds the points that are very close and replaces them with a single point. The return value is a tuple of two arrays:

  • the unique points as a Coords object with shape (npoints,3)
  • an integer (nnod) array holding an index in the unique coordinates array for each of the original nodes. This index will have the same shape as the pshape() of the coords array.

The procedure works by first dividing the 3D space in a number of equally sized boxes, with a mean population of nodesperbox. The boxes are numbered in the 3 directions and a unique integer scalar is computed, that is then used to sort the nodes. Then only nodes inside the same box are compared on almost equal coordinates, using the numpy allclose() function. Two coordinates are considered close if they are within a relative tolerance rtol or absolute tolerance atol. See numpy for detail. The default atol is set larger than in numpy, because pyformex typically runs with single precision. Close nodes are replaced by a single one.

Running the procedure once does not guarantee to find all close nodes: two close nodes might be in adjacent boxes. The performance hit for testing adjacent boxes is rather high, and the probability of separating two close nodes with the computed box limits is very small. Therefore, the most sensible way is to run the procedure twice, with a different shift value (they should differ more than the tolerance). Specifying repeat=True will automatically do this.

match(coords, **kargs)

Match points form another Coords object.

This method finds the points from coords that coincide with (or are very close to) points of self.

Parameters:

  • coords: a Coords object
  • **kargs: keyword arguments that you want to pass to the fuse() method.

This method works by concatenating the serialized point sets of both Coords and then fusing them.

Returns:

  • matches: an Int array with shape (nmatches,2)
  • coords: a Coords with the fused coordinate set
  • index: an index with the position of each of the serialized points of the concatenation in the fused coordinate set. To find the index of the points of the orginal coordinate sets, split this index at the position self.npoints() and reshape the resulting parts to self.pshape(), resp. coords.pshape().
append(coords)

Append coords to a Coords object.

The appended coords should have matching dimensions in all but the first axis.

Returns the concatenated Coords object, without changing the current.

This is comparable to numpy.append(), but the result is a Coords object, the default axis is the first one instead of the last, and it is a method rather than a function.

classmethod concatenate(clas, L, axis=0)

Concatenate a list of Coords object.

All Coords object in the list L should have the same shape except for the length of the specified axis. This function is equivalent to the numpy concatenate, but makes sure the result is a Coords object,and the default axis is the first one instead of the last.

classmethod fromstring(clas, fil, sep=' ', ndim=3, count=-1)

Create a Coords object with data from a string.

This convenience function uses the numpy.fromstring() function to read coordinates from a string.

fil: a string containing a single sequence of float numbers separated by whitespace and a possible separator string.

sep: the separator used between the coordinates. If not a space, all extra whitespace is ignored.

ndim: number of coordinates per point. Should be 1, 2 or 3 (default). If 1, resp. 2, the coordinate string only holds x, resp. x,y values.

count: total number of coordinates to read. This should be a multiple of 3. The default is to read all the coordinates in the string. count can be used to force an error condition if the string does not contain the expected number of values.

The return value is Coords object.

classmethod fromfile(clas, fil, **kargs)

Read a Coords from file.

This convenience function uses the numpy fromfile function to read the coordinates from file. You just have to make sure that the coordinates are read in order (X,Y,Z) for subsequent points, and that the total number of coordinates read is a multiple of 3.

interpolate(X, div)

Create interpolations between two Coords.

Parameters:

  • X: a Coords with same shape as self.
  • div: a list of floating point values, or an int. If an int is specified, a list with (div+1) values for div is created by dividing the interval [0..1] into div equal distances.

Returns:

A Coords with an extra (first) axis, containing the concatenation of the interpolations of self and X at all values in div. Its shape is (n,) + self.shape, where n is the number of values in div.

An interpolation of F and G at value v is a Coords H where each coordinate Hijk is obtained from: Fijk = Fijk + v * (Gijk-Fijk). Thus, X.interpolate(Y,[0.,0.5,1.0]) will contain all points of X and Y and all points with mean coordinates between those of X and Y.

F.interpolate(G,n) is equivalent with F.interpolate(G,arange(0,n+1)/float(n))

Functions defined in module coords

coords.bbox(objects)

Compute the bounding box of a list of objects.

The bounding box of an object is the smallest rectangular cuboid in the global Cartesian coordinates, such that no points of the objects lie outside that cuboid. The resulting bounding box of the list of objects is the smallest bounding box that encloses all the objects in the list. Objects that do not have a bbox() method or whose bbox() method returns invalid values, are ignored.

Parameters:

  • objects: a list of objects (which should probably have the method bbox()).
Returns:
A Coords object with two points: the first contains the minimal coordinate values, the second has the maximal ones of the overall bounding box.

Example:

>>> from formex import *
>>> bbox([Coords([-1.,1.,0.]),Formex('l:5')])
Coords([[-1.,  0.,  0.],
       [ 1.,  1.,  0.]], dtype=float32)
coords.origin()

Return a single point with coordinates [0.,0.,0.].

Returns:
A Coords object with shape(3,) holding three zero coordinates.
coords.pattern(s, connect=True)

Return a series of points lying on a regular grid.

This function creates a series of points that lie on a regular grid with unit step. These points are created from a string input, interpreting each character as a code specifying how to move to the next point. The start position is always the origin (0.,0.,0.).

Currently the following codes are defined:

  • 0: goto origin (0.,0.,0.)
  • 1..8: move in the x,y plane
  • 9: remain at the same place (and duplicate the last point)
  • A..I: same as 1..9 plus step +1. in z-direction
  • a..i: same as 1..9 plus step -1. in z-direction
  • /: do not insert the next point

Any other character raises an error.

When looking at the x,y-plane with the x-axis to the right and the y-axis up, we have the following basic moves: 1 = East, 2 = North, 3 = West, 4 = South, 5 = NE, 6 = NW, 7 = SW, 8 = SE.

Adding 16 to the ordinal of the character causes an extra move of +1. in the z-direction. Adding 48 causes an extra move of -1. This means that ‘ABCDEFGHI’, resp. ‘abcdefghi’, correspond with ‘123456789’ with an extra z +/-= 1. This gives the following schema:

    z+=1             z unchanged            z -= 1

F    B    E          6    2    5         f    b    e 
     |                    |                   |     
     |                    |                   |     
C----I----A          3----9----1         c----i----a  
     |                    |                   |     
     |                    |                   |     
G    D    H          7    4    8         g    d    h

The special character ‘/’ can be put before any character to make the move without inserting the new point. You need to start the string with a ‘0’ or ‘9’ to include the origin in the output.

Returns a list with the generated points as integers.

Example:

>>> pattern('0123')
[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
coords.xpattern(s, nplex=1)

Create a Coords object from a string pattern.

This is like pattern, but allows grouping the points into elements. First, the string is expanded to a list of points by calling pattern(s). Then the resulting list of points is transformed in a 2D table of points where each row has the length nplex.

If the number of points produced by s is not a multiple of nplex, an error is raised.

coords.sweepCoords(self, path, origin=[0.0, 0.0, 0.0], normal=0, upvector=2, avgdir=False, enddir=None, scalex=None, scaley=None)

Sweep a Coords object along a path, returning a series of copies.

origin and normal define the local path position and direction on the mesh.

At each point of the curve, a copy of the Coords object is created, with its origin in the curve’s point, and its normal along the curve’s direction. In case of a PolyLine, directions are pointing to the next point by default. If avgdir==True, average directions are taken at the intermediate points avgdir can also be an array like sequence of shape (N,3) to explicitely set the the directions for ALL the points of the path

Missing end directions can explicitely be set by enddir, and are by default taken along the last segment. enddir is a list of 2 array like values of shape (3). one of the two can also be an empty list If the curve is closed, endpoints are treated as any intermediate point, and the user should normally not specify enddir.

At each point of the curve, the original Coords object can be scaled in x and y direction by specifying scalex and scaley. The number of values specified in scalex and scaly should be equal to the number of points on the curve.

The return value is a sequence of the transformed Coords objects.