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

A structured collection of 3D coordinates.

The coords module defines the Coords class, which is the basic data structure in pyFormex to store 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. The Coords class is used by other classes, such as Formex and Surface, which thus inherit the same transformation capabilities. In future, other geometrical data models may (and should) also derive from the Coords 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.

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 float type numpy.ndarray whose last axis 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 Coords object inherits all the methods of the numpy.ndarray.

data: If specified, data should evaluate to an (...,3) shaped array of floats. If no data are given, a single point (0.,0.,0.) will be created.

dtyp: The datatype to be used. It not specified, the datatype of data is used, or the default Float (which is equivalent to numpy.float32).

copy: If True, the data are copied. By default, the original data are used if possible, e.g. if a correctly shaped and typed numpy.ndarray is specified.

Methods

Coords objects have the following methods:

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.
x()
Return the x-plane
y()
Return the y-plane
z()
Return the z-plane
bbox()

Return the bounding box of a set of points.

The bounding box is the smallest rectangular volume in global coordinates, such at no points are outside the box. It is returned as a Coords object with shape (2,3): the first point holds the minimal coordinates and the second point has the maximal ones.

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.

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.

sizes()

Return the sizes of the Coords.

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

dsize()

Return an estimate of the global size of the Coords.

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

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.

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 [...] shaped array 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.

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.

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.

directionalSize(n, p=None)

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.

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 designing one of the coordinate axes.

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

directionalExtremes(n, p=None)

Return extremal planes in the direction 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 list of two points on the line (p,n) thus that the planes with normal through these points define the extremal planes of the Coords.

test(dir=0, min=None, max=None, atol=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, 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.

translate(vector, distance=None, inplace=False)

Translate a Coords object.

The translation vector can be specified in one of the following ways:

  • an axis number (0,1,2),
  • a single translation vector,
  • an array of translation vectors.

If an axis number is given, a unit vector in the direction of the specified axis will be used. If an array of translation vectors is given, it should be broadcastable to the size of the Coords array. If a distance value is given, the translation vector is multiplied with this value before it is added to the coordinates.

Thus, the following lines are all equivalent:

F.translate(1)
F.translate(1,1)
F.translate([0,1,0])
F.translate([0,2,0],0.5)
rotate(angle, axis=2, around=None, inplace=False)

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

Reflect the coordinates in direction dir against plane at pos.

Default position of the plane is through the origin. Default mirror direction is the z-direction.

affine(mat, vec=None, inplace=False)

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., 1., 1.], angle_spec=Deg)

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.

hyperCylindrical(dir=[, 0, 1, 2], scale=[, 1., 1., 1.], rfunc=None, zfunc=None, angle_spec=Deg)
toCylindrical(dir=[, 0, 1, 2], angle_spec=Deg)

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., 1., 1.], angle_spec=Deg, 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., 1., 1.], angle_spec=Deg, 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=Deg)

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

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.

newmap(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: E.map(lambda x,y,z: [2*x,3*y,4*z]) is equivalent with E.scale([2,3,4])

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: E.map(lambda x,y,z: [2*x,3*y,4*z]) is equivalent with E.scale([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(P, n)

Project Coords on the plane(s) (P,n)

P and n define a plane or a set of planes by a point P and the normal n. If a set of planes, there should be exactly ncoords planes. Each of P and n thus can have shape (ncoords,3) or (1,3) or (3,).

Return a Coords with same shape as original, with the base points of the lines through all the points of self, perpendicular to the plane(s) (P,n), i.e. the projection of the points on the plane(s).

projectOnSphere(radius=1., center=[, 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., dir=0, center=[, 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..

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.e-5, atol=1.e-5, 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,
  • 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.

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 the :numpy:`append` function, 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)

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.

classmethod interpolate(clas, F, G, div)

Create interpolations between two Coords.

F and G are two Coords with the same shape. v is a list of floating point values. The result is the concatenation of the interpolations of F and G at all the values in div. An interpolation of F and G at value v is a Coords H where each coordinate Hijk is obtained from: Hijk = Fijk + v * (Gijk-Fijk). Thus, a Coords interpolate(F,G,[0.,0.5,1.0]) will contain all points of F and G and all points with mean coordinates between those of F and G.

As a convenience, if an integer is specified for div, it is taken as a number of divisions for the interval [0..1]. Thus, interpolate(F,G,n) is equivalent with interpolate(F,G,arange(0,n+1)/float(n))

The resulting Coords array has an extra axis (the first). Its shape is (n,) + F.shape, where n is the number of divisions.

Functions defined in the module coords

coords.bbox(objects)

Compute the bounding box of a list of objects.

All the objects in list should have the bbox method. The result is the eclosing bbox of all the objects in the list. Objects returning a None bbox are ignored.

coords.coordsmethod(f)

Decorator to apply a Coords method to a ‘coords’ attribute.

Many classes that model geometry use a ‘coords’ attribute to store the coordinates. This decorator can be used to apply the Coords method to that attribute, thus making the Coords transformations available to other classes.

The following lines show how to use the decorator. These lines make the ‘scale’ method of the Coords class available in your class, with the same arguments:

@coordsmethod
def scale(self,*args,**kargs):
    pass

The coordinates are changed inplane, so if you want to save the original ones, you need to copy them before you use the transformation.

coords.origin()
Return a single point with coordinates [0.,0.,0.].

Documentation

Previous topic

pyFormex reference manual

Next topic

2. formex — Formex algebra in Python

This Page