#### Previous topic

pyFormex reference manual

#### Next topic

2. formex — Formex algebra in Python

# 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()

Returns 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

```asarray(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

```asarray(self[...,1])
```
z()

Returns 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

```asarray(self[...,2])
```
bbox()

Returns 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:

```>>> X = Coords([[[0.,0.,0.],[3.,0.,0.],[0.,3.,0.]]])
>>> print(X.bbox())
[[ 0.  0.  0.]
[ 3.  3.  0.]]
```
apt(align)

Returns an alignment point of a Coords.

Alignment point are points whose coordinates are either the minimal value, the maximal value or the middle value for the Coords. Combining the three values with the three dimensions, a Coords has in 27 (3**3) alignment points. The corner points of the bounding box are a subset of these.

The 27 points are addressed by an alignment string of three characters, one for each direction. Each character should be one of the following

• ‘-‘: use the minimal value for that coordinate,
• ‘+’: use the minimal value for that coordinate,
• ‘0’: use the middle value for that coordinate.

Any other character will set the corresponding coordinate to zero.

A string ‘000’ is equivalent with center(). The values ‘—’ and ‘+++’ give the points of the bounding box.

Example:

```>>> X = Coords([[[0.,0.,0.],[1.,1.,1.]]])
>>> print(X.apt('-0+'))
[ 0.   0.5  1. ]
```
center()

Returns 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:

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

average(wts=None, axis=0)

Returns 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:

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

Returns 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.]
```

sizes()

Returns the sizes of the Coords.

Returns 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()

Returns 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()

Returns 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.12132024765
```
bboxes()

Returns the bboxes of all elements in the coords array.

The returned array has shape (...,2,3). Along the -2 axis are stored the minimal and maximal values of the Coords along that axis.

inertia(mass=None)

Returns inertia related quantities of the Coords.

Parameters:

• mass: float array with ncoords weight values. The default is to attribute a weight 1.0 to each point.

Returns a tuple of:

• center: the center of mass: shape (3,)
• axes: the principal axes of the inertia tensor: shape (3,3)
• principal: the (prinicipal) moments of inertia: shape (3,)
• tensor: the full inertia tensor in the global axes: shape (3,3)
distanceFromPlane(p, n)

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

Parameters:

• 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:

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

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

p,n are (1,3) or (npts,3) arrays defining 1 or npts lines

Parameters:

• 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:

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

Returns 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:

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

Returns the point closest to point p.

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

Returns the extreme distances from the plane p,n.

Parameters:

• n: the direction 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)

Returns 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)

Returns 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.

Tests the position of the points of the Coords with respect to one or two planes. This method is very convenient in clipping a Coords in a specified direction. In most cases the clipping direction is one of the global cooordinate axes, but a general direction may be used as well.

Parameters:

• dir: either a global axis number (0, 1 or 2) or a direction vector consisting of 3 floats. It specifies the direction in which the distances are measured. Default is the 0 (or x) direction.
• min, max: position of the minimum and maximum clipping planes. If dir was specified as an integer (0,1,2), this is a single float value corresponding with the coordinate in that axis direction. Else, it is a point in the clipping plane with normal direction dir. One of the two clipping planes may be left unspecified.

Returns:

A 1D integer array with same length as the number of points. For each point the value is 1 (True) if the point is above the minimum clipping plane and below the maximum clipping plane, or 0 (False) otherwise. An unspecified clipping plane corresponds with an infinitely low or high value. The return value can directly be used as an index to obtain a Coords with the points satisfying the test (or not). See the examples below.

Example:

```>>> x = Coords([[0.,0.],[1.,0.],[0.,1.],[0.,2.]])
>>> print(x.test(min=0.5))
[False  True False False]
>>> t = x.test(dir=1,min=0.5,max=1.5)
>>> print(x[t])
[[ 0.  1.  0.]]
>>> print(x[~t])
[[ 0.  0.  0.]
[ 1.  0.  0.]
[ 0.  2.  0.]]
```
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)

Returns 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()

Returns 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='---', point=[0.0, 0.0, 0.0])

Align a Coords on a given point.

Alignment involves a translation such that the bounding box of the Coords object becomes aligned with a given point. By default this is 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.

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

Returns 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)

Returns 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)

Perform a general affine transformation.

Parameters:

• mat: a 3x3 float matrix
• vec: a length 3 list or array of floats

The returned object has coordinates given by self * mat + vec. If mat is a rotation matrix, than the operation performs a rigid rotation of the object plus a translation.

position(x, y)

Position an object so that points x are aligned with y.

Parameters are as for arraytools.trfMatrix()

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

Converts from cylindrical to cartesian after scaling.

Parameters:

• 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.

Parameters:

• 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.

Parameters:

• 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.

Parameters:

• 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.
• n, 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.

Parameters:

• 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)

Returns a Coords with a one-dimensional bump.

Parameters:

• 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)

Returns a Coords with a two-dimensional bump.

Parameters:

• 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)

Returns 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.

Parameters:

• 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)

Map a Coords by a 3-D function.

This is one of the versatile mapping functions.

Parameters:

• 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)

Map one coordinate by a 1-D function of one coordinate.

Parameters:

• 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=[0.0, 0.0, 0.0], dist=None)

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

Parameters:

• dir: 0, 1 or 2: the coordinate that will be replaced with func(d), where d is calculated as the distance to point.
• func: a numerical function which takes one float argument and produce one float result. The function must be applicable on arrays, so it should only include numerical operations and functions understood by the numpy module.
• point: the point to where the distance d is computed.
• dist: a list of coordinate directions that are used to compute the distances d. It can also be a single coordinate direction. The default is to use 3-D distances.

This method is one of several mapping methods. See also map3() and map1().

Example:

```E.mapd(2,lambda d:sqrt(10**2-d**2),E.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.

Note

This method will also work if any or both of P and n have a shape (ncoords,3), where ncoords is the total number of points in the Coords. This allows to project each point on an individual plane.

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

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.

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, dir=0, missing='error', return_indices=False)

Project the Coords on a triangulated surface.

The points of the Coords are projected in the specified direction dir onto the surface S.

Parameters:

• S: TriSurface: any triangulated surface
• dir: int or vector: specifies the direction of the projection
• missing: float value or a string. Specifies a distance to set the position of the projection point in cases where the projective line does not cut the surface. The sign of the distance is taken into account. If specified as a string, it should be one of the strings ‘c’, ‘f’, or ‘m’, possibly preceded by a ‘+’ or ‘-‘. The distance will then be taken equal to the closest, the furthest, or the mean distance of a point to its projection, and applied in positive or negative direction as specified. Any other value of missing will result in an error if some point does not have any projection. An error will also be raised if not a single point projection intersects the surface.
• return_indices: if True, also returns an index of the points that have a projection on the surface.

Returns:

A Coords with the same shape as the input. If return_indices is True, also returns an index of the points that have a projection on the surface. This index is a sequential one, no matter what the shape of the input Coords is.
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 coordinate system transformation on the Coords.

This method transforms the Coords object by the transformation that turns the initial coordinate system into the current coordinate system.

currentCS and initialCS are (4,3) shaped Coords instances defining a coordinate system as described in CoordinateSystem. 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)
```

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 r than asize+rsize*self.sizes().max(). The default is to set it to 0.05 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.

sort(order=[0, 1, 2])

Sort points in the specified order of their coordinates.

The points are sorted based on their coordinate values. There is a maximum number of points (above 2 million) that can be sorted. If you need to to sort more, first split up your data according to the first axis.

Parameters:

• order: permutation of [0,1,2], specifying the order in which the subsequent axes are used to sort the points.

Returns:

An int array which is a permutation of range(self.npoints()). If taken in the specified order, it is guaranteed that no point can have a coordinate that is larger that the corresponding coordinate of the next point.
boxes(ppb=1, shift=0.5, minsize=1e-05)

Create a grid of equally sized boxes spanning the points x.

A regular 3D grid of equally sized boxes is created spanning all the points x. The size, position and number of boxes are determined from the specified parameters.

Parameters:

• ppb: int: mean number of points per box. The box sizes and number of boxes will be determined to approximate this number.
• shift: float (0.0 .. 1.0): a relative shift value for the grid. Applying a shift of 0.5 will make the lowest coordinate values fall at the center of the outer boxes.
• minsize: float: minimum absolute size of the boxes (same in each coordinate direction).

Returns a tuple of:

• ox: float array (3): minimal coordinates of the box grid,
• dx: float array (3): box size in the three axis directions,
• nx: in array (3): number of boxes in each of the coordinate directions.
fuse(ppb=1, shift=0.5, rtol=1e-05, atol=1e-05, repeat=True, nodesperbox=None)

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.

Returns a tuple of two arrays:

• coords: the unique points as a Coords object with shape (npoints,3),
• elems: an int array holding an index in the unique coordinates array for each of the original nodes. The shape of the index array is equal to the shape of the input coords array minus the last dimension (also given by self.pshape()).

The procedure works by first dividing the 3D space in a number of equally sized boxes, with a mean population of ppb. 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.

The result is at least a 2D array, even when the list contains a single Coords with a single point.

```>>> X = Coords([1.,1.,0.])
>>> Y = Coords([[2.,2.,0.],[3.,3.,0.]])
>>> print(Coords.concatenate([X,Y]))
[[ 1.  1.  0.]
[ 2.  2.  0.]
[ 3.  3.  0.]]
>>> print(Coords.concatenate([X,X]))
[[ 1.  1.  0.]
[ 1.  1.  0.]]
>>> print(Coords.concatenate([Y]))
[[ 2.  2.  0.]
[ 3.  3.  0.]]
>>> print(Coords.concatenate([X]))
[[ 1.  1.  0.]]
```
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.

Parameters:

• 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)

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)

Returns 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.

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.bboxIntersection(A, B)

Compute the intersection of the bounding box of two objects.

A and B are objects having a bbox method. The intersection of the two bounding boxes is returned in boox format.

coords.testBbox(A, bb, dirs=[0, 1, 2], nodes='any')

Test which part of A is inside a given bbox, applied in directions dirs.

Parameters:

• A: is any object having bbox and a test method (Formex, Mesh).
• bb: is a bounding box, i.e. a (2,3) shape float array.
• dirs: is a list of the three coordinate axes or a subset thereof.
• nodes: has the same meaning as in Formex.test and Mesh.test.

The result is a bool array flagging the elements that are inside the given bounding box.

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, aslist=False)

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 or .: remain at the same place (i.e. 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.

Parameters:

• s: string: with the characters generating subsequent points.
• aslist: bool: if True, the points are returned as lists of integer coordinates instead of a Coords object.

Returns a Coords with the generated points (default) or a list of tuples with 3 integer coordinates (if aslist is True).

Example:

```>>> print(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.

Example:

```>>> print(xpattern('.12.34',3))
[[[ 0.  0.  0.]
[ 1.  0.  0.]
[ 1.  1.  0.]]

[[ 1.  1.  0.]
[ 0.  1.  0.]
[ 0.  0.  0.]]]
```
coords.align(L, align, offset=[0.0, 0.0, 0.0])

Align a list of geometrical objects.

L is a list of geometrical objects (Coords or Geometry or subclasses thereof) and thus having an appropriate align method. align is a string of three characters, one for each coordinate direction, defining how the subsequent objects have to be aligned in that direction:

• - : align on the minimal coordinate value
• + : align on the maximal coordinate value
• 0 : align on the middle coordinate value
• | : align the minimum value on the maximal value of the previous item

E.g., the string '|--' will juxtapose the objects in the x-direction, while aligning them on their minimal coordinates in the y- and z- direction.

An offset may be specified to create a space between the object, instead of juxtaposing them.

Returns: a list with the aligned objects.

coords.sweepCoords(self, path, origin=[0.0, 0.0, 0.0], normal=0, upvector=2, avgdir=False, enddir=None, scalex=None, scaley=None, scalez=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.