pyformex-0.8.6/ 0000755 0002115 0002115 00000000000 11705105304 013226 5 ustar bene bene 0000000 0000000 pyformex-0.8.6/pyformex.desktop 0000644 0002115 0002115 00000000350 11702357667 016512 0 ustar bene bene 0000000 0000000 [Desktop Entry] Type=Application Exec=pyformex --redirect Icon=pyformex-64x64.xpm Name=pyFormex GenericName=pyFormex 3D Geometry Designer Comment=pyFormex is a program to design, manipulate and operate on 3D geometrical structures. pyformex-0.8.6/README 0000644 0002115 0002115 00000021221 11705104656 014115 0 ustar bene bene 0000000 0000000 .. $Id: README 2150 2012-01-16 20:33:48Z bverheg $ -*- rst -*- .. This file is part of pyFormex 0.8.6 (Mon Jan 16 21:15:46 CET 2012) pyFormex is a tool for generating, manipulating and transforming 3D geometrical models by sequences of mathematical operations. Home page: http://pyformex.org Project page: http://savannah.nongnu.org/projects/pyformex/ Copyright 2004-2011 (C) Benedict Verhegghe (benedict.verhegghe@ugent.be) Distributed under the GNU General Public License version 3 or later. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. What is pyFormex? ================= pyFormex is a tool for generating, manipulating and transforming large geometrical models of 3D structures by sequences of mathematical transformations. Thanks to a powerful (Python based) scripting language, pyFormex is very well suited for the automated design of spatial frame structures. It provides a wide range of operations on surface meshes, like STL type triangulated surfaces. There are provisions to import medical scan images. pyFormex can also be used as a pre- and post-processor for Finite Element analysis programs. Finally, it might be used just for creating some nice graphics. Using pyFormex, the topology of the elements and the final geometrical form can be decoupled. Often, topology is created first and then mapped onto the geometry. Through the scripting language, the user can define any sequence of transformations, built from provided or user defined functions. This way, building parametric models becomes a natural thing. While pyFormex is still under development (see the project page at http://savannah.nongnu.org/projects/pyformex/), it already provides a fairly stable scripting language and an OpenGL GUI environment for displaying and manipulating the generated structures. Installation ============ We detail here only the installation on Linux platforms. Prerequisites ------------- Essential: - python: http://www.python.org (version 2.4 or higher; 2.5 recommended) - numpy: /http://numpy.scipy.org/ (version 1.0 or higher; 1.1 recommended) - Qt4: http://www.trolltech.com/products/qt - PyQt4: http://www.riverbankcomputing.co.uk/pyqt/index.php - PyOpenGL: http://pyopengl.sourceforge.net/ To compile the acceleration library (highly recommended!), you will also need the appropriate header Python and OpenGL header files. Further, we recommend to install the following for extended functionality: - python-gnuplot - python-doc - python-scipy - units - imagemagick - admesh For the following extensions, which are not easily packaged format, an install script is provided in this distribution. - calpy - pygl2ps - gts - tetgen Easy way to install prerequisites on Debian GNU/Linux or Ubuntu --------------------------------------------------------------- On Debian (lenny) systems (and Debian-derivatives like Ubuntu) you can install all basic prerequisites and their dependencies with the command: ``apt-get install python-qt4-gl python-numpy`` If you want to compile the acceleration library (which is highly recommended) you also need the header files: ``apt-get install python-dev libgl1-mesa-dev`` Install the extras: ``apt-get install python-gnuplot python-doc python-scipy units imagemagick admesh`` Howto install pyFormex: ----------------------- If a previous version of pyFormex was already installed on your system, you may want to remove the older version first before installing the new one. See further (Howto uninstall pyFormex) We suppose you have installed all the prerequisites and downloaded the pyformex source tarball: pyformex-VERSION.tar.gz Unpack the pyFormex source tarball: ``tar xvzf pyformex-VERSION.tar.gz`` Go to the created pyformex directory: ``cd pyformex-VERSION`` Do (with root privileges) ``python setup.py install --prefix=/usr/local`` This will install pyFormex under /usr/local/. You can change the prefix to install in some other place. After installation you can remove the directory where you unpacked the tarball. The installation procedure installs everything into a single directory, and creates a symlink to the executable in /usr/local/bin. You can use the command pyformex --whereami to find out where pyFormex is installed. If you have xdg-utils on your system, the installation procedure will also install a menu and desktop starter for pyFormex. Howto uninstall pyFormex: ------------------------- A pyFormex installation of version 0.5 or later can be removed with the command ``pyformex --remove`` and then answering 'yes' to the question. Howto install the extra packages ----------------------------------- pyFormex makes use of extra software components to enhance its functionality. While they are not required for the core operation of pyFormex, many users may want to install them. Some of these extras (admesh, units) can easily be installed from your regular distribution repositories. Some extra components however either are not available in packaged format, or the existing packages do not work together well with pyFormex. For these components, the pyFormex distribution contains an adhoc install procedure to help our users with the installation. The procedures are located in dedicated subdirectories of the pyformex-VERSION/pyformex/extra directory of the unpacked release tree. Each subdirectory contains a install script `install.sh`. To install the corresponding package, execute the script from within the subdirectory, with root privileges and with a single parameter 'all': ``(sudo) ./install.sh all`` - gl2ps: Image output to in vector formats (PS, EPS, PDF and SVG). Requires a Python interface, provided by our install procedure. - gts: Operations on triangulated surfaces. The available standard packages do not install all required files. Our install procedure will also fix some bugs. - tetgen: Create quality tetraeder meshes. - calpy: Simple finite element simulation framework. Needed for the *_calpy examples. Has to be installed from source, because is has to be compiled against the same numpy version as pyFormex itself. Running pyFormex from Subversion (SVN) sources ---------------------------------------------- If the officially released pyFormex packages are not suitable for your needs, you can try installing pyFormex from the Subversion sources. Besides the basic prerequisites (see above), you will also need to have 'Subversion' installed. The `SVN repository`_ on the developer site is accessible by anonymous SVN. The command ``svn co svn://svn.savannah.nongnu.org/pyformex/trunk/pyformex MYDIR`` will checkout the source to a local directory ``MYDIR``. Provided you have all the prerequisites installed, pyFormex can then be run directly from the checked out source with the command: ``MYDIR/pyformex/pyformex``. If you want to use the compiled accelerator library however, you will have to create it first: ``cd MYDIR/pyformex/lib; ./configure; make`` should do it. Once you have a checked-out source tree, you can easily sync it to the latest repository version by just issuing the command ``svn up`` from your checkout directory. Documentation ============= The documentation is included with the pyFormex distribution. Execute the command pyformex --whereami to find out where the pyformex files are installed. The pyformex path contains a directory doc/html with the full html ocumentation. When working with the pyFormex GUI, you can load this local documentation in your browser using the help menu, or view the online documentation at http://pyformex.org/doc. To use pyFormex, you create a script that builds a structure layout and geometry. Look at the examples to get the feeling of how it is working. Use the File->Play menu selection to display the structure. The examples and the Python source are relatively well documented. Help and Feedback ================= For any questions or feedback, please go to the pyFormex support tracker at http://savannah.nongnu.org/support/?group=pyformex If you find any bugs or malfunctions in pyFormex, please submit them to the pyFormex Bug tracker http://savannah.nongnu.org/bugs/?group=pyformex .. _`SVN repository`: http://savannah.nongnu.org/svn/?group=pyformex .. target-notes:: .. End pyformex-0.8.6/PKG-INFO 0000644 0002115 0002115 00000002611 11705105304 014323 0 ustar bene bene 0000000 0000000 Metadata-Version: 1.1 Name: pyformex Version: 0.8.6 Summary: Program to generate and transform 3D geometries from scripts. Home-page: http://pyformex.org Author: Benedict Verhegghe Author-email: benedict.verhegghe@ugent.be License: GNU General Public License (GPL) Description: pyFormex is a tool to generate, transform and manipulate large and complex geometrical models of 3D structures by sequences of mathematical operations in a Python script. Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Environment :: Console Classifier: Environment :: X11 Applications :: Qt Classifier: Intended Audience :: End Users/Desktop Classifier: Intended Audience :: Science/Research Classifier: Intended Audience :: Education Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Operating System :: POSIX :: Linux Classifier: Operating System :: POSIX Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: C Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling Classifier: Topic :: Multimedia :: Graphics :: 3D Rendering Classifier: Topic :: Scientific/Engineering :: Mathematics Classifier: Topic :: Scientific/Engineering :: Visualization Classifier: Topic :: Scientific/Engineering :: Physics Requires: numpy Requires: OpenGL Requires: PyQt4 pyformex-0.8.6/ReleaseNotes 0000644 0002115 0002115 00000010253 11705104656 015554 0 ustar bene bene 0000000 0000000 .. $Id: ReleaseNotes 2150 2012-01-16 20:33:48Z bverheg $ -*- rst -*- .. This file is part of pyFormex 0.8.6 (Mon Jan 16 21:15:46 CET 2012) pyFormex is a tool for generating, manipulating and transforming 3D geometrical models by sequences of mathematical operations. Home page: http://pyformex.org Project page: http://savannah.nongnu.org/projects/pyformex/ Copyright 2004-2011 (C) Benedict Verhegghe (benedict.verhegghe@ugent.be) Distributed under the GNU General Public License version 3 or later. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. pyFormex 0.8.6 Releasenotes ============================ This is a collection of the most prominent changes in pyFormex 0.8.6 compared to the previous release 0.8.5. There are not many new features in this release. The major change is the installation procedure, triggered by our attempts to create Debian packages. And we have a couple of bug fixes. Installation ------------ - The installation procedure now includes a configuration file (setup.py) which sets the default installation prefix to '/usr/local'. The command to install (if you accept the defaults) is thus:: python setup.py install - Secondly, if the compilation of the acceleration libraries fails, the installation procedure continues without the libraries. - Finally, it is now possible to enforce installation without the libraries, by using the command:: python setup.py install --no-accel Gui --- - Camera Settings dialog, with e.g. interactive front and back plane clipping - Save current camera settings (and restore) pyFormex 0.8.5 Releasenotes ============================ This is a collection of the most prominent changes in pyFormex 0.8.5 compared to the previous release 0.8.4. Like always, besides the new things mentioned below, we also have lots of bug fixes, code cleanup and functionality enhancements. Documentation ------------- - The official documentation is now on the new website at http://www.nongnu.org/pyformex/doc/index.html Installation ------------ - The post-install script will normally not need to run pyformex, easing the installation in sandboxed environments. Command line ------------ Configuration ------------- Core ---- - coords: new Coords methods: average, inertia, centered; new class BoundVectors; new functions pattern and xpattern - formex: the pattern and mpattern functions are replaced by the functions pattern and xpattern in the coords module. Some functions are provided for compatibility, but users are urged to transform their code to the new conventions. - geomtools: new functions pointsAtLines, pointsAtSegments, distancesPFL, distancesPFS; mode parameter to intersection* functions - Mesh: new methods: partitionByAngle, avgNodes, removeDuplicate, enhanced and unified connect, extrude and revolve methods Gui --- - canvas background can have a horizontal grading - more configuration settings can be changed from the GUI Widgets ------- Drawing ------- - faster drawing of large lists - improved Nurbs drawing Scripting --------- Plugin menus ------------ - geometry_menu: added(moved) some functionality from Surface menu, added (some) DXF import Plugins ------- - curve: Curve.endpoints method; Arc (enhanced) and Line (new) classes, PolyLine concatenation (append), BezierSpline.toMesh - dxf: added import of some entities from .DXF files: Line, Polyline, Arc External -------- - a new program *dxfparser* is provided to import (parts of) .DXF files. - pyformex-search script for searching the pyFormex source Examples -------- New examples: - Multicut - ExtrudeMesh - Connect .. End pyformex-0.8.6/setup.cfg 0000644 0002115 0002115 00000000034 11700305342 015043 0 ustar bene bene 0000000 0000000 [global] prefix=/usr/local pyformex-0.8.6/pyformex/ 0000755 0002115 0002115 00000000000 11705105304 015077 5 ustar bene bene 0000000 0000000 pyformex-0.8.6/pyformex/doc/ 0000755 0002115 0002115 00000000000 11705105304 015644 5 ustar bene bene 0000000 0000000 pyformex-0.8.6/pyformex/doc/html/ 0000755 0002115 0002115 00000000000 11705105304 016610 5 ustar bene bene 0000000 0000000 pyformex-0.8.6/pyformex/doc/html/ref/ 0000755 0002115 0002115 00000000000 11705105304 017364 5 ustar bene bene 0000000 0000000 pyformex-0.8.6/pyformex/doc/html/ref/arraytools.html 0000644 0002115 0002115 00000241207 11705104247 022464 0 ustar bene bene 0000000 0000000
These are general utility functions that depend only on the numpy array model. All pyformex modules needing numpy should import everything from this module:
from arraytools import *
Classes defined in module arraytools
Functions defined in module arraytools
Return the sine of an angle in degrees.
For convenience, this can also be used with an angle in radians, by specifying angle_spec=Rad.
>>> print sind(30), sind(pi/6,Rad)
0.5 0.5
Return the cosine of an angle in degrees.
For convenience, this can also be used with an angle in radians, by specifying angle_spec=Rad.
>>> print cosd(60), cosd(pi/3,Rad)
0.5 0.5
Return the tangens of an angle in degrees.
For convenience, this can also be used with an angle in radians, by specifying angle_spec=Rad.
Return the angle whose sine is equal to the argument.
By default, the angle is returned in Degrees. Specifying angle_spec=Rad will return the angle in radians.
>>> print arcsind(0.5), arcsind(1.0,Rad)
30.0 1.57079632679
Return the angle whose cosine is equal to the argument.
By default, the angle is returned in Degrees. Specifying angle_spec=Rad will return the angle in radians.
>>> print arccosd(0.5), arccosd(-1.0,Rad)
60.0 3.14159265359
Return the angle whose tangens is equal to the argument.
By default, the angle is returned in Degrees. Specifying angle_spec=Rad will return the angle in radians.
>>> print arctand(1.0), arctand(-1.0,Rad)
45.0 -0.785398163397
Return the angle whose sine and cosine values are given.
By default, the angle is returned in Degrees. Specifying angle_spec=Rad will return the angle in radians. This returns an angle in the range ]-180,180].
>>> print arctand2(0.0,-1.0), arctand2(-sqrt(0.5),-sqrt(0.5),Rad)
180.0 -2.35619449019
Return the smallest integer e such that 10**e > abs(f).
This returns the number of digits before the decimal point.
>>> print [ niceLogSize(a) for a in [1.3, 35679.23, 0.4, 0.00045676] ]
[1, 5, 0, -3]
Return a nice number close to f.
f is a float number, whose sign is disregarded.
A number close to abs(f) but having only 1 significant digit is returned. By default, the value is above abs(f). Setting below=True returns a value above.
Example:
>>> [ str(niceNumber(f)) for f in [ 0.0837, 0.837, 8.37, 83.7, 93.7] ]
['0.09', '0.9', '9.0', '90.0', '100.0']
>>> [ str(niceNumber(f,below=True)) for f in [ 0.0837, 0.837, 8.37, 83.7, 93.7] ]
['0.08', '0.8', '8.0', '80.0', '90.0']
Return the dot product of vectors of A and B in the direction of axis.
This multiplies the elements of the arrays A and B, and the sums the result in the direction of the specified axis. Default is the last axis. Thus, if A and B are sets of vectors in their last array direction, the result is the dot product of vectors of A with vectors of B. A and B should be broadcast compatible.
>>> A = array( [[1.0, 1.0], [1.0,-1.0], [0.0, 5.0]] )
>>> B = array( [[5.0, 3.0], [2.0, 3.0], [1.33,2.0]] )
>>> print dotpr(A,B)
[ 8. -1. 10.]
Returns the length of the vectors of A in the direction of axis.
The components of the vectors are stored along the specified array axis (default axis is the last).
Normalize the vectors of A in the direction of axis.
The components of the vectors are stored along the specified array axis (default axis is the last).
Return the (signed) length of the projection of vector of A on B.
The components of the vectors are stored along the specified array axis (default axis is the last).
Return the (signed) length of the projection of vector of A on B.
The components of the vectors are stored along the specified array axis (default axis is the last).
Return thr n-norm of the vector v.
Default is the quadratic norm (vector length). n == 1 returns the sum. n <= 0 returns the max absolute value.
Compute the value of a polynom using Horner’s rule.
Params:
Returns: float(nu,nd), nd-dimensional values of the polynom.
>>> print horner([[1.,1.,1.],[1.,2.,3.]],[0.5,1.0])
[[ 1.5 2. 2.5]
[ 2. 3. 4. ]]
Solve many systems of linear equations.
Parameters:
Returns: a float array x with same shape as b, where x[:,i,j] solves the system of linear equations A[:,:,j].x[:,i,j] = b[:,i,j].
For ndof in [1,2,3], all solutions are by default computed directly and simultaneously. If direct=False is specified, a general linear equation solver is called for each system of equations. This is also the method used if ndof > 4.
Return true if point p is inside bbox defined by points mi and ma
Returns an array flagging the elements close to target.
values is a float array, target is a float value. values and target should be broadcastable to the same shape.
The return value is a boolean array with shape of values flagging
where the values are close to target.
Two values a and b are considered close if
Create a 3D vector.
v is some data compatible with a (3)-shaped float array. Returns v as such an array.
Return a unit vector in the direction of v.
v is either an integer specifying one of the global axes (0,1,2), or a 3-element array or compatible.
Return a rotation matrix over angle, optionally around axis.
The angle is specified in degrees, unless angle_spec=Rad is specified. If axis==None (default), a 2x2 rotation matrix is returned. Else, axis should specifying the rotation axis in a 3D world. It is either one of 0,1,2, specifying a global axis, or a vector with 3 components specifying an axis through the origin. In either case a 3x3 rotation matrix is returned. Note that:
but the latter functions calls are more efficient. The result is returned as an array.
Create a rotation matrix defined by 3 points in space.
x is an array of 3 points. After applying the resulting rotation matrix to the global axes, the 0 axis becomes // to the vecors x0-x1, the 1 axis lies in the plane x0,x1,x2 and is orthogonal to x0-x1, and the 3 axis is orthogonal to the plane x0,x1,x2.
Find the transformation matrix from points x0 to x1.
x and y are each arrays of 3 non-colinear points. The return value is a tuple of a translation vector and a rotation matrix. The returned translation trl and rotationmatrix rot transform the points x thus that:
The rotation is to be applied first and should be around the first point x0. The full transformation of a Coords object is thus obtained by
(coords - x0) * rot + trl + x0 = coords * rot + (trl+x0-x0*rot)
Create a rotation matrix that rotates axis 0 to the given vector.
u is a vector representing the Return either a 3x3(default) or 4x4(if n==4) rotation matrix.
Return rotation angles from rotation matrix mat.
This returns the three angles around the global axes 0, 1 and 2. The angles are returned in degrees, unless angle_spec=Rad.
Return a rotation matrix for rotating vector vec1 to vec2
The rotation matrix will be such that the plane of vec2 and the rotated upvec will be parallel to the original upvec.
This function is like arraytools.rotMatrix(), but allows the specification of vec1. The returned matrix should be used in postmultiplication to the Coords.
Increase the length of a single array axis.
The specified axis of the array a is increased with a value add and the new elements all get the value fill.
Parameters:
Example:
>>> growAxis([[1,2,3],[4,5,6]],2)
array([[1, 2, 3, 0, 0],
[4, 5, 6, 0, 0]])
Reorder the planes of an array along the specified axis.
The elements of the array are reordered along the specified axis according to the specified order.
Parameters:
a: array_like
order: specifies how to reorder the elements. It is either one of the special string values defined below, or else it is an index holding a permutation of arange(self.nelems(). Each value specifies the index of the old element that should be placed at its position. Thus, the order values are the old index numbers at the position of the new index number.
order can also take one of the following predefined values, resulting in the corresponding renumbering scheme being generated:
Example:
>>> reorderAxis([[1,2,3],[4,5,6]],[2,0,1])
array([[3, 1, 2],
[6, 4, 5]])
Reverse the elements along a computed axis.
Example:
>>> reverseAxis([[1,2,3],[4,5,6]],0)
array([[4, 5, 6],
[1, 2, 3]])
Remark: if the axis is known in advance, it may be more efficient to use an indexing operation, like a[:,::-1,:]
Add an additional axis with length 1 to an array.
The new axis is inserted before the specified one. Default is to add it at the front.
Stack a list of arrays along a new axis.
al is a list of arrays all of the same shape. The return value is a new array with one extra axis, along which the input arrays are stacked. The position of the new axis can be specified, and is the first axis by default.
Check that an array a has the correct shape and type.
The input a is anything that can be converted into a numpy array. Either shape and/or kind can be specified. and will then be checked. The dimensions where shape contains a -1 value are not checked. The number of dimensions should match. If kind does not match, but the value is included in allow, conversion to the requested type is attempted.
Returns the array if valid; else, an error is raised.
Check that an array a has the correct size and type.
Either size and or kind can be specified. If kind does not match, but is included in allow, conversion to the requested type is attempted. Returns the array if valid. Else, an error is raised.
Check that an array has the correct dimensionality.
Returns asarray(a) if ndim < 0 or a.ndim == ndim Else, an error is raised.
Check that an array contains a set of unique integers in a given range.
This functions tests that all integer numbers in the array are within the range math:nmin <= i < nmax
nrs: an integer array of any shape. nmin: minimum allowed value. If set to None, the test is skipped. nmax: maximum allowed value + 1! If set to None, the test is skipped. Default range is [0,unlimited].
If the numbers are no unique or one of the limits is passed, an error is raised. Else, the sorted list of unique values is returned.
Read an array from an open file.
This uses numpy.fromfile() to read an array with known shape and data type from an open file. The sep parameter can be specified as in fromfile.
Write an array to an open file.
This uses numpy.tofile() to write an array to an open file. The sep parameter can be specified as in tofile.
Solve a cubiq equation using a direct method.
a,b,c,d are the (floating point) coefficients of a third degree polynomial equation:
a * x**3 + b * x**2 + c * x + d = 0
This function computes the three roots (real and complex) of this equation and returns full information about their kind, sorting order, occurrence of double roots. It uses scaling of the variables to enhance the accuracy.
The return value is a tuple (r1,r2,r3,kind), where r1,r2 and r3 are three float values and kind is an integer specifying the kind of roots.
Depending on the value of kind, the roots are defined as follows:
kind | roots |
---|---|
0 | three real roots r1 < r2 < r3 |
1 | three real roots r1 < r2 = r3 |
2 | three real roots r1 = r2 < r3 |
3 | three real roots r1 = r2 = r3 |
4 | one real root r1 and two complex conjugate roots with real part r2 and imaginary part r3; the complex roots are thus: r2+i*r3 en r2-i*r3, where i = sqrt(-1). |
If the coefficient a==0, a ValueError is raised.
Example:
>>> cubicEquation(1.,-3.,3.,-1.)
([1.0, 1.0, 1.0], 3)
Find the unique elements of an array.
This works like numpy’s unique, but uses a stable sorting algorithm. The returned index may therefore hold other entries for multiply occurring values. In such case, uniqueOrdered returns the first occurrence in the flattened array. The unique elements and the inverse index are always the same as those returned by numpy’s unique.
Parameters:
This array will be flattened if it is not already 1-D.
If True, also return the indices against ar1 that result in the unique array.
If True, also return the indices against the unique array that result in ar1.
Returns:
The unique values.
The indices of the unique values. Only provided if return_index is True.
The indices to reconstruct the original array. Only provided if return_inverse is True.
Example:
>>> a = array([2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,7,8])
>>> unique(a,True,True)
(array([1, 2, 3, 4, 5, 6, 7, 8]), array([ 7, 0, 1, 10, 3, 4, 5, 6]), array([1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 6, 7]))
>>> uniqueOrdered(a,True,True)
(array([1, 2, 3, 4, 5, 6, 7, 8]), array([7, 0, 1, 2, 3, 4, 5, 6]), array([1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 6, 7]))
Notice the difference in the 4-th entry of the second array.
Renumber an index sequentially.
Given a one-dimensional integer array with only non-negative values, and nval being the number of different values in it, and you want to replace its elements with values in the range 0..nval, such that identical numbers are always replaced with the same number and the new values at their first occurrence form an increasing sequence 0..nval. This function will give you the old numbers corresponding with each position 0..nval.
Parameters:
Example:
>>> renumberIndex([0,5,2,2,6,0])
array([0, 5, 2, 6])
>>> inverseUniqueIndex(renumberIndex([0,5,2,2,6,0]))[[0,5,2,2,6,0]]
array([0, 1, 2, 2, 3, 0])
Inverse an index.
Given a 1-D integer array with unique non-negative values, and max being the highest value in it, this function returns the position in the array of the values 0..max. Values not occurring in input index get a value -1 in the inverse index.
Parameters:
Example:
>>> inverseUniqueIndex([0,5,2,6])
array([ 0, -1, 2, -1, -1, 1, 3])
>>> inverseUniqueIndex([0,5,2,6])[[0,5,2,6]]
array([0, 1, 2, 3])
Sort an array on all its columns, from left to right.
The rows of a 2-dimensional array are sorted, first on the first column, then on the second to resolve ties, etc..
Parameters:
Example:
>>> sortByColumns([[1,2],[2,3],[3,2],[1,3],[2,3]])
array([0, 3, 1, 4, 2])
Return (the indices of) the unique rows of a 2-D array.
Parameters:
Returns:
Example:
>>> uniqueRows([[1,2],[2,3],[3,2],[1,3],[2,3]])
(array([0, 3, 1, 2]), array([0, 2, 3, 1, 2]))
>>> uniqueRows([[1,2],[2,3],[3,2],[1,3],[2,3]],permutations=True)
(array([0, 3, 1]), array([0, 2, 2, 1, 2]))
Return the index of the item nearest to target.
Parameters:
Returns: the position of the item in values that is nearest to target.
Example:
>>> argNearestValue([0.1,0.5,0.9],0.7)
1
Return the item nearest to target.
values: a list of float values
target: a single value
Return value: the item in values values that is nearest to target.
Return an inverse index.
An index is an array pointing at other items by their position. The inverse index is a collection of the reverse pointers. Negative values in the input index are disregarded.
Parameters:
An (mr,mc) shaped integer array where:
Row i of the inverse index contains all the row numbers of index that contain the number i. Because the number of rows containing the number i is usually not a constant, the resulting array will have a number of columns mc corresponding to the highest row-occurrence of any single number. Shorter rows are padded with -1 values to flag non-existing entries.
Example:
>>> inverseIndex([[0,1],[0,2],[1,2],[0,3]])
array([[ 0, 1, 3],
[-1, 0, 2],
[-1, 1, 2],
[-1, -1, 3]])
Find position of values in target.
This function finds the position in the array target of the elements from the array values.
Parameters:
Returns: an index array with the same size as values. For each number in values, the index contains the position of that value in the flattened target, or -1 if that number does not occur in target. If an element from values occurs more than once in target, it is currently undefined which of those positions is returned.
Remark that after m = matchIndex(target,values) the equality values[m] == target holds in all the non-negative positions of m.
Example:
>>> A = array([1,3,4,5,7,8,9])
>>> B = array([0,6,7,1,2])
>>> matchIndex(A,B)
array([-1, -1, 4, 0, -1])
Compute the group minimum
Computes the minimum value per group of a set of values tagged with a group number.
Parameters:
Returns:
After return, the minimum values corresponding to the groups in ugid are given by val[minpos].
>>> val = array([ 0.0, 1.0, 2.0, 3.0, 4.0, -5.0 ])
>>> gid = array([ 2, 1, 1, 6, 6, 1 ])
>>> print groupArgmin(val,gid)
(array([1, 2, 6]), array([5, 0, 3]))
Return the lengths of a set of vectors.
vec is an (n,3) shaped array holding a collection of vectors. The result is an (n,) shaped array with the length of each vector.
Normalize a set of vectors.
vec is a (n,3) shaped arrays holding a collection of vectors. The result is a tuple of two arrays:
Compute area of and normals on parallellograms formed by vec1 and vec2.
vec1 and vec2 are (n,3) shaped arrays holding collections of vectors. The result is a tuple of two arrays:
These are calculated from the cross product of vec1 and vec2, which indeed gives area * normal.
Note that where two vectors are parallel, an area zero results and an axis with components NaN.
Compute area of the parallellogram formed by a vector pair vec1,vec2.
vec1 and vec2 are (n,3) shaped arrays holding collections of vectors. The result is an (n) shaped array with the area of the parallellograms formed by each pair of vectors (vec1,vec2).
Compute vectors normal to vec1 and vec2.
vec1 and vec2 are (n,3) shaped arrays holding collections of vectors. The result is an (n,3) shaped array of unit length vectors normal to each couple (edg1,edg2).
Compute triple product vec1 . (vec2 x vec3).
vec1, vec2, vec3 are (n,3) shaped arrays holding collections of vectors. The result is a (n,) shaped array with the triple product of each set of corresponding vectors from vec1,vec2,vec3. This is also the square of the volume of the parallellepid formex by the 3 vectors. If vec1 is a unit normal, the result is also the area of the parallellogram (vec2,vec3) projected in the direction vec1.
Return the cosinus of the angle between the vectors v1 and v2.
vec1 and vec2 are (n,3) shaped arrays holding collections of vectors. The result is an (n) shaped array with the cosinus of the angle between each pair of vectors (vec1,vec2).
Return the angle (in radians) between the vectors v1 and v2.
vec1 and vec2 are (n,3) shaped arrays holding collections of vectors. The result is an (n) shaped array with the angle between each pair of vectors (vec1,vec2).
Compute the histogram of a set of data.
This function is a like numpy’s histogram function, but also returns the bin index for each individual entry in the data set.
Parameters:
Returns:
Example:
>>> histogram2([1,2,3,4,2,3,1],[1,2,3,4,5])
(array([2, 2, 2, 1]), [array([0, 6]), array([1, 4]), array([2, 5]), array([3])], array([1, 2, 3, 4, 5]))
Create a moving view along the first axis of an array
Parameters:
Returns:
An array that is a view of the original array with an extra first axis of length w.
Using swapaxes(0,axis) moving views over any axis can be created.
Examples:
>>> x=arange(10).reshape((5,2))
>>> print x
[[0 1]
[2 3]
[4 5]
[6 7]
[8 9]]
>>> print movingView(x, 3)
[[[0 1]
[2 3]
[4 5]]
<BLANKLINE>
[[2 3]
[4 5]
[6 7]]
<BLANKLINE>
[[4 5]
[6 7]
[8 9]]]
Calculate rolling sum of first axis:
>>> print movingView(x, 3).sum(axis=0)
[[ 6 9]
[12 15]
[18 21]]
Compute the moving average along the first axis of an array.
Parameters:
Returns:
An array with the moving average over n data sets along the first axis of a. The array has the same shape as a, except possibly for the length of the first axis. If neither m0 nor m1 are set, the first axis will have a length of a.shape[0] - (n-1). If both m0 and m1 are give, the first axis will have a length of a.shape[0] - (n-1) + m0 + m1. If either m0 or m1 are set and the other not, the missing value m0 or m1 will be computed thus that the return array has a first axis with length a.shape[0].
Examples:
>>> x=arange(10).reshape((5,2))
>>> print movingAverage(x,3)
[[ 2. 3.]
[ 4. 5.]
[ 6. 7.]]
>>> print movingAverage(x,3,2)
[[ 0. 1. ]
[ 0.66666667 1.66666667]
[ 2. 3. ]
[ 4. 5. ]
[ 6. 7. ]]
Create an array with random values between min and max
This module defines some functions that can be used to save the OpenGL rendering and the pyFormex GUI to image files. There are even provisions for automatic saving to a series of files and creating a movie from these images.
Classes defined in module image
Functions defined in module image
Initialize the image module.
Return a list of the valid image formats.
image formats are lower case strings as ‘png’, ‘gif’, ‘ppm’, ‘eps’, etc. The available image formats are derived from the installed software.
Checks image format; if verbose, warn if it is not.
Returns the image format, or None if it is not OK.
Determine the image format from an extension.
The extension may or may not have an initial dot and may be in upper or lower case. The format is equal to the extension characters in lower case. If the supplied extension is empty, the default format ‘png’ is returned.
Save the rendering on canvas as an image file.
canvas specifies the qtcanvas rendering window. fn is the name of the file fmt is the image file format
Save a window as an image file.
This function needs a filename AND format. If a window is specified, the named window is saved. Else, the main pyFormex window is saved.
Save the main pyFormex window as an image file.
This function needs a filename AND format. This is an alternative for save_window, by grabbin it from the root window, using save_rect. This allows us to grab the border as well.
Save a rectangular part of the screen to a an image file.
Saves an image to file or Starts/stops multisave mode.
With a filename and multi==False (default), the current viewport rendering is saved to the named file.
With a filename and multi==True, multisave mode is started. Without a filename, multisave mode is turned off. Two subsequent calls starting multisave mode without an intermediate call to turn it off, do not cause an error. The first multisave mode will implicitely be ended before starting the second.
In multisave mode, each call to saveNext() will save an image to the next generated file name. Filenames are generated by incrementing a numeric part of the name. If the supplied filename (after removing the extension) has a trailing numeric part, subsequent images will be numbered continuing from this number. Otherwise a numeric part ‘-000’ will be added to the filename.
If window is True, the full pyFormex window is saved. If window and border are True, the window decorations will be included. If window is False, only the current canvas viewport is saved.
If hotkey is True, a new image will be saved by hitting the ‘S’ key. If autosave is True, a new image will be saved on each execution of the ‘draw’ function. If neither hotkey nor autosave are True, images can only be saved by executing the saveNext() function from a script.
If no format is specified, it is derived from the filename extension. fmt should be one of the valid formats as returned by imageFormats()
If verbose=True, error/warnings are activated. This is usually done when this function is called from the GUI.
Saves an image to file or Starts/stops multisave mode.
With a filename and multi==False (default), the current viewport rendering is saved to the named file.
With a filename and multi==True, multisave mode is started. Without a filename, multisave mode is turned off. Two subsequent calls starting multisave mode without an intermediate call to turn it off, do not cause an error. The first multisave mode will implicitely be ended before starting the second.
In multisave mode, each call to saveNext() will save an image to the next generated file name. Filenames are generated by incrementing a numeric part of the name. If the supplied filename (after removing the extension) has a trailing numeric part, subsequent images will be numbered continuing from this number. Otherwise a numeric part ‘-000’ will be added to the filename.
If window is True, the full pyFormex window is saved. If window and border are True, the window decorations will be included. If window is False, only the current canvas viewport is saved.
If hotkey is True, a new image will be saved by hitting the ‘S’ key. If autosave is True, a new image will be saved on each execution of the ‘draw’ function. If neither hotkey nor autosave are True, images can only be saved by executing the saveNext() function from a script.
If no format is specified, it is derived from the filename extension. fmt should be one of the valid formats as returned by imageFormats()
If verbose=True, error/warnings are activated. This is usually done when this function is called from the GUI.
In multisave mode, saves the next image.
This is a quiet function that does nothing if multisave was not activated. It can thus safely be called on regular places in scripts where one would like to have a saved image and then either activate the multisave mode or not.
Save the current rendering as an icon.
Returns True if autosave multisave mode is currently on.
Use this function instead of directly accessing the autosave variable.
Create a movie from a saved sequence of images.
encoder is one of: ‘ffmpeg, mencoder, convert’
Create a movie from the pyFormex window.
make[2]: Map ‘/home/bene/prj’ wordt binnengegaan make[2]: Map ‘/home/bene/prj’ wordt verlaten .. $Id$ -- rst -- .. pyformex reference manual — menu .. CREATED WITH py2rst.py: DO NOT EDIT
This module contains functions to use bitmap images as colors on a pyFormex geometry.
Classes defined in module imagecolor
Functions defined in module imagecolor
Convert a bitmap image to corresponding OpenGL colors.
im is a QImage or any data from which a QImage can be initialized. The image RGB colors are converted to OpenGL colors. The return value is a (w,h,3) shaped array of values in the range 0.0 to 1.0. By default the image is flipped upside-down because the vertical OpenGL axis points upwards, while bitmap images are stored downwards.
Classes defined in module datareader
Functions defined in module datareader
Match a floating point number at the beginning of a string
If the beginning of the string matches a floating point number, a list is returned with the float and the remainder of the string; if not, None is returned. Example: splitFloat('123e4rt345e6') returns [1230000.0, 'rt345e6']
Read data from a line matching the ‘type’ specification.
This is a powerful function for reading, interpreting and converting numerical data from a string. Fields in the string s are separated by commas. The ‘type’ argument is a list where each element specifies how the corresponding field should be interpreted. Available values are ‘int’, ‘float’ or some unit (‘kg’, ‘m’, etc.). If the type field is ‘int’ or ‘float’, the data field is converted to the matching type. If the type field is a unit, the data field should be a number and a unit separated by space or not, or just a number. If it is just a number, its value is returned unchanged (as float). If the data contains a unit, the number is converted to the requested unit. It is an error if the datafield holds a non-conformable unit. The function returns a list of ints and/or floats (without the units). If the number of data fields is not equal to the number of type specifiers, the returned list will correspond to the shortest of both and the surplus data or types are ignored, UNLESS the strict flag has been set, in which case a RuntimError is raised. Example:
readData('12, 13, 14.5e3, 12 inch, 1hr, 31kg ', ['int','float','kg','cm','s'])
returns [12, 13.0, 14500.0, 30.48, 3600.0]
..warning
You need to have the GNU ``units`` command installed for the unit
conversion to work.
This is a plugin for pyFormex. (C) 2002 Benedict Verhegghe
See the Section2D example for an example of its use.
Classes defined in module section2d
A class describing a general 2D section.
The 2D section is the area inside a closed curve in the (x,y) plane. The curve is decribed by a finite number of points and by straight segments connecting them.
Functions defined in module section2d
Compute characteristics of plane sections.
The plane sections are described by their circumference, consisting of a sequence of straight segments. The segment end point data are gathered in a plex-2 Formex. The segments should form a closed curve. The z-value of the coordinates does not have to be specified, and will be ignored if it is. The resulting path through the points should rotate positively around the z axis to yield a positive surface.
The return value is a dict with the following characteristics:
Computes extended section characteristics for the given section.
S is a dict with section basic section characteristics as returned by sectionChar(). This function computes and returns a dict with the following:
Compute the principal values and directions of a 2D tensor.
Returns a tuple with three values:
This module defines a specialized array class for representing nodal connectivity. This is e.g. used in mesh models, where geometry is represented by a set of numbered points (nodes) and the geometric elements are described by refering to the node numbers. In a mesh model, points common to adjacent elements are unique, and adjacency of elements can easily be detected from common node numbers.
Classes defined in module connectivity
A class for handling element/node connectivity.
A connectivity object is a 2-dimensional integer array with all non-negative values. Each row of the array defines an element by listing the numbers of its lower entity types. A typical use is a Mesh object, where each element is defined in function of its nodes. While in a Mesh the word ‘node’ will normally refer to a geometrical point, here we will use ‘node’ for the lower entity whatever its nature is. It doesn’t even have to be a geometrical entity.
The current implementation limits a Connectivity object to numbers that are smaller than 2**31.
In a row (element), the same node number may occur more than once, though usually all numbers in a row are different. Rows containing duplicate numbers are called degenerate elements. Rows containing the same node sets, albeit different permutations thereof, are called duplicates.
A new Connectivity object is created with the following syntax
Connectivity(data=[],dtyp=None,copy=False,nplex=0)
Parameters:
Example:
>>> print Connectivity([[0,1,2],[0,1,3],[0,3,2],[0,5,3]])
[[0 1 2]
[0 1 3]
[0 3 2]
[0 5 3]]
Return the number of elements in the Connectivity table.
Example:
>>> Connectivity([[0,1,2],[0,1,3],[0,3,2],[0,5,3]]).nelems()
4
Return the plexitude of the elements in the Connectivity table.
Example:
>>> Connectivity([[0,1,2],[0,1,3],[0,3,2],[0,5,3]]).nplex()
3
Format a Connectivity table
Flag the degenerate elements (rows).
A degenerate element is a row which contains at least two equal values.
Example:
>>> Connectivity([[0,1,2],[0,1,1],[0,3,2]]).testDegenerate()
array([False, True, False], dtype=bool)
Return a list with the numbers of the degenerate elements.
Example:
>>> Connectivity([[0,1,2],[0,1,1],[0,3,2]]).listDegenerate()
array([1])
Return a list with the numbers of the non-degenerate elements.
Example:
>>> Connectivity([[0,1,2],[0,1,1],[0,3,2]]).listNonDegenerate()
array([0, 2])
Remove the degenerate elements from a Connectivity table.
Degenerate elements are rows with repeating values. Returns a Connectivity with the degenerate elements removed.
Example:
>>> Connectivity([[0,1,2],[0,1,1],[0,3,2]]).removeDegenerate()
Connectivity([[0, 1, 2],
[0, 3, 2]])
Reduce degenerate elements to lower plexitude elements.
This will try to reduce the degenerate elements of the Connectivity to a lower plexitude. This is only possible if an element type was set in the Connectivity. This function uses the data of the Element database in elements.
If a target element type is given, only the reductions to that element type are performed. Else, all the target element types for which a reduction scheme is available, will be tried.
Returns:
A list of Connectivities of which the first one contains the originally non-degenerate elements and the last one contains the elements that could not be reduced and may be empty. If the original Connectivity does not have an element type set, or the element type does not have any reduction schemes defined, a list with only the original is returned.
Remark: If the Connectivity is part of a Mesh, you should use the Mesh.reduceDegenerate method instead, as that one will preserve the property numbers into the resulting Meshes.
Example:
>>> C = Connectivity([[0,1,2],[0,1,1],[0,3,2]],eltype='line3')
>>> print C.reduceDegenerate()
[Connectivity([[0, 1]]), Connectivity([[0, 1, 2],
[0, 3, 2]])]
Test the Connectivity list for duplicates.
By default, duplicates are elements that consist of the same set of nodes, in any particular order. Setting permutations to False will only find the duplicate rows that have matching values at every position.
This function returns a tuple with two arrays:
Example:
>>> Connectivity([[0,1,2],[0,2,1],[0,3,2]]).testDuplicate()
(array([0, 1, 2]), Connectivity([ True, False, True], dtype=bool))
Return a list with the numbers of the unique elements.
Example:
>>> Connectivity([[0,1,2],[0,2,1],[0,3,2]]).listUnique()
array([0, 2])
Return a list with the numbers of the duplicate elements.
Example:
>>> Connectivity([[0,1,2],[0,2,1],[0,3,2]]).listDuplicate()
array([1])
Remove duplicate elements from a Connectivity list.
By default, duplicates are elements that consist of the same set of nodes, in any particular order. Setting permutations to False will only remove the duplicate rows that have matching values at matching positions.
Returns a new Connectivity with the duplicate elements removed.
Example:
>>> Connectivity([[0,1,2],[0,2,1],[0,3,2]]).removeDuplicate()
Connectivity([[0, 1, 2],
[0, 3, 2]])
Reorder the elements of a Connectivity in a specified order.
This does not actually reorder the elements itself, but returns an index with the order of the rows (elements) in the connectivity table that meets the specified requirements.
Parameters:
order: specifies how to reorder the elements. It is either one of the special string values defined below, or else it is an index with length equal to the number of elements. The index should be a permutation of the numbers in range(self.nelems(). Each value gives of the number of the old element that should be placed at this position. Thus, the order values are the old element numbers on the position of the new element number.
order can also take one of the following predefined values, resulting in the corresponding renumbering scheme being generated:
Example:
>>> A = Connectivity([[1,2],[2,3],[3,0],[0,1]])
>>> A[A.reorder('reverse')]
Connectivity([[0, 1],
[3, 0],
[2, 3],
[1, 2]])
>>> A.reorder('nodes')
array([3, 2, 0, 1])
>>> A[A.reorder([2,3,0,1])]
Connectivity([[3, 0],
[0, 1],
[1, 2],
[2, 3]])
Return the inverse index of a Connectivity table.
This returns the inverse index of the Connectivity, as computed by arraytools.inverseIndex(). See
Example:
>>> Connectivity([[0,1,2],[0,1,3],[0,3,2]]).inverse()
array([[ 0, 1, 2],
[-1, 0, 1],
[-1, 0, 2],
[-1, 1, 2]])
Return a table of adjacent items.
Returns an element adjacency table (kind=’e’) or node adjacency table (kind=’n’).
An element i is said to be ajacent to element j, if the two elements have at least one common node.
A node i is said to be adjacent to node j, if there is at least one element containing both nodes.
Parameters:
Returns: an integer array with shape (nr,nc), where row i holds a sorted list of all the items that are adjacent to item i, padded with -1 values to create an equal list length for all items.
Example:
>>> Connectivity([[0,1],[0,2],[1,3],[0,5]]).adjacency('e')
array([[ 1, 2, 3],
[-1, 0, 3],
[-1, -1, 0],
[-1, 0, 1]])
>>> Connectivity([[0,1],[0,2],[1,3],[0,5]]).adjacency('n')
array([[ 1, 2, 5],
[-1, 0, 3],
[-1, -1, 0],
[-1, -1, 1],
[-1, -1, -1],
[-1, -1, 0]])
>>> Connectivity([[0,1,2],[0,1,3],[2,4,5]]).adjacency('n')
array([[-1, 1, 2, 3],
[-1, 0, 2, 3],
[ 0, 1, 4, 5],
[-1, -1, 0, 1],
[-1, -1, 2, 5],
[-1, -1, 2, 4]])
Return a Connectivity containing subsets of the nodes.
Parameters:
Returns a Connectivity object with shape (self.nelems*selector.nelems,selector.nplex). This function does not collapse the duplicate elements. The eltype of the result is equal to that of the selector, possibly None.
Example:
>>> Connectivity([[0,1,2],[0,2,1],[0,3,2]]).selectNodes([[0,1],[0,2]])
Connectivity([[0, 1],
[0, 2],
[0, 2],
[0, 1],
[0, 3],
[0, 2]])
Insert an extra hierarchical level in a Connectivity table.
A Connectivity table identifies higher hierchical entities in function of lower ones. This method inserts an extra hierarchical level. For example, if you have volumes defined in function of points, you can insert an intermediate level of edges, or faces. Multiple intermediate level entities may be created from each element.
Parameters:
Return value: a tuple of two Connectivities hi,`lo`, where:
Intermediate level items that consist of the same items in any permutation order are collapsed to single items. The low level items respect the numbering order inside the original elements, but it is undefined which of the collapsed sequences is returned.
Because the precise order of the data in the collapsed rows is lost, it is in general not possible to restore the exact original table from the two result tables. See however Mesh.getBorder() for an application where an inverse operation is possible, because the border only contains unique rows. See also Mesh.combine(), which is an almost inverse operation for the general case, if the selector is complete. The resulting rows may however be permutations of the original.
Example:
>>> Connectivity([[0,1,2],[0,2,1],[0,3,2]]).insertLevel([[0,1],[1,2],[2,0]])
(Connectivity([[0, 3, 1],
[1, 3, 0],
[2, 4, 1]]), Connectivity([[0, 1],
[2, 0],
[0, 3],
[1, 2],
[3, 2]]))
Combine two hierarchical Connectivity levels to a single one.
self and lo are two hierarchical Connectivity tables, representing higher and lower level respectively. This means that the elements of self hold numbers which point into lo to obtain the lowest level items.
In the current implementation, the plexitude of lo should be 2!
As an example, in a structure of triangles, hi could represent triangles defined by 3 edges and lo could represent edges defined by 2 vertices. This method will then result in a table with plexitude 3 defining the triangles in function of the vertices.
This is the inverse operation of insertLevel() with a selector which is complete. The algorithm only works if all vertex numbers of an element are unique.
Example:
>>> hi,lo = Connectivity([[0,1,2],[0,2,1],[0,3,2]]).insertLevel([[0,1],[1,2],[2,0]])
>>> hi.combine(lo)
Connectivity([[0, 1, 2],
[0, 2, 1],
[0, 3, 2]])
Resolve the connectivity into plex-2 connections.
Creates a Connectivity table with a plex-2 (edge) connection between any two nodes that are connected to a common element.
There is no point in resolving a plexitude 2 structure. Plexitudes lower than 2 can not be resolved.
Returns a plex-2 Connectivity with all connections between node pairs. In each element the nodes are sorted.
Example:
>>> print([ i for i in combinations(range(3),2) ])
[(0, 1), (0, 2), (1, 2)]
>>> Connectivity([[0,1,2],[0,2,1],[0,3,2]]).resolve()
Connectivity([[0, 1],
[0, 2],
[0, 3],
[1, 2],
[2, 3]])
Functions defined in module connectivity
Sort an adjacency table.
An adjacency table is an integer array where each row lists the numbers of the items that are connected to the item with number equal to the row index. Rows are padded with -1 value to create rows of equal length.
This function sorts the rows of the adjacency table in ascending order and removes all columns containing only -1 values.
Paramaters:
Returns: an integer array with shape (adj.shape[0],maxc), with maxc <= adj.shape[1], where the rows are sorted in ascending order and where columns with only -1 values are removed.
Example:
>>> a = array([[ 0, 2, 1, -1],
... [-1, 3, 1, -1],
... [ 3, -1, 0, 1],
... [-1, -1, -1, -1]])
>>> sortAdjacency(a)
array([[ 0, 1, 2],
[-1, 1, 3],
[ 0, 1, 3],
[-1, -1, -1]])
Reduce an adjacency table.
An adjacency table is an integer array where each row lists the numbers of the items that are connected to the item with number equal to the row index. Rows are padded with -1 value to create rows of equal length.
A reduced adjacency table is one where each row:
and that has at least one row without -1 value.
Paramaters:
Returns: an integer array with shape (adj.shape[0],maxc), with maxc <= adj.shape[1], where row i retains the unique non-negative numbers of the original array except the valu i, and is possibly padded with -1 values.
Example:
>>> a = array([[ 0, 0, 0, 1, 2, 5],
... [-1, 0, 1, -1, 1, 3],
... [-1, -1, 0, -1, -1, 2],
... [-1, -1, 1, -1, -1, 3],
... [-1, -1, -1, -1, -1, -1],
... [-1, -1, 0, -1, -1, 5]])
>>> reduceAdjacency(a)
array([[ 1, 2, 5],
[-1, 0, 3],
[-1, -1, 0],
[-1, -1, 1],
[-1, -1, -1],
[-1, -1, 0]])
Find a single path of connected line elems.
This function is intended as a helper function for connectedLineElems(). It should probably not be used directly, because, as a side-effect, it changes the data in the elems argument. connectedLineElems() does not have this inconvenience.
The function searches a Connectivity table for a chain of elements in which the first node of all but the first element is equal to the last node of the previous element. To create such a chain, elements may be reordered and the node sequence of an element may be reversed.
Parameters:
Connectivity. The result will not necessarily be the longest path. It will however contain the first element of the input table.
As a side-effect, all elements contained in the output chain will have their entries in the input table elems changed to -1.
Example:
>>> findConnectedLineElems([[0,1],[1,2],[0,4],[4,2]])
Connectivity([[0, 1],
[1, 2],
[2, 4],
[4, 0]])
>>> findConnectedLineElems([[0,1],[1,2],[0,4]])
Connectivity([[2, 1],
[1, 0],
[0, 4]])
>>> C = Connectivity([[0,1],[0,2],[0,3],[4,5]])
>>> findConnectedLineElems(C)
Connectivity([[ 1, 0],
[ 0, 2],
[-1, -1],
[-1, -1]])
>>> print C
[[-1 -1]
[-1 -1]
[ 0 3]
[ 4 5]]
Partition a segmented curve into connected segments.
The input argument is a (nelems,2) shaped array of integers. Each row holds the two vertex numbers of a single line segment.
The return value is a list of (nsegi,2) shaped array of integers.
Example:
>>> connectedLineElems([[0,1],[1,2],[0,4],[4,2]])
[Connectivity([[0, 1],
[1, 2],
[2, 4],
[4, 0]])]
>>> connectedLineElems([[0,1],[1,2],[0,4]])
[Connectivity([[2, 1],
[1, 0],
[0, 4]])]
>>> connectedLineElems([[0,1],[0,2],[0,3],[4,5]])
[Connectivity([[1, 0],
[0, 2]]), Connectivity([[0, 3]]), Connectivity([[4, 5]])]
>>> connectedLineElems([[0,1,2],[2,0,3],[0,3,1],[4,5,2]])
[Connectivity([[3, 0, 2],
[2, 1, 0],
[0, 3, 1]]), Connectivity([[4, 5, 2]])]
Create adjacency arrays for 2-node elements.
elems is a (nr,2) shaped integer array. The result is a list of adjacency arrays, where row i of adjacency array j holds a sorted list of the nodes that are connected to node i via a shortest path of j elements, padded with -1 values to create an equal list length for all nodes. This is: [adj0, adj1, ..., adjj, ... , adjn] with n=nsteps.
Example:
>>> adjacencyArrays([[0,1],[1,2],[2,3],[3,4],[4,0]],3)
[array([[0],
[1],
[2],
[3],
[4]]), array([[1, 4],
[0, 2],
[1, 3],
[2, 4],
[0, 3]]), array([[2, 3],
[3, 4],
[0, 4],
[0, 1],
[1, 2]]), array([], shape=(5, 0), dtype=int64)]
The widgets in this module were primarily created in function of the pyFormex GUI. The user can apply them to change the GUI or to add interactive widgets to his scripts. Of course he can also use all the Qt widgets directly.
Classes defined in module widgets
A single input item.
This is the base class for widgets holding a single input item. A single input item is any item that is treated as a unit and refered to by a single name.
This base class is rarely used directly. Most of the components of an InputDialog are subclasses of hereof, each specialized in some form of input data or representation. There is e.g. an InputInteger class to input an integer number and an InputString for the input of a string. The base class groups the functionality that is common to the different input widgets.
The InputItem widget holds a horizontal layout box (QHBoxLayout) to group its its components. In most cases there are just two components: a label with the name of the field, and the actual input field. Other components, such as buttons or sliders, may be added. This is often done in subclasses.
The constructor has one required argument: name. Other (optional) positional parameters are passed to the QtGui.QWidget constructor. The remaining keyword parameters are options that somehow change the default behavior of the InputItem class.
Parameters:
Subclasses should have an __init__() method which first constructs a proper widget for the input field, and stores it in the attribute self.input. Then the baseclass should be properly initialized, passing any optional parameters:
self.input = SomeInputWidget()
InputItem.__init__(self,name,*args,**kargs)
Subclasses should also override the following default methods of the InputItem base class:
Subclasses are allowed to NOT have a self.input attribute, IFF they redefine both the value() and the setValue() methods.
Subclasses can set validators on the input, like:
self.input.setValidator(QtGui.QIntValidator(self.input))
Subclasses can define a show() method e.g. to select the data in the input field on display of the dialog.
Return the name of the InputItem.
Return the displayed text of the InputItem.
Return the widget’s value.
Change the widget’s value.
An unchangeable input field with a label in front.
It is just like an InputString, but the text can not be edited. The value should be a simple string without newlines.
There are no specific options.
Return the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
Change the widget’s value.
An unchangeable information field.
The value is displayed as a string, but may contain more complex texts.
By default, the text format will be guessed to be either plain text, ReStructuredText ot html. Specify plain=True to display in plain text.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
Return the widget’s value.
A string input field with a label in front.
If the type of value is not a string, the input string will be eval’ed before returning.
Options:
Select all text on first display.
Return the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
Change the widget’s value.
A scrollable text input field with a label in front.
By default, the text format will be guessed to be either plain text, ReStructuredText ot html.
Specify plain=True to display in plain text.
If the type of value is not a string, the input text will be eval’ed before returning.
Select all text on first display.
Return the widget’s value.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
A boolean input item.
Creates a new checkbox for the input of a boolean value.
Displays the name next to a checkbox, which will initially be set if value evaluates to True. (Does not use the label) The value is either True or False,depending on the setting of the checkbox.
Return the displayed text.
Return the widget’s value.
Change the widget’s value.
Return the name of the InputItem.
A list selection InputItem.
A list selection is a widget allowing the selection of zero, one or more items from a list.
choices is a list/tuple of possible values. default is the initial/default list of selected items. Values in default that are not in the choices list, are ignored. If default is None or an empty list, nothing is selected initially.
By default, the user can select multiple items and the return value is a list of all currently slected items. If single is True, only a single item can be selected.
If check is True, all items have a checkbox and only the checked items are returned. This option sets single==False.
Mark the specified items as selected or not.
Mark the specified items as checked or not.
Return the widget’s value.
Change the widget’s value.
Mark all items as selected/checked.
Mark all items as not selected/checked.
Return the name of the InputItem.
Return the displayed text of the InputItem.
A combobox InputItem.
A combobox is a widget allowing the selection of an item from a drop down list.
choices is a list/tuple of possible values. default is the initial/default choice. If default is not in the choices list, it is prepended. If default is None, the first item of choices is taken as the default.
The choices are presented to the user as a combobox, which will initially be set to the default value.
An optional onselect function may be specified, which will be called whenever the current selection changes.
Return the widget’s value.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
A radiobuttons InputItem.
Radio buttons are a set of buttons used to select a value from a list.
choices is a list/tuple of possible values. default is the initial/default choice. If default is not in the choices list, it is prepended. If default is None, the first item of choices is taken as the default.
The choices are presented to the user as a hbox with radio buttons, of which the default will initially be pressed. If direction == ‘v’, the options are in a vbox.
Return the widget’s value.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
A pushbuttons InputItem.
Creates pushbuttons for the selection of a value from a list.
choices is a list/tuple of possible values. default is the initial/default choice. If default is not in the choices list, it is prepended. If default is None, the first item of choices is taken as the default.
The choices are presented to the user as a hbox with radio buttons, of which the default will initially be selected. If direction == ‘v’, the options are in a vbox.
Change the text on button index.
Change the icon on button index.
Return the widget’s value.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
An integer input item.
Options:
Select all text on first display.
Return the widget’s value.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
An float input item.
Select all text on first display.
Return the widget’s value.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
An integer input item using a slider.
Options:
Return the name of the InputItem.
Return the displayed text of the InputItem.
Select all text on first display.
Return the widget’s value.
Change the widget’s value.
A float input item using a slider.
Options:
Return the name of the InputItem.
Return the displayed text of the InputItem.
Select all text on first display.
Return the widget’s value.
Change the widget’s value.
A 3D point/vector input item.
Return the widget’s value.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
A vector of int values.
Return the widget’s value.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
A button input item.
The button input field is a button displaying the current value. Clicking on the button executes a function responsible for changing the value.
Extra parameters:
Return the widget’s value.
Set the value by calling the button’s func
Return the name of the InputItem.
Return the displayed text of the InputItem.
Change the widget’s value.
A color input item. Creates a new color input field with a label in front.
The color input field is a button displaying the current color. Clicking on the button opens a color dialog, and the returned value is set in the button.
Change the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
Return the widget’s value.
An input item to select a font.
Return the widget’s value.
Return the name of the InputItem.
Return the displayed text of the InputItem.
Change the widget’s value.
An input item containing any other widget.
The widget should have:
The return value of this item is an ODict.
Return the displayed text.
Change the widget’s value.
Return the name of the InputItem.
Return the widget’s value.
An input form.
The input form is a layout box in which the items are layed out vertically. The layout can also contain any number of tab widgets in which items can be layed out using tab pages.
A boxed group of InputItems.
Return the widget’s value.
Change the widget’s value.
A tab page in an input form.
A dialog widget to interactively set the value of one or more items.
Overview
The pyFormex user has full access to the Qt4 framework on which the GUI was built. Therefore he can built input dialogs as complex and powerful as he can imagine. However, directly dealing with the Qt4 libraries requires some skills and, for simple input widgets, more effort than needed.
The InputDialog class presents a unified system for quick and easy creation of common dialog types. The provided dialog can become quite sophisticated with tabbed pages, groupboxes and custom widgets. Both modal and modeless (non-modal) dialogs can be created.
Items
Each basic input item is a dictionary, where the fields have the following meaning:
Other arguments
Add input items to form.
items is a list of input item data layout is the widget layout where the input widgets will be added
Add a Tab page of input items.
Add a group of input items.
Add a single input item to the form.
Hide the dialog and set the result code to TIMEOUT
Returns True if the result code was set to TIMEOUT
Show the dialog.
For a non-modal dialog, the user has to call this function to display the dialog. For a modal dialog, this is implicitely executed by getResult().
If a timeout is given, start the timeout timer.
Update the dialog’s return value from the field values.
This function is connected to the ‘accepted()’ signal. Modal dialogs should normally not need to call it. In non-modal dialogs however, you can call it to update the results without having to raise the accepted() signal (which would close the dialog).
Update a dialog from the data in given dictionary.
d is a dictionary where the keys are field names in the dialog. The values will be set in the corresponding input items.
Get the results from the input dialog.
This fuction is used to present a modal dialog to the user (i.e. a dialog that must be ended before the user can continue with the program. The dialog is shown and user interaction is processed. The user ends the interaction either by accepting the data (e.g. by pressing the OK button or the ENTER key) or by rejecting them (CANCEL button or ESC key). On accept, a dictionary with all the fields and their values is returned. On reject, an empty dictionary is returned.
If a timeout (in seconds) is given, a timer will be started and if no user input is detected during this period, the input dialog returns with the default values set. A value 0 will timeout immediately, a negative value will never timeout. The default is to use the global variable input_timeout.
The result() method can be used to find out how the dialog was ended. Its value will be one of ACCEPTED, REJECTED ot TIMEOUT.
Get the results from the input dialog.
This fuction is used to present a modal dialog to the user (i.e. a dialog that must be ended before the user can continue with the program. The dialog is shown and user interaction is processed. The user ends the interaction either by accepting the data (e.g. by pressing the OK button or the ENTER key) or by rejecting them (CANCEL button or ESC key). On accept, a dictionary with all the fields and their values is returned. On reject, an empty dictionary is returned.
If a timeout (in seconds) is given, a timer will be started and if no user input is detected during this period, the input dialog returns with the default values set. A value 0 will timeout immediately, a negative value will never timeout. The default is to use the global variable input_timeout.
The result() method can be used to find out how the dialog was ended. Its value will be one of ACCEPTED, REJECTED ot TIMEOUT.
A file selection dialog.
You can specify a default path/filename that will be suggested initially. If a pattern is specified, only matching files will be shown. A pattern can be something like Images (*.png *.jpg) or a list of such strings. Default mode is to accept any filename. You can specify exist=True to accept only existing files. Or set exist=True and multi=True to accept multiple files. If dir==True, a single existing directory is asked.
Ask for a filename by user interaction.
Return the filename selected by the user. If the user hits CANCEL or ESC, None is returned.
A file selection dialog specialized for opening projects.
Ask for a filename by user interaction.
Return the filename selected by the user. If the user hits CANCEL or ESC, None is returned.
A dialog for saving to an image file.
The dialog contains the normal file selection widget plus some extra fields to set the Save Image parameters:
Ask for a filename by user interaction.
Return the filename selected by the user. If the user hits CANCEL or ESC, None is returned.
A dialog for selecting one or more items from a list.
This is a convenient class which constructs an input dialog with a single input item: an InputList. It allows the user to select one or more items from a list. The constructor supports all arguments of the InputDialog and the InputList classes. The return value is the value of the InputList, not the result of the InputDialog.
Mark the specified items as selected.
Return the selected items.
Show the modal dialog and return the list of selected values.
If the user cancels the selection operation, the return value is None. Else, the result is always a list, possibly empty or with a single value.
Add input items to form.
items is a list of input item data layout is the widget layout where the input widgets will be added
Add a Tab page of input items.
Add a group of input items.
Add a single input item to the form.
Hide the dialog and set the result code to TIMEOUT
Returns True if the result code was set to TIMEOUT
Show the dialog.
For a non-modal dialog, the user has to call this function to display the dialog. For a modal dialog, this is implicitely executed by getResult().
If a timeout is given, start the timeout timer.
Update the dialog’s return value from the field values.
This function is connected to the ‘accepted()’ signal. Modal dialogs should normally not need to call it. In non-modal dialogs however, you can call it to update the results without having to raise the accepted() signal (which would close the dialog).
Update a dialog from the data in given dictionary.
d is a dictionary where the keys are field names in the dialog. The values will be set in the corresponding input items.
Get the results from the input dialog.
This fuction is used to present a modal dialog to the user (i.e. a dialog that must be ended before the user can continue with the program. The dialog is shown and user interaction is processed. The user ends the interaction either by accepting the data (e.g. by pressing the OK button or the ENTER key) or by rejecting them (CANCEL button or ESC key). On accept, a dictionary with all the fields and their values is returned. On reject, an empty dictionary is returned.
If a timeout (in seconds) is given, a timer will be started and if no user input is detected during this period, the input dialog returns with the default values set. A value 0 will timeout immediately, a negative value will never timeout. The default is to use the global variable input_timeout.
The result() method can be used to find out how the dialog was ended. Its value will be one of ACCEPTED, REJECTED ot TIMEOUT.
A generic dialog widget.
The dialog is formed by a number of widgets stacked in a vertical box layout. At the bottom is a horizontal button box with possible actions.
A table model that represent data as a two-dimensional array of items.
data is any tabular data organized in a fixed number of rows and colums. This means that an item at row i and column j can be addressed as data[i][j]. Optional lists of column and row headers can be specified.
Return the TableModel flags.
A TableModel specialized for represents 2D array data.
Return the TableModel flags.
A widget to show/edit a two-dimensional array of items.
Present a list of widgets as a single tabbed widget.
A dialog widget to show/edit a two-dimensional array of items.
A convenience class representing a Table within a dialog.
A message box is a widget displaying a short text for the user.
The message box displays a text, an optional icon depending on the level and a number of push buttons.
When the MessageBox is displayed with the getResult() method, a modal dialog is created, i.e. the user will have to click a button or hit the ESC key before he can continue.
If you want a modeless dialog, allowing the user to continue while the message stays open, use the show() mehod to display it.
Add a check field at the bottom of the layout.
Display the message box and wait for user to click a button.
This will show the message box as a modal dialog, so that the user has to click a button (or hit the ESC key) before he can continue. Returns the text of the button that was clicked or an empty string if ESC was hit.
A message box is a widget displaying a short text for the user.
The message box displays a text, an optional icon depending on the level and a number of push buttons.
When the MessageBox is displayed with the getResult() method, a modal dialog is created, i.e. the user will have to click a button or hit the ESC key before he can continue.
If you want a modeless dialog, allowing the user to continue while the message stays open, use the show() mehod to display it.
Display a text and wait for user response.
Possible choices are ‘OK’ and ‘CANCEL’. The function returns True if the OK button was clicked or ‘ENTER’ was pressed, False if the ‘CANCEL’ button was pressed or ESC was pressed.
A box with action buttons.
Return the name of the InputItem.
Return the displayed text of the InputItem.
Change the text on button index.
Change the icon on button index.
Return the widget’s value.
Change the widget’s value.
A widget displaying the coordinates of a point.
Return the current x,y,z values as a list of floats.
Set the three values of the widget.
A widget displaying an image.
Show an image in the viewer.
image: either a filename or an existing QImage instance. If a filename, it should be an image file that can be read by the QImage constructor. Most image formats are understood by QImage. The variable gui.image.image_formats_qtr provides a list.
Functions defined in module widgets
Return the maximum widget size.
The maximum widget size is the (available) screen size. This may be smaller than the physical screen size (e.g. excluding docking panels).
Add a timeout to a widget.
If timeout is positive, a timer will be installed into the widget which will call the timeoutfunc after timeout seconds have elapsed. The timeoutfunc can be any callable, but usually will emit a signal to make the widget accept or reject the input. The timeoutfunc will not be called is if the widget is destructed before the timer has finished.
Guess the InputItem type from the value
A convenience function to create an InputItem dictionary
A convenience function to create an InputItem dictionary
A convenience function to create an InputItem dictionary
A convenience function to create an InputItem dictionary
This function accepts InputItem data in the old format:
( name, value, [ itemtype, [ optionsdict ] ] )
and turns them into a dictionary as required by the new InputItem format.
Convert InputItem data to a proper dict.
This function tries to convert some old style or sloppy InputItem data to a proper InputItem data dict.
The conversion does the following:
Create an InputItem of any type, depending on the arguments.
Arguments: only name, value and itemtype are required
Update the input data fields with new data values
The data items with a name occurring as a key in newdata will have their value replaced with the corresponding value in newdata, unless this value is None.
The user should make sure to set only values of the proper type!
Ask the user to select a font.
A font selection dialog widget is displayed and the user is requested to select a font. Returns a font if the user exited the dialog with the OK button. Returns None if the user clicked CANCEL.
Create a color selection dialog and return the selected color.
col is the initial selection. If a valid color is selected, its string name is returned, usually as a hex #RRGGBB string. If the dialog is canceled, None is returned.
Update the text of a text display widget.
This function allows to display other text formats besides the plain text and html supported by the widget. Any format other than plain or html will be converted to one of these before sending it to the widget. Currently, we convert the following formats:
Create a set of dialog buttons
dia is a dialog widget
actions is a list of tuples (name,) or (name,function). If a function is specified, it will be executed on pressing the button. If no function is specified, and name is one of ‘ok’ or ‘cancel’ (case is ignored), the button will be bound to the dialog’s ‘accept’ or ‘reject’ slot. If actions==None (default), it will be set to the default [('Cancel',),('OK',)].
Specify actions=[] if you want an empty dialogDuttons. default is the name of the action to set as the default. If no default is given, it is set to the LAST button.
Returns a horizontal box layout with the buttons.
A collection of functions to read/write tetgen files and to run the tetgen program
tetgen is a quality tetrahedral mesh generator and a 3D Delaunay triangulator. See http://tetgen.org
Classes defined in module tetgen
Functions defined in module tetgen
Read a tetgen .node file.
Returns a tuple as described in readNodesBlock.
Read a tetgen .ele file.
Returns a tuple as described in readElemsBlock.
Read a tetgen .face file.
Returns a tuple as described in readFacesBlock.
Read a tetgen .smesh file.
Returns an array of triangle elements.
Read a tetgen .poly file.
Returns an array of triangle elements.
Read a tetgen surface from a .node/.face file pair.
The given filename is either the .node or .face file. Returns a tuple of (nodes,elems).
Skip comments and blank lines on a tetgen file.
Reads from a file until the first non-comment and non-empty line. Then returns the non-empty, non-comment line, stripped from possible trailing comments. Returns None if end of file is reached.
Strip blanks, newline and comments from a line of text.
Read a number of ints from a line, adding zero for omitted values.
line is a string with b;anks separated integer values. Returns a list of nint integers. The trailing ones are set to zero if the strings contains less values.
Add an element to a collection.
Read a tetgen nodes block.
Returns a tuple with:
The last two may be None.
Read a tetgen elems block.
Returns a tuple with:
The last can be None.
Read a tetgen faces block.
Returns a a tuple with:
The last can be None.
Read a tetgen .smesh facets bock.
Returns a tuple of dictionaries with plexitudes as keys:
Read a tetgen .neigh file.
Returns an arrays containing the tetrahedra neighbours:
Write a tetgen .node file.
Write a tetgen .smesh file.
Currently it only writes the facets of a triangular surface mesh. Coords should be written independently to a .node file.
Write a tetgen surface model to .node and .smesh files.
The provided file name is the .node or the .smesh filename.
Returns the next file name in a family of tetgen file names.
Run tetgen mesher on the specified file.
The input file is a closed triangulated surface. tetgen will generate a volume tetraeder mesh inside the surface, and create a new approximation of the surface as a by-product.
Read and draw a tetgen file.
This is an experimental function for the geometry import menu.
This module contains functions to convert bitmap images into numpy arrays and vice versa.
Most of this code was borrowed from the PyQwt mailing list
Classes defined in module imagearray
Functions defined in module imagearray
Convert the 2D numpy array gray into a 8-bit QImage with a gray colormap. The first dimension represents the vertical image axis.
Convert the 3D numpy array rgb into a 32-bit QImage. rgb must have three dimensions with the vertical, horizontal and RGB image axes.
Classes defined in module camera
A dict to keep named camera angle settings.
This class keeps a dictionary of named angle settings. Each value is a tuple of (longitude, latitude, twist) camera angles. This is a static class which should not need to be instantiated.
There are seven predefined values: six for looking along global coordinate axes, one isometric view.
Get the angles for a named view.
Returns a tuple of angles (longitude, latitude, twist) if the named view was defined, or None otherwise
A camera for OpenGL rendering.
The Camera class holds all the camera related settings related to the rendering of a scene in OpenGL. These include camera position, the viewing direction of the camera, and the lens parameters (opening angle, front and back clipping planes). This class also provides convenient methods to change the settings so as to get smooth camera manipulation.
Camera position and orientation:
The camera viewing line is defined by two points: the position of the camera and the center of the scene the camera is looking at. We use the center of the scene as the origin of a local coordinate system to define the camera position. For convenience, this could be stored in spherical coordinates, as a distance value and two angles: longitude and latitude. Furthermore, the camera can also rotate around its viewing line. We can define this by a third angle, the twist. From these four values, the needed translation vector and rotation matrix for the scene rendering may be calculated.
Inversely however, we can not compute a unique set of angles from a given rotation matrix (this is known as ‘gimball lock’). As a result, continuous (smooth) camera rotation by e.g. mouse control requires that the camera orientation be stored as the full rotation matrix, rather than as three angles. Therefore we store the camera position and orientation as follows:
- ctr: [ x,y,z ] : the reference point of the camera: this is always a point on the viewing axis. Usually, it is set to the center of the scene you are looking at.
- dist: distance of the camera to the reference point.
- rot: a 3x3 rotation matrix, rotating the global coordinate system thus that the z-direction is oriented from center to camera.
These values have influence on the ModelView matrix.
Camera lens settings:
The lens parameters define the volume that is seen by the camera. It is described by the following parameters:
- fovy: the vertical lens opening angle (Field Of View Y),
- aspect: the aspect ratio (width/height) of the lens. The product fovy * aspect is the horizontal field of view.
- near, far: the position of the front and back clipping planes. They are given as distances from the camera and should both be strictly positive. Anything that is closer to the camera than the near plane or further away than the far plane, will not be shown on the canvas.
Camera methods that change these values will not directly change the ModelView matrix. The loadModelView() method has to be called explicitely to make the settings active.
These values have influence on the Projection matrix.
Methods that change the camera position, orientation or lens parameters will not directly change the related ModelView or Projection matrix. They will just flag a change in the camera settings. The changes are only activated by a call to the loadModelView() or loadProjection() method, which will test the flags to see whether the corresponding matrix needs a rebuild.
The default camera is at distance 1.0 of the center point [0.,0.,0.] and looking in the -z direction. Near and far clipping planes are by default set to 0.1, resp 10 times the camera distance.
Return the camera reference point (the scene center).
Return the camera rotation matrix.
Return the camera distance.
Lock/unlock a camera.
When a camera is locked, its position and lens parameters can not be changed. This can e.g. be used in multiple viewports layouts to create fixed views from different angles.
Set the center of the camera in global cartesian coordinates.
Set the rotation angles.
angles is either:
Set the rotation matrix of the camera from three angles.
Set the distance.
Return a report of the current camera settings.
Move the camera eye towards/away from the scene center.
This has the effect of zooming. A value > 1 zooms out, a value < 1 zooms in. The resulting enlargement of the view will approximately be 1/val. A zero value will move the camera to the center of the scene. The front and back clipping planes may need adjustment after a dolly operation.
Rotate the camera around axis through its eye.
The camera is rotated around an axis through the eye point. For axes 0 and 1, this will move the center, creating a panning effect. The default axis is parallel to the y-axis, resulting in horizontal panning. For vertical panning (axis=1) a convenience alias tilt is created. For axis = 2 the operation is equivalent to the rotate operation.
Rotate the camera up/down around its own horizontal axis.
The camera is rotated around and perpendicular to the plane of the y-axis and the viewing axis. This has the effect of a vertical pan. A positive value tilts the camera up, shifting the scene down. The value is specified in degrees.
Move the camera over translation (dx,dy,dz) in global coordinates.
The center of the camera is moved over the specified translation vector. This has the effect of moving the scene in opposite direction.
Rotate the camera around current camera axes.
Save the ModelView matrix.
Set the ModelView matrix from camera parameters.
Load the ModelView matrix.
There are thrre uses of this function:
In the latter two cases, the new ModelView matrix is saved, and if a camera attribute modelview_callback has been set, a call to this function is done, passing the camera instance as parameter.
Load the current ModelView matrix with translations canceled out.
Transform a vertex using the currently saved Modelview matrix.
Transform a vertex from camera to world coordinates.
The specified vector can have 3 or 4 (homogoneous) components. This uses the currently saved rotation matrix.
Set the field of view of the camera.
We set the field of view by the vertical opening angle fovy and the aspect ratio (width/height) of the viewing volume. A parameter that is not specified is left unchanged.
Set maximal camera area.
Resets the camera window area to its maximum values corresponding to the fovy setting, symmetrical about the camera axes.
Set the viewable area of the camera.
Zoom in/out by shrinking/enlarging the camera view area.
The zoom factor is relative to the current setting. Values smaller than 1.0 zoom in, larger values zoom out.
Pan by moving the vamera area.
dx and dy are relative movements in fractions of the current area size.
Set the near and far clipping planes
Set perspective on or off
Load the projection/perspective matrix.
The caller will have to setup the correct GL environment beforehand. No need to set matrix mode though. This function will switch to GL_PROJECTION mode before loading the matrix
!! CHANGED: does not switch back to GL_MODELVIEW mode!
A pick region can be defined to use the camera in picking mode. pick defines the picking region center and size (x,y,w,h).
This function does it best at autodetecting changes in the lens settings, and will only reload the matrix if such changes are detected. You can optionally force loading the matrix.
Map the object coordinates (x,y,z) to window coordinates.
Map the window coordinates (x,y,z) to object coordinates.
Enable/disable coordinate tracking using the camera
Functions defined in module camera
Return the tan of an angle in degrees.
This module defines the functions for creating the pyFormex window toolbars.
Classes defined in module toolbar
Functions defined in module toolbar
Add the script action buttons to the toolbar.
Add a button to a toolbar.
Remove a button from a toolbar.
Add the camera buttons to a toolbar.
Update the corresponding viewport attribute.
This does not update the button state.
Update the button to correct state.
Update the transparency button to correct state.
Update the light button to correct state.
Update the normals button to correct state.
Update the normals button to correct state.
Add or remove the timeout button,depending on cfg.
Programmatically toggle the timeout button
This module allows to import and export some simple geometrical items in DXF format.
Classes defined in module dxf
Export geometry in DXF format.
While we certainly do not want to promote proprietary software, some of our users occasionally needed to export some model in DXF format. This class provides a minimum of functionality.
Write a string to the dxf file.
The string does not include the line terminator.
Output a string data item to the dxf file.
code is the group code, data holds the data
Finalize and close the DXF file
Start a new section
End the current section
Start the ENTITIES section
Export the layer
Export a line.
x is a (2,3) shaped array
Functions defined in module dxf
Import (parts of) a DXF file into pyFormex.
This function scans a DXF file for recognized entities and imports those entities as pyFormex objects. It is only a very partial importer, but has proven to be already very valuable for many users.
filename: name of a DXF file. The return value is a list of pyFormex objects.
Importing a DXF file is done in two steps:
Read a DXF file and extract the recognized entities.
filename: name of a .DXF file.
Returns a multiline string with one line for each recognized entity, in a format that can directly be used by convertDXF().
This function requires the external program dxfparser which comes with the pyFormex distribution. It currently recognizes entities of type ‘Arc’, ‘Line’, ‘Polyline’, ‘Vertex’.
Convert a textual representation of a DXF format to pyFormex objects.
This text representation can e.g. be obtained by the function readDXF(). It contains lines defining DXF entities. A small example:
Arc(0.0,0.0,0.0,1.0,-90.,90.)
Arc(0.0,0.0,0.0,3.0,-90.,90.)
Line(0.0,-1.0,0.0,0.0,1.0,0.0)
Polyline(0)
Vertex(0.0,3.0,0.0)
Vertex(-2.0,3.0,0.0)
Vertex(-2.0,-7.0,0.0)
Vertex(0.0,-7.0,0.0)
Vertex(0.0,-3.0,0.0)
Each line of the text defines a single entity or starts a multiple component entity. The text should be well aligned to constitute a proper Python script. Currently, the only defined entities are ‘Arc’, ‘Line’, ‘Polyline’, ‘Vertex’.
Returns a list of pyFormex objects corresponding to the text. The returned objects are of the following type:
function name object Arc plugins.curve.Arc Line plugins.curve.Line Polyline plugins.curve.PolyLine
No object is returned for the Vertex function: they define the vertices of a PolyLine.
Export a Formex to a DXF file
Currently, only plex-2 Formices can be exported to DXF.
Classes defined in module flavia
Functions defined in module flavia
Read a flavia mesh file.
Returns a list of Meshes if succesful.
Read a set of coordinates from a flavia file
Read a set of coordinates from a flavia file
Read a flavia results file for an ndim mesh.
Read a set of results from a flavia file
Create an FeResult from meshes and results
Read flavia results files
Currently we only read matching pairs of meshfile,resfile files.
Classes defined in module marks
A 2D drawing inserted at a 3D position of the scene.
Perform the OpenGL drawing functions to display the actor.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
Two viewport axes drawn at a 3D position.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A text drawn at a 3D position.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A list of numbers drawn at 3D positions.
This functions mimicks the drawing of a number list for picking.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
Functions defined in module marks
This module provides the basic functions for using the GLUT library in the rendering of text on an OpenGL canvas.
Classes defined in module gluttext
Functions defined in module gluttext
Select one of the glut fonts using a font + size description.
The return value is a 4-character string representing one of the GLUT fonts.
Return GLUT font designation for the named font.
The recognized font names are:
If an unrecognized string is given, the default is ‘hv18’.
Return the height of the named glut font.
This supposes that the last two characters of the name hold the font height.
Draw a text in given font at the current rasterpoint.
font should be one of the legal fonts returned by glutFont(). If text is not a string, it will be formatted to a string before drawing. After drawing, the rasterpos will have been updated!
Compute the length in pixels of a text string in given font.
We use our own function to calculate the length because the builtin has a bug.
Draw a text at given 2D position in window.
Graphic Tools for pyFormex.
Classes defined in module tools
Functions defined in module tools
Get the specified items from object.
Returns a collection.
Grow the collection with n frontal rings.
K should be a collection of elements. This currently only works on surfaces. Objects that do not have a nodeFront() generator function are
Partition the collection according to node adjacency.
The actor numbers will be connected to a collection of property numbers, e.g. 0 [1 [4,12] 2 [6,20]], where 0 is the actor number, 1 and 2 are the property numbers and 4, 12, 6 and 20 are the element numbers.
Remove all partitions with property not in prop.
Export a list of objects under the given name.
If obj is a list, and single=True, each element of the list is exported as a single item. The items will be given the names name-0, name-1, etc. Else, the obj is exported as is under the name.
Finite element models are geometrical models that consist of a unique set of nodal coordinates and one of more sets of elements.
Classes defined in module fe
Contains all FE model data.
Return the number of nodes in the model.
Return the number of elements in the model.
Return the number of element groups in the model.
Return the maximum plexitude of the model.
Splits a set of element numbers over the element groups.
Returns two lists of element sets, the first in global numbering, the second in group numbering. Each item contains the element numbers from the given set that belong to the corresponding group.
Return the global element numbers for elements set in group
Return the definitions of the elements in sets.
sets should be a list of element sets with length equal to the number of element groups. Each set contains element numbers local to that group.
As the elements can be grouped according to plexitude, this function returns a list of element arrays matching the element groups in self.elems. Some of these arrays may be empty.
It also provide the global and group element numbers, since they had to be calculated anyway.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return a deep copy of the object.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
Renumber a set of nodes.
old and new are equally sized lists with unique node numbers, each smaller that the number of nodes in the model. The old numbers will be renumbered to the new numbers. If one of the lists is None, a range with the length of the other is used. If the lists are shorter than the number of nodes, the remaining nodes will be numbered in an unspecified order. If both lists are None, the nodes are renumbered randomly.
This function returns a tuple (old,new) with the full renumbering vectors used. The first gives the old node numbers of the current numbers, the second gives the new numbers cooresponding with the old ones.
Functions defined in module fe
Returns the fe Model obtained from merging individual meshes.
The input arguments are (coords,elems) tuples. The return value is a merged fe Model.
This module defines extended Mesh functionality which is considered to be experimental, maybe incomplete or even buggy.
The functions in this module can be called as functions operating on a Mesh object, but are also available as Mesh methods.
Classes defined in module mesh_ext
Functions defined in module mesh_ext
Create a report on the Mesh shape and size.
The report contains the number of nodes, number of elements, plexitude, element type, bbox and size.
Create a report on the Mesh shape and size.
The report contains the number of nodes, number of elements, plexitude, element type, bbox and size.
Generator function returning the frontal elements.
startat is an element number or list of numbers of the starting front. On first call, this function returns the starting front. Each next() call returns the next front.
Detects different parts of the Mesh using a frontal method.
okedges flags the edges where the two adjacent elems are to be in the same part of the Mesh. startat is a list of elements that are in the first part. The partitioning is returned as a property type array having a value corresponding to the part number. The lowest property number will be firstprop.
Detect the connected parts of a Mesh.
The Mesh is partitioned in parts in which all elements are connected. Two elements are connected if it is possible to draw a continuous (poly)line from a point in one element to a point in the other element without leaving the Mesh. The partitioning is returned as a property type array having a value corresponding to the part number. The lowest property number will be firstprop.
Split the Mesh into connected parts.
Returns a list of Meshes that each form a connected part.
Return the largest connected part of the Mesh.
It finds the rings of elems connected to sources by node.
Sources is a list of elem indices. A list of rings is returned, from zero (equal to sources) to step. If step is -1, all rings are returned.
Modify the connectivity of negative-volume elements to make positive-volume elements.
Negative-volume elements (hex or tet with inconsistent face orientation) may appear by error during geometrical trnasformations (e.g. reflect, sweep, extrude, revolve). This function fixes those elements. Currently it only works with linear tet and hex.
Returns a quality measure for volume meshes.
If scaled if False, it returns the Jacobian at the corners of each element. If scaled is True, it returns a quality metrics, being the minumum value of the scaled Jacobian in each element (at one corner, the Jacobian divided by the volume of a perfect brick). Each tet or hex element gives a value between -1 and 1. Acceptable elements have a positive scaled Jacobian. However, good quality requires a minimum of 0.2. Quadratic meshes are first converted to linear. If the mesh contain mainly negative Jacobians, it probably has negative volumes and can be fixed with the correctNegativeVolumes.
area of elements
For surface element the faces’ area is returned. For volume elements the sum of the faces’areas is returned.
Return the total area of the Mesh.
For a Mesh with dimensionality 2, the total area of the Mesh is returned. For a Mesh with dimensionality 3, the total area of all the element faces is returned. Use Mesh.getBorderMesh().area() if you only want the total area of the border faces. For a Mesh with dimensionality < 2, 0 is returned.
Partition a surface Mesh by the angle between adjacent elements.
The Mesh is partitioned in parts bounded by the sharp edges in the surface. The arguments and return value are the same as in TriSurface.partitionByAngle().
Currently this only works for ‘tri3’ and ‘quad4’ type Meshes. Also, the ‘quad4’ partitioning method currently only works corectly if the quads are nearly planar.
Initialize the Mesh extensions.
Calling this function will install some of the mesh functions defined in this modules as Mesh methods.
Classes defined in module colors
Functions defined in module colors
Convert a color to an OpenGL RGB color.
The output is a tuple of three RGB float values ranging from 0.0 to 1.0. The input can be any of the following: - a QColor - a string specifying the Xwindow name of the color - a hex string ‘#RGB’ with 1 to 4 hexadecimal digits per color - a tuple or list of 3 integer values in the range 0..255 - a tuple or list of 3 float values in the range 0.0..1.0 Any other input may give unpredictable results.
Return a string designation for the color.
color can be anything that is accepted by GLColor. In most cases If color can not be converted, None is returned.
Return an RGB (0-255) tuple for an OpenGL color
Return an RGB hex string for an OpenGL color
Return the closest color name.
Adds an alpha channel to an RGB color
Returns a grey OpenGL color of given intensity (0..1)
Postprocessing means collecting a geometrical model and computed values from a numerical simulation, and render the values on the domain.
Classes defined in module postproc
Functions defined in module postproc
Return a sequence of scale values between -1 and +1.
nframes : the number of steps between 0 and -1/+1 values.
cycle: determines how subsequent cycles occur:
'up': ramping up
'updown': ramping up and down
'revert': ramping up and down then reverse up and down
shape: determines the shape of the amplitude curve:
'linear': linear scaling
'sine': sinusoidal scaling
Classes defined in module decors
A decoration is a 2-D drawing at canvas position x,y.
All decorations have at least the following attributes:
x,y : (int) window coordinates of the insertion point
This should only use openGL function that are allowed in a display list.
Perform the OpenGL drawing functions to display the actor.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A mark at a fixed position on the canvas.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A straight line on the canvas.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A viewport decoration showing a text string.
Draw the text.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A labeled colorscale legend.
When showing the distribution of some variable over a domain by means of a color encoding, the viewer expects some labeled colorscale as a guide to decode the colors. The ColorLegend decoration provides such a color legend. This class only provides the visual details of the scale. The conversion of the numerical values to the matching colors is provided by the colorscale.ColorLegend class.
Parameters:
Some practical guidelines:
The ColorScale example script provides opportunity to experiment with different settings.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A 2D-rectangle on the canvas.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A 2D-grid on the canvas.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A collection of straight lines on the canvas.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
An OpenGL actor representing a triade of global axes.
horizontal position (‘l’, ‘c’ or ‘r’) and second sets vertical position (‘b’, ‘c’ or ‘t’).
size: size in pixels of the zone displaying the triade.
pat: shape to be drawn in the coordinate planes. Default is a square. ‘16’ givec a triangle. ‘’ disables the planes.
legend: text symbols to plot at the end of the axes. A 3-character string or a tuple of 3 strings.
Perform the OpenGL drawing functions to display the actor.
Mimick the OpenGL drawing functions to pick (from) the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
Functions defined in module decors
Draw a dot at canvas coordinates (x,y).
Draw a straight line from (x1,y1) to (x2,y2) in canvas coordinates.
Draw a rectangular grid of lines
The rectangle has (x1,y1) and and (x2,y2) as opposite corners. There are (nx,ny) subdivisions along the (x,y)-axis. So the grid has (nx+1) * (ny+1) lines. nx=ny=1 draws a rectangle. nx=0 draws 1 vertical line (at x1). nx=-1 draws no vertical lines. ny=0 draws 1 horizontal line (at y1). ny=-1 draws no horizontal lines.
Draw the circumference of a rectangle.
Draw a single rectangular quad.
This modules allows for a consistent local numbering scheme of element connectivities throughout pyFormex. When interfacing with other programs, one should be aware that conversions may be necessary. Conversions to/from external programs should be done by the interface modules.
Classes defined in module elements
Element base class: an empty element.
All derived classes should have a capitalized name: starting with an uppercase character and further only lower case and digits.
Each element is defined by the following attributes:
The vertices of the elements are defined in a unit space [0,1] in each axis direction.
The elements guarantee a fixed local numbering scheme of the vertices. One should however not rely on a specific numbering scheme of edges, faces or elements. For solid elements, it is guaranteed that the vertices of all faces are numbered in a consecutive order spinning positively around the outward normal on the face.
The list of available element types can be found by:
>>> printElementTypes()
Available Element Types:
0-dimensional elements: ['point']
1-dimensional elements: ['line2', 'line3']
2-dimensional elements: ['tri3', 'tri6', 'quad4', 'quad6', 'quad8', 'quad9']
3-dimensional elements: ['tet4', 'tet10', 'tet14', 'tet15', 'wedge6', 'hex8', 'hex16', 'hex20', 'icosa']
Optional attributes:
Conversion actions:
Return the type and connectivity table of some element entities.
The full list of entities with increasing dimensionality 0,1,2,3 is:
['points', 'edges', 'faces', 'cells' ]
If level is negative, the dimensionality returned is relative to the highest dimensionality (.i.e., that of the element). If it is positive, it is taken absolute.
Thus, for a 3D element type, getEntities(-1) returns the faces, while for a 2D element type, it returns the edges. For both types however, getLowerEntities(+1) returns the edges.
The return value is a dict where the keys are element types and the values are connectivity tables. If reduce == False: there will be only one connectivity table and it may include degenerate elements. If reduce == True, an attempt is made to reduce the degenerate elements. The returned dict may then have multiple entries.
If the requested entity level is outside the range 0..ndim, the return value is None.
Functions defined in module elements
Return the requested element type
Parameters:
Returns: a subclass of Element
Example:
>>> elementType('tri3').name()
'tri3'
>>> elementType(nplex=2).name()
'line2'
Return the names of available elements.
If a value is specified for ndim, only the elements with the matching dimensionality are returned.
Print all available element types.
Prints a list of the names of all availabale element types, grouped by their dimensionality.
This module implements user interaction with the OpenGL canvas defined in module canvas. QtCanvas is a single interactive OpenGL canvas, while MultiCanvas implements a dynamic array of multiple canvases.
Classes defined in module viewport
A class for handling the mouse cursor shape on the Canvas.
Set the cursor shape to shape
Set the cursor shape to shape
A class for handling the mouse events on the Canvas.
Return the mouse function bound to self.button and self.mod
A canvas for OpenGL rendering.
This class provides interactive functionality for the OpenGL canvas provided by the canvas.Canvas class.
Interactivity is highly dependent on Qt4. Putting the interactive functions in a separate class makes it esier to use the Canvas class in non-interactive situations or combining it with other GUI toolsets.
Reset the Drawing options to some defaults
Set the Drawing options to some values
Set the cursor shape to shape
Set the cursor shape to shape
Return the mouse function bound to self.button and self.mod
Process mouse events during interactive rectangle zooming.
On PRESS, record the mouse position. On MOVE, create a rectangular zoom window. On RELEASE, zoom to the picked rectangle.
Set the list of pickable actors
Start an interactive picking mode.
If selection mode was already started, mode is disregarded and this can be used to change the filter method.
Wait for the user to interactively make a selection.
End an interactive picking mode.
Accept or cancel an interactive picking mode.
If clear == True, the current selection is cleared.
Cancel an interactive picking mode and clear the selection.
Interactively pick objects from the viewport.
mode: defines what to pick : one of ['actor','element','point','number','edge']
oneshot: if True, the function returns as soon as the user ends a picking operation. The default is to let the user modify his selection and only to return after an explicit cancel (ESC or right mouse button).
func: if specified, this function will be called after each atomic pick operation. The Collection with the currently selected objects is passed as an argument. This can e.g. be used to highlight the selected objects during picking.
filter: defines what elements to retain from the selection: one of [None,'single','closest,'connected'].
None (default) will return the complete selection.
‘closest’ will only keep the element closest to the user.
‘connected’ will only keep elements connected to - the closest element (set picked) - what is already in the selection (add picked).
Currently this only works when picking mode is ‘element’ and for Actors having a partitionByConnection method.
When the picking operation is finished, the selection is returned. The return value is always a Collection object.
Go into number picking mode and return the selection.
Interactively draw on the canvas.
This function allows the user to interactively create points in 3D space and collects the subsequent points in a Coords object. The interpretation of these points is left to the caller.
The drawing operation is finished when the number of requested points has been reached, or when the user clicks the right mouse button or hits ‘ENTER’. The return value is a (n,3) shaped Coords array.
Start an interactive drawing mode.
End an interactive drawing mode.
Cancel an interactive drawing mode.
If clear == True, the current drawing is cleared.
Cancel an interactive drawing mode and clear the drawing.
Process mouse events during interactive drawing.
On PRESS, do nothing. On MOVE, do nothing. On RELEASE, add the point to the point list.
Start an interactive line drawing mode.
Wait for the user to interactively draw a line.
End an interactive drawing mode.
Cancel an interactive drawing mode.
If clear == True, the current drawing is cleared.
Cancel an interactive drawing mode and clear the drawing.
Edit an interactive drawing.
Interactively draw lines on the canvas.
When the drawing operation is finished, the drawing is returned. The return value is a (n,2,2) shaped array.
Perform dynamic rotation operation.
This function processes mouse button events controlling a dynamic rotation operation. The action is one of PRESS, MOVE or RELEASE.
Perform dynamic pan operation.
This function processes mouse button events controlling a dynamic pan operation. The action is one of PRESS, MOVE or RELEASE.
Perform dynamic zoom operation.
This function processes mouse button events controlling a dynamic zoom operation. The action is one of PRESS, MOVE or RELEASE.
Zoom by rotating a wheel over an angle delta
Emit a DONE event by clicking the mouse.
This is equivalent to pressing the ENTER button.
Emit a CANCEL event by clicking the mouse.
This is equivalent to pressing the ESC button.
Store the pos and draw a rectangle to it.
Process mouse events during interactive picking.
On PRESS, record the mouse position. On MOVE, create a rectangular picking window. On RELEASE, pick the objects inside the rectangle.
Set the list of actors inside the pick_window.
Set the list of actor parts inside the pick_window.
obj_type can be ‘element’, ‘edge’ or ‘point’ ‘edge’ is only available for mesh type geometry max_objects specifies the maximum number of objects
The picked object numbers are stored in self.picked. If store_closest==True, the closest picked object is stored in as a tuple ( [actor,object] ,distance) in self.picked_closest
A list of actors from which can be picked may be given. If so, the resulting keys are indices in this list. By default, the full actor list is used.
Set the list of actor elements inside the pick_window.
Set the list of actor points inside the pick_window.
Set the list of actor edges inside the pick_window.
Return the numbers inside the pick_window.
Store the pos and draw a line to it.
Process mouse events during interactive drawing.
On PRESS, record the mouse position. On MOVE, draw a line. On RELEASE, add the line to the drawing.
Process a mouse press event.
Process a mouse move event.
Process a mouse release event.
Process a wheel event.
Toggle lights on/off.
Return the status of the lighting.
Return all the settings to their default values.
Set the global ambient lighting for the canvas
Set the default material light properties for the canvas
Change the light parameters
Set the rendering mode.
This sets or changes the rendermode and lighting attributes. If lighting is not specified, it is set depending on the rendermode.
If the canvas has not been initialized, this merely sets the attributes self.rendermode and self.lighting. If the canvas was already initialized (it has a camera), and one of the specified settings is fdifferent from the existing, the new mode is set, the canvas is re-initialized according to the newly set mode, and everything is redrawn with the new mode.
Set the linewidth for line rendering.
Set the linestipple for line rendering.
Set the size for point drawing.
Set the background color.
If one color is specified, a solid background is set. If two colors are specified, a graded background is set and an object is created to display the background.
Create the background object.
Set the default foreground color.
Set the highlight color.
Toggle the display of the global axes on or off.
If on is True, a triade of global axes is displayed, if False it is removed. The default (None) toggles between on and off.
Initialize the rendering machine.
The rendering machine is initialized according to: - self.rendermode: one of - self.lighting
Flush all OpenGL commands, making sure the display is updated.
Clear the canvas to the background color.
Activate the canvas settings in the GL machine.
(Re)display all the actors in the scene.
This should e.g. be used when actors are added to the scene, or after changing camera position/orientation or lens.
Set up the canvas for 2D drawing on top of 3D canvas.
The 2D drawing operation should be ended by calling end_2D_drawing. It is assumed that you will not try to change/refresh the normal 3D drawing cycle during this operation.
Cancel the 2D drawing mode initiated by begin_2D_drawing.
Set the bounding box of the scene you want to be visible.
Add a 3D actor to the 3D scene.
Remove a 3D actor from the 3D scene.
Add a 3D actor highlight to the 3D scene.
Remove a 3D actor highlight from the 3D scene.
Add an annotation to the 3D scene.
Remove an annotation from the 3D scene.
Add a 2D decoration to the canvas.
Remove a 2D decoration from the canvas.
Remove a list of any actor/highlights/annotation/decoration items.
This will remove the items from any of the canvas lists in which the item appears. itemlist can also be a single item instead of a list.
Remove all actors in actorlist (default = all) from the scene.
Remove all highlights in actorlist (default = all) from the scene.
Remove all annotations in actorlist (default = all) from the scene.
Remove all decorations in actorlist (default = all) from the scene.
Remove all actors and decorations
Redraw all actors in the scene.
Sets the camera looking under angles at bbox.
This function sets the camera angles and adjusts the zooming. The camera distance remains unchanged.
If a bbox is specified, the camera will be zoomed to make the whole bbox visible. If no bbox is specified, the current scene bbox will be used. If no current bbox has been set, it will be calculated as the bbox of the whole scene.
If no camera angles are given, the camera orientation is kept. angles can be a set of 3 angles, or a string
Map the object coordinates (x,y,z) to window coordinates.
Map the window coordinates (x,y,z) to object coordinates.
Dolly zooming.
Zooms in with a factor f by moving the camera closer to the scene. This does noet change the camera’s FOV setting. It will change the perspective view though.
Rectangle zooming.
Zooms in/out by changing the area and position of the visible part of the lens. Unlike zoom(), this does not change the perspective view.
x0,y0,x1,y1 are pixel coordinates of the lower left and upper right corners of the area of the lens that will be mapped on the canvas viewport. Specifying values that lead to smaller width/height will zoom in.
Rectangle zooming with specified center.
This is like zoomRectangle, but the zoom rectangle is specified by its center and size, which may be more appropriate when using off-center zooming.
Rectangle zoom to make full scene visible.
Save the current OpenGL buffer
Show the saved buffer
Draw the focus rectangle.
The specified width is HALF of the line width
draw the cursor
An OpenGL canvas with multiple viewports and QT interaction.
The MultiCanvas implements a central QT widget containing one or more QtCanvas widgets.
Change the lay-out of the viewports on the OpenGL widget.
nvps: number of viewports ncols: number of columns nrows: number of rows pos: list holding the position and span of each viewport [[row,col,rowspan,colspan],...] rstretch: list holding the stretch factor for each row cstretch: list holding the stretch factor for each column (rows/columns with a higher stretch factor take more of the available space) Each of this parameters is optional.
If pos is given, it specifies all viewports and nvps, nrows and ncols are disregarded.
Else:
If nvps is given, it specifies the number of viewports in the layout. Else, nvps will be set to the current number of viewports.
If ncols is an int, viewports are laid out rowwise over ncols columns and nrows is ignored. If ncols is None and nrows is an int, viewports are laid out columnwise over nrows rows.
If nvps is not equal to the current number of viewports, viewports will be added or removed to match the requested number.
By default they are laid out rowwise over two columns.
Create a new viewport
If another QtCanvas instance is passed, both will share the same display lists and textures.
Add a new viewport and make it visible
Remove a view from the canvas
If view is None, the last one is removed. You can not remove a view when there is only one left.
Make the specified viewport the current one.
view can be either a viewport or viewport number.
Set the row and column stretch factors.
rowstretch and colstretch are lists of stretch factors to be applied on the subsequent rows/columns. If the lists are shorter than the number of rows/columns, the
Link viewport vp to to
A QtGui.QGridLayout where each added widget is framed.
An OpenGL canvas with multiple viewports and QT interaction.
The MultiCanvas implements a central QT widget containing one or more QtCanvas widgets.
Create a new viewport
If another QtCanvas instance is passed, both will share the same display lists and textures.
Add a new viewport to the widget
Make the specified viewport the current one.
canv can be either a viewport or viewport number.
Show the view w.
Change the lay-out of the viewports on the OpenGL widget.
nvps: number of viewports ncols: number of columns nrows: number of rows pos: list holding the position and span of each viewport [[row,col,rowspan,colspan],...] rstretch: list holding the stretch factor for each row cstretch: list holding the stretch factor for each column (rows/columns with a higher stretch factor take more of the available space) Each of this parameters is optional.
If a number of viewports is given, viewports will be added or removed to match the requested number. By default they are laid out rowwise over two columns.
If ncols is an int, viewports are laid out rowwise over ncols columns and nrows is ignored. If ncols is None and nrows is an int, viewports are laid out columnwise over nrows rows. Alternatively, the pos argument can be used to specify the layout of the viewports.
Link viewport vp to to
Functions defined in module viewport
Return the dot product of vectors v and w
Return the length of the vector v
Return the (signed) length of the projection of vector v on vector w.
Set the correct OpenGL format.
On a correctly installed system, the default should do well. The default OpenGL format can be changed by command line options:
--dri : use the Direct Rendering Infrastructure
--nodri : do not use the DRI
--alpha : enable the alpha buffer
Some information about the OpenGL format.
Classes defined in module lima
A class for operations on Lindenmayer Systems.
Print the status of the Lima
Add a new rule (or overwrite an existing)
Translate the product by the specified rule set.
If keep=True is specified, atoms that do not have a translation in the rule set, will be kept unchanged. The default (keep=False) is to remove those atoms.
Functions defined in module lima
Create a list of connected points using a Lindenmayer system.
axiom is the initial string, rules are translation rules for the characters in the string, level is the number of generations to produce, turtlecmds are the translation rules of the final string to turtle cmds, glob is an optional list of globals to pass to the turtle script player.
This is a convenience function for quickly creating a drawing of a single generation member. If you intend to draw multiple generations of the same Lima, it is better to use the grow() and translate() methods directly.
Classes defined in module actors
An Actor is anything that can be drawn in an OpenGL 3D Scene.
The visualisation of the Scene Actors is dependent on camera position and angles, clipping planes, rendering mode and lighting.
An Actor subclass should minimally reimplement the following methods:
The interactive picking functionality requires the following methods, for which we porvide do-nothing defaults here:
Default implementation for bbox().
Perform the OpenGL drawing functions to display the actor.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
An Actor translated to another position.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
An Actor rotated to another position.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
An OpenGL actor with cubic shape and 6 colored sides.
Draw the cube.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
An OpenGL actor representing a sphere.
Draw the cube.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
Draws a bbox.
Always draws a wireframe model of the bbox.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
An actor showing the three axes of a CoordinateSystem.
If no CoordinateSystem is specified, the global coordinate system is drawn.
The default actor consists of three colored lines of unit length along the unit vectors of the axes and three colored triangles representing the coordinate planes. This can be modified by the following parameters:
size: scale factor for the unit vectors. color: a set of three colors to use for x,y,z axes. colored_axes = False: draw black axes. draw_planes = False: do not draw the coordinate planes.
Draw the axes.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
Draws a (set of) grid(s) in one of the coordinate planes.
Draw the grid.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
Draws a set of 3 coordinate planes.
Draw the grid.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
A plane in a 3D scene.
Draw the grid.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Set the color of the Drawable.
An OpenGL actor representing a geometrical model.
The model can either be in Formex or Mesh format.
Return the vertives as a 2-dim array.
Set the color of the Actor.
Set the backside color of the Actor.
Set the Actors alpha value.
Draw the geometry on the specified canvas.
The drawing parameters not provided by the Actor itself, are derived from the canvas defaults.
mode and color can be overridden for the sole purpose of allowing the recursive use for modes ending on ‘wire’ (‘smoothwire’ or ‘flatwire’). In these cases, two drawing operations are done: one with mode=’wireframe’ and color=black, and one with mode=mode[:-4].
Allow picking of parts of the actor.
mode can be ‘element’, ‘edge’ or ‘point’
Return a GeomActor with a selection of this actor’s elements
Currently, the resulting Actor will not inherit the properties of its parent, but the eltype will be retained.
Set the linewidth of the Actor.
Set the linewidth of the Actor.
Functions defined in module actors
The ABAQUS .fil output file can be scanned and translated into a pyFormex script with the ‘postabq’ command. Use it as follows:
postabq job.fil > job.py
Then execute the created script from inside pyFormex.
Classes defined in module fe_post
Functions defined in module fe_post
(C) 2008 Benedict Verhegghe (benedict.verhegghe@ugent.be) I wrote this software in my free time, for my joy, not as a commissioned task. Any copyright claims made by my employer should therefore be considered void.
Distributed under the GNU General Public License, version 3 or later
Classes defined in module sendmail
Functions defined in module sendmail
Create an email message
‘to’ and ‘cc’ can be lists of email addresses.
Send an email message
‘message’ is an email message (e.g. returned by message()) ‘sender’ is a single mail address ‘to’ can be a list of addresses
This module uses the standard UNIX program ‘units’ (available from http://www.gnu.org/software/units/units.html) to do the actual conversions. Obviously, it will only work on systems that have this program available.
If you really insist on running another OS lacking the units command, have a look at http://home.tiscali.be/be052320/Unum.html and make an implementation based on unum. If you GPL it and send it to me, I might include it in this distribution.
Classes defined in module units
A class for handling and converting units of physical quantities.
The units class provides two built-in consistent units systems: International() and Engineering(). International() returns the standard International Standard units. Engineering() returns a consistent engineering system,which is very practical for use in mechanical engineering. It uses ‘mm’ for length and ‘MPa’ for pressure and stress. To keep it consistent however, the density is rather unpractical: ‘t/mm^3’. If you want to use t/m^3, you can make a custom units system. Beware with non-consistent unit systems though! The better practice is to allow any unit to be specified at input (and eventually requested for output), and to convert everyting internally to a consistent system. Apart from the units for usual physical quantities, Units stores two special purpose values in its units dictionary: ‘model’ : defines the length unit used in the geometrical model ‘problem’ : defines the unit system to be used in the problem. Defaults are: model=’m’, problem=’international’.
Add the units from dictionary un to the units system
Returns the predefined units for the specified system
Returns the international units system.
Returns a consistent engineering units system.
Read units from file with specified name.
The units file is an ascii file where each line contains a couple of words separated by a colon and a blank. The first word is the type of quantity, the second is the unit to be used for this quantity. Lines starting with ‘#’ are ignored. A ‘problem: system’ line sets all units to the corresponding value of the specified units system.
Get units list for the specified entitities.
If ent is a single entity, returns the corresponding unit if an entry ent exists in the current system or else returns ent unchanged. If ent is a list of entities, returns a list of corresponding units. Example: with the default units system:
Un = UnitsSystem()
Un.Get(['length','mass','float'])
returns: ['m', 'kg', 'float']
Functions defined in module units
Converts between conformable units.
This function converts the units ‘From’ to units ‘To’. The units should be conformable. The ‘From’ argument can (and usually does) include a value. The return value is the converted value without units. Thus: convertUnits(‘3.45 kg’,’g’) will return ‘3450’. This function is merely a wrapper around the GNU ‘units’ command, which should be installed for this function to work.
Compute inertia related quantities of a Formex. This comprises: center of gravity, inertia tensor, principal axes
Currently, these functions work on arrays of nodes, not on Formices! Use func(F,f) to operate on a Formex F.
Classes defined in module inertia
Functions defined in module inertia
Compute the centroids of the points of a set of elements.
X (nelems,nplex,3)
Compute the center of gravity of an array of points.
mass is an optional array of masses to be atributed to the points. The default is to attribute a mass=1 to all points.
If you also need the inertia tensor, it is more efficient to use the inertia() function.
Compute the inertia tensor of an array of points.
mass is an optional array of masses to be atributed to the points. The default is to attribute a mass=1 to all points.
Returns the principal values and axes of the inertia tensor.
If sort is True, they are sorted (maximum comes first). If right_handed is True, the axes define a right-handed coordinate system.
Classes defined in module config
A configuration class allowing Python expressions in the input.
The configuration settings are stored in the __dict__ of a Python object. An item ‘foo’ in the configuration ‘config’ can be accessed either as dictionary lookup (config['foo']) or as object attribute (config.foo).
The configuration object can be initialized from a multiline string or a text file (or any other object that allows iterating over strings).
The format of the config file/text is described hereafter.
All config lines should have the format: key = value, where key is a string and value is a Python expression The first ‘=’ character on the line is the delimiter between key and value. Blanks around both the key and the value are stripped. The value is then evaluated as a Python expression and stored in a variable with name specified by the key. This variable is available for use in subsequent configuration lines. It is an error to use a variable before it is defined. The key,value pair is also stored in the config dictionary, unless the key starts with an underscore (‘_’): this provides for local variables.
Lines starting with ‘#’ are comments and are ignored, as are empty and blank lines. Lines ending with ‘’ are continued on the next line. A line starting with ‘[‘ starts a new section. A section is nothing more than a Python dictionary inside the config dictionary. The section name is delimited by ‘[‘and ‘]’. All subsequent lines will be stored in the section dictionary instead of the toplevel dictionary.
All other lines are executed as python statements. This allows e.g. for importing modules.
Whole dictionaries can be inserted at once in the config with the update() function.
All defined variables while reading config files remain available for use in the config file statements, even over multiple calls to the read() function. Variables inserted with addSection() will not be available as individual variables though, but can be access as self['name'].
As an example, if your config file looks like:
aa = 'bb'
bb = aa
[cc]
aa = 'aa'
_n = 3
rng = range(_n)
the resulting configuration dictionary is {'aa': 'bb', 'bb': 'bb', 'cc': {'aa': 'aa', 'rng': [0, 1, 2]}}
As far as the resulting Config contents is concerned, the following are equivalent:
C.update({'key':'value'})
C.read("key='value'\n")
There is an important difference though: the second line will make a variable key (with value ‘value’) available in subsequent Config read() method calls.
Add a dictionary to the Config object.
The data, if specified, should be a valid Python dict. If no name is specified, the data are added to the top dictionary and will become attributes. If a name is specified, the data are added to the named attribute, which should be a dictionary. If the name does not specify a dictionary, an empty one is created, deleting the existing attribute.
If a name is specified, but no data, the effect is to add a new empty dictionary (section) with that name.
If removeLocals is set, keys starting with ‘_’ are removed from the data before updating the dictionary and not included in the config. This behaviour can be changed by setting removeLocals to false.
Read a configuration from a file or text
fil is a sequence of strings. Any type that allows a loop like for line in fil: to iterate over its text lines will do. This could be a file type, or a multiline text after splitting on ‘n’.
The function will try to react intelligently if a string is passed as argument. If the string contains at least one ‘n’, it will be interpreted as a multiline string and be splitted on ‘n’. Else, the string will be considered and a file with that name will be opened. It is an error if the file does not exist or can not be opened.
The function returns self, so that you can write: cfg = Config().
Write the config to the given file
The configuration data will be written to the file with the given name in a text format that is both readable by humans and by the Config.read() method.
The header and trailer arguments are strings that will be added at the start and end of the outputfile. Make sure they are valid Python statements (or comments) and that they contain the needed line separators, if you want to be able to read it back.
Return the keys in the config.
By default this descends one level of Dicts.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
Functions defined in module config
Format a dict in Python source representation.
Each (key,value) pair is formatted on a line of the form:
key = value
The resulting text is a legal Python script to define the items in the dict.
The script module provides the basic functions available in all pyFormex scripts. These functions are available in GUI and NONGUI applications, without the need to explicitely importing the script module.
Classes defined in module script
Functions defined in module script
Return the globals that are passed to the scripts on execution.
This basically contains the globals defined in draw.py, colors.py, and formex.py, as well as the globals from numpy. It also contains the definitions put into the pyformex.PF, by preference using the export() function. During execution of the script, the global variable __name__ will be set to either ‘draw’ or ‘script’ depending on whether the script was executed in the ‘draw’ module (–gui option) or the ‘script’ module (–nogui option).
Export the variables in the given dictionary.
Export a list of names and values.
Remove the global variables specified in list.
Delete all the global variables.
Rename the global variables in oldnames to newnames.
Return a list of all objects in dictionay that match criteria.
The return value is a list of keys from dic.
Returns the global object named name.
Return a value from the configuration.
Ask a question and present possible answers.
If no choices are presented, anything will be accepted. Else, the question is repeated until one of the choices is selected. If a default is given and the value entered is empty, the default is substituted. Case is not significant, but choices are presented unchanged. If no choices are presented, the string typed by the user is returned. Else the return value is the lowest matching index of the users answer in the choices list. Thus, ask(‘Do you agree’,[‘Y’,’n’]) will return 0 on either ‘y’ or ‘Y’ and 1 on either ‘n’ or ‘N’.
Show a Yes/No question and return True/False depending on answer.
Show an error message and wait for user acknowlegement.
Run a command and return its output.
If result == ‘status’, the exit status of the command is returned. If result == ‘output’, the output of the command is returned. If result == ‘both’, a tuple of status and output is returned.
Execute a Python script in specified globals.
Play a pyformex script scr. scr should be a valid Python text.
There is a lock to prevent multiple scripts from being executed at the same time. This implies that pyFormex scripts can currently not be recurrent. If a name is specified, set the global variable pyformex.scriptName to it when the script is started. If a filename is specified, set the global variable __file__ to it.
If step==True, an indefinite pause will be started after each line of the script that starts with ‘draw’. Also (in this case), each line (including comments) is echoed to the message board.
Set a breakpoint where the script can be halted on a signal.
If an argument is specified, it will be written to the message board.
The exitrequested signal is usually emitted by pressing a button in the GUI.
Set the exitrequested flag.
Play a formex script from file fn.
fn is the name of a file holding a pyFormex script. A list of arguments can be passed. They will be available under the name argv. This variable can be changed by the script and the resulting argv is returned to the caller.
Play the pyFormex script with filename fn or the current script file.
This function does nothing if no filename is passed or no current scriptfile was set. If arguments are given, they are passed to the script. If step is True, the script is executed in step mode.
Exit from the current script or from pyformex if no script running.
Quit the pyFormex program
This is a hard exit from pyFormex. It is normally not called directly, but results from an exit(True) call.
Run the application without gui.
Arguments are interpreted as names of script files, possibly interspersed with arguments for the scripts. Each running script should pop the required arguments from the list.
Update the current settings (store) with the values in res.
res is a dictionary with configuration values. The current settings will be update with the values in res.
If save is True, the changes will be stored to the user’s configuration file.
Print all Formices in globals()
Returns True if the specified path is writeable
Change the current working directory.
If fn is a directory name, the current directory is set to fn. If fn is a file name, the current directory is set to the directory holding fn. In either case, the current directory is stored in the user’s preferences for persistence between pyFormex invocations.
If fn does not exist, nothing is done.
Return the time elapsed since start of execution of the script.
Start the gui
Check that the specified path is writeable.
BEWARE: this only works if the path exists!
Check the pyFormex revision number.
By default, this function returns True if the pyFormex revision number is equal or larger than the specified number.
The comp argument may specify another comparison operator.
If pyFormex is unable to find its revision number (this is the case on very old versions) the test returns False.
Require a specified pyFormex revision number.
The arguments are like checkRevision. Ho9wever, this function will raise an error if the requirement fails.
Finds pattern in the pyFormex source .py files.
Uses the grep program to find all occurrences of some specified pattern text in the pyFormex source .py files (including the examples). Extra options can be passed to the grep command. See man grep for more info.
Returns the output of the grep command.
Save geometric objects to a pyFormex Geometry File.
A pyFormex Geometry File can store multiple geometrical objects in a native format that can be efficiently read back into pyformex. The format is portable over different pyFormex versions and even to other software.
Returns the number of objects written to the file.
Read a pyFormex Geometry File.
A pyFormex Geometry File can store multiple geometrical objects in a native format that can be efficiently read back into pyformex. The format is portable over different pyFormex versions and even to other software.
Returns a dictionary with the geometric objects read from the file. If object names were stored in the file, they will be used as the keys. Else, default names will be provided.
This module defines the Mesh class, which can be used to describe discrete geometrical models like those used in Finite Element models. It also contains some useful functions to create such models.
Classes defined in module mesh
A Mesh is a discrete geometrical model defined by nodes and elements.
In the Mesh geometrical data model, the coordinates of all the points are gathered in a single twodimensional array with shape (ncoords,3). The individual geometrical elements are then described by indices into the coordinates array.
This model has some advantages over the Formex data model (which stores all the points of all the elements by their coordinates):
The downside is that geometry generating algorithms are far more complex and possibly slower.
In pyFormex we therefore mostly use the Formex data model when creating geometry, but when we come to the point of exporting the geometry to file (and to other programs), a Mesh data model may be more adequate.
The Mesh data model has at least the following attributes:
If eltype is None, the eltype of the elems Connectivity table is used, and if that is missing, a default eltype is derived from the plexitude, by a call to the elements.elementType function. In most cases the eltype can be set automatically. The user can override the default value, but an error will occur if the element type does not exist or does not match the plexitude.
A Mesh can be initialized by its attributes (coords,elems,prop,eltype) or by a single geometric object that provides a toMesh() method.
Set the eltype from a character string.
This function allows the user to change the element type of the Mesh. The input is a character string with the name of one of the element defined in elements.py. The function will only allow to set a type matching the plexitude of the Mesh.
This method is seldom needed, because the applications should normally set the element type at creation time.
Create or destroy the property array for the Mesh.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Mesh. You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Mesh.
Return the properties as a numpy array (ndarray)
Return the highest property value used, or None
Return a list with unique property values.
Return a copy using the same data arrays
Convert a Mesh to a Formex.
The Formex inherits the element property numbers and eltype from the Mesh. Node property numbers however can not be translated to the Formex data model.
Convert a Mesh to a Surface.
If the plexitude of the mesh is 3, returns a TriSurface equivalent with the Mesh. Else, an error is raised.
Return the number of edges.
This returns the number of rows that would be in getEdges(), without actually constructing the edges. The edges are not fused!
Return the centroids of all elements of the Mesh.
The centroid of an element is the point whose coordinates are the mean values of all points of the element. The return value is a Coords object with nelems points.
Get the coords data.
Returns the full array of coordinates stored in the Mesh object. Note that this may contain points that are not used in the mesh. compact() will remove the unused points.
Get the elems data.
Returns the element connectivity data as stored in the object.
Get the entities of a lower dimensionality.
If the element type is defined in the elements module, this returns a Connectivity table with the entities of a lower dimensionality. The full list of entities with increasing dimensionality 0,1,2,3 is:
['points', 'edges', 'faces', 'cells' ]
If level is negative, the dimensionality returned is relative to that of the caller. If it is positive, it is taken absolute. Thus, for a Mesh with a 3D element type, getLowerEntities(-1) returns the faces, while for a 2D element type, it returns the edges. For both meshes however, getLowerEntities(+1) returns the edges.
By default, all entities for all elements are returned and common entities will appear multiple times. Specifying unique=True will return only the unique ones.
The return value may be an empty table, if the element type does not have the requested entities (e.g. the ‘point’ type). If the eltype is not defined, or the requested entity level is outside the range 0..3, the return value is None.
Return the set of unique node numbers in the Mesh.
This returns only the node numbers that are effectively used in the connectivity table. For a compacted Mesh, it is equal to `arange(self.nelems)`. This function also stores the result internally so that future requests can return it without the need for computing it again.
Return the nodal coordinates of the Mesh.
This returns only those points that are effectively used in the connectivity table. For a compacted Mesh, it is equal to the coords attribute.
Return the unique edges of all the elements in the Mesh.
This is a convenient function to create a table with the element edges. It is equivalent to `self.getLowerEntities(1,unique=True)`, but this also stores the result internally so that future requests can return it without the need for computing it again.
Return the unique faces of all the elements in the Mesh.
This is a convenient function to create a table with the element faces. It is equivalent to `self.getLowerEntities(2,unique=True)`, but this also stores the result internally so that future requests can return it without the need for computing it again.
Return the cells of the elements.
This is a convenient function to create a table with the element cells. It is equivalent to `self.getLowerEntities(3,unique=True)`, but this also stores the result internally so that future requests can return it without the need for computing it again.
Defines the elements in function of its edges.
This returns a Connectivity table with the elements defined in function of the edges. It is equivalent to `self.elems.insertLevel(self.eltype.getEntities(1))` but it also stores the definition of the edges and the returned element to edge connectivity.
Return the border of the Mesh.
Returns a Connectivity table with the free entities of the specified level of the Mesh. Free entities are entities that are only connected with a single element.
If return_indices==True, also returns an (nentities,2) index for inverse lookup of the higher entity (column 0) and its local lower entity number (column 1).
Return a Mesh with lower entities.
Returns a Mesh representing the lower entities of the specified level. If the Mesh has property numbers, the lower entities inherit the property of the element to which they belong.
By default, the resulting Mesh is compacted. Compaction can be switched off by setting compact=False.
Return the border of the Mesh.
This returns a Connectivity table with the border of the Mesh. The border entities are of a lower hierarchical level than the mesh itself. These entities become part of the border if they are connected to only one element.
If return_indices==True, it returns also an (nborder,2) index for inverse lookup of the higher entity (column 0) and its local border part number (column 1).
This is a convenient shorthand for
self.getFreeEntities(level=-1,return_indices=return_indices)
Return a Mesh with the border elements.
The returned Mesh is of the next lower hierarchical level and contains all the free entitites of that level. If the Mesh has property numbers, the border elements inherit the property of the element to which they belong.
By default, the resulting Mesh is compacted. Compaction can be switched off by setting compact=False.
This is a convenient shorthand for
self.getFreeEntitiesMesh(level=-1,compact=compact)
Return a Mesh with the free edge elements.
The returned Mesh is of the hierarchical level 1 (no mather what the level of the parent Mesh is) and contains all the free entitites of that level. If the Mesh has property numbers, the border elements inherit the property of the element to which they belong.
By default, the resulting Mesh is compacted. Compaction can be switched off by setting compact=False.
This is a convenient shorthand for
self.getFreeEntitiesMesh(level=1,compact=compact)
Return a Mesh where all elements have been reversed.
Reversing an element has the following meaning:
The reflect() method by default calls this method to undo the element reversal caused by the reflection operation.
Reflect the coordinates in one of the coordinate directions.
Parameters:
Find and store the elems connected to nodes.
Find the number of elems connected to nodes.
Find and store the elems connected to edges.
Find the number of elems connected to edges.
Find the elems adjacent to each elem via one or more nodes.
Find the number of elems which are adjacent by node to each elem.
Find the elems adjacent to elems via an edge.
Find the number of adjacent elems.
Create a report on the Mesh shape and size.
The report contains the number of nodes, number of elements, plexitude, element type, bbox and size.
Fuse the nodes of a Meshes.
All nodes that are within the tolerance limits of each other are merged into a single node.
The merging operation can be tuned by specifying extra arguments that will be passed to Coords:fuse().
Match nodes of Mesh with nodes of self.
This is a convenience function equivalent to:
self.coords.match(mesh.coords,**kargs)
See also Coords.match()
Match elems of Mesh with elems of self.
self and Mesh are same eltype meshes and are both without duplicates.
Elems are matched by their centroids.
Match faces of mesh with faces of self.
self and Mesh can be same eltype meshes or different eltype but of the same hierarchical type (i.e. hex8-quad4 or tet4 - tri3) and are both without duplicates.
Returns the indices array of the elems of self that matches the faces of mesh
Remove unconnected nodes and renumber the mesh.
Returns a mesh where all nodes that are not used in any element have been removed, and the nodes are renumbered to a compacter scheme.
Return a Mesh only holding the selected elements.
Returns a Mesh (or subclass) with only the selected elements.
See cselect for the complementary operation.
Return a mesh without the selected elements.
Returns a Mesh with all but the selected elements.
This is the complimentary operation of select.
Create average nodes from the existing nodes of a mesh.
nodsel is a local node selector as in selectNodes() Returns the (weighted) average coordinates of the points in the selector as (nelems*nnod,3) array of coordinates, where nnod is the length of the node selector. wts is a 1-D array of weights to be attributed to the points. Its length should be equal to that of nodsel.
Create nodes from the existing nodes of a mesh.
nodsel is a local node selector as in selectNodes() Returns the mean coordinates of the points in the selector as (nelems*nnod,3) array of coordinates, where nnod is the length of the node selector.
Add new nodes to elements.
newcoords is an (nelems,nnod,3) or`(nelems*nnod,3)` array of coordinates. Each element gets exactly nnod extra nodes from this array. The result is a Mesh with plexitude self.nplex() + nnod.
Add new nodes to elements by averaging existing ones.
nodsel is a local node selector as in selectNodes() Returns a Mesh where the mean coordinates of the points in the selector are added to each element, thus increasing the plexitude by the length of the items in the selector. The new element type should be set to correct value.
Return a mesh with subsets of the original nodes.
nodsel is an object that can be converted to a 1-dim or 2-dim array. Examples are a tuple of local node numbers, or a list of such tuples all having the same length. Each row of nodsel holds a list of local node numbers that should be retained in the new connectivity table.
Return a Mesh which holds only the elements with property val.
val is either a single integer, or a list/array of integers. The return value is a Mesh holding all the elements that have the property val, resp. one of the values in val. The returned Mesh inherits the matching properties.
If the Mesh has no properties, a copy with all elements is returned.
Return a Mesh without the elements with property val.
This is the complementary method of Mesh.withProp(). val is either a single integer, or a list/array of integers. The return value is a Mesh holding all the elements that do not have the property val, resp. one of the values in val. The returned Mesh inherits the matching properties.
If the Mesh has no properties, a copy with all elements is returned.
Partition a Mesh according to its propery values.
Returns a dict with the property values as keys and the corresponding partitions as values. Each value is a Mesh instance. It the Mesh has no props, an empty dict is returned.
Split a mesh in n parts, distributing the elements randomly.
Returns a list of n Mesh objects, constituting together the same Mesh as the original. The elements are randomly distributed over the subMeshes.
By default, the Meshes are compacted. Compaction may be switched off for efficiency reasons.
Convert a Mesh to another element type.
Converting a Mesh from one element type to another can only be done if both element types are of the same dimensionality. Thus, 3D elements can only be converted to 3D elements.
The conversion is done by splitting the elements in smaller parts and/or by adding new nodes to the elements.
Not all conversions between elements of the same dimensionality are possible. The possible conversion strategies are implemented in a table. New strategies may be added however.
The return value is a Mesh of the requested element type, representing the same geometry (possibly approximatively) as the original mesh.
If the requested conversion is not implemented, an error is raised.
Convert choosing randomly between choices
Reduce degenerate elements to lower plexitude elements.
This will try to reduce the degenerate elements of the mesh to elements of a lower plexitude. If a target element type is given, only the matching reduce scheme is tried. Else, all the target element types for which a reduce scheme from the Mesh eltype is available, will be tried.
The result is a list of Meshes of which the last one contains the elements that could not be reduced and may be empty. Property numbers propagate to the children.
Split a Mesh in degenerate and non-degenerate elements.
If autofix is True, the degenerate elements will be tested against known degeneration patterns, and the matching elements will be transformed to non-degenerate elements of a lower plexitude.
The return value is a list of Meshes. The first holds the non-degenerate elements of the original Mesh. The last holds the remaining degenerate elements. The intermediate Meshes, if any, hold elements of a lower plexitude than the original. These may still contain degenerate elements.
Remove the degenerate elements from a Mesh.
Returns a Mesh with all degenerate elements removed.
Remove the duplicate elements from a Mesh.
Duplicate elements are elements that consist of the same nodes, by default in no particular order. Setting permutations=False will only consider elements with the same nodes in the same order as duplicates.
Returns a Mesh with all duplicate elements removed.
Renumber the nodes of a Mesh in the specified order.
order is an index with length equal to the number of nodes. The index specifies the node number that should come at this position. Thus, the order values are the old node numbers on the new node number positions.
order can also be a predefined value that will generate the node index automatically:
Renumber the elements of a Mesh.
Parameters:
See also: Connectivity.reorder()
Connect a sequence of toplogically congruent Meshes into a hypermesh.
Parameters:
coordslist: either a list of Coords instances, all having the same shape as self.coords, or a single Mesh instance whose coords attribute has the same shape.
If it is a list of Coords, consider a list of Meshes obtained by combining each Coords object with the connectivity table, element type and property numbers of the current Mesh. The return value then is the hypermesh obtained by connecting each consecutive slice of (degree+1) of these meshes. The hypermesh has a dimensionality that is one higher than the original Mesh (i.e. points become lines, lines become surfaces, surfaces become volumes). The resulting elements will be of the given degree in the direction of the connection. Notice that the coords of the current Mesh are not used, unless these coords are explicitely included into the specified coordslist. In many cases self.coords will be the first item in coordslist, but it could occur anywhere in the list or even not at all. The number of Coords items in the list should be a multiple of degree plus 1.
Specifying a single Mesh instead of a list of Coords is just a convenience for the often occurring situation of connecting a Mesh (self) with another one (mesh) having the same connectivity: in this case the list of Coords will automatically be set to [ self.coords, mesh.coords ]. The degree should be 1 in this case.
degree: degree of the connection. Currently only degree 1 and 2 are supported.
loop: if True, the connections with loop around the list and connect back to the first. This is accomplished by adding the first Coords item back at the end of the list.
div: Either an integer, or a sequence of float numbers (usually in the range ]0.0..1.0]). With this parameter the generated elements can be further subdivided along the connection direction. If an int is given, the connected elements will be divided into this number of elements along the connection direction. If a sequence of float numbers is given, the numbers specify the relative distance along the connection direction where the elements should end. If the last value in the sequence is not equal to 1.0, there will be a gap between the consecutive connections.
eltype: the element type of the constructed hypermesh. Normally, this is set automatically from the base element type and the connection degree. If a different element type is specified, a final conversion to the requested element type is attempted.
Extrude a Mesh in one of the axes directions.
Returns a new Mesh obtained by extruding the given Mesh over n steps of length step in direction of axis dir.
Revolve a Mesh around an axis.
Returns a new Mesh obtained by revolving the given Mesh over an angle around an axis in n steps, while extruding the mesh from one step to the next. This extrudes points into lines, lines into surfaces and surfaces into volumes.
Sweep a mesh along a path, creating an extrusion
Returns a new Mesh obtained by sweeping the given Mesh over a path. The returned Mesh has double plexitude of the original. The operation is similar to the extrude() method, but the path can be any 3D curve.
This function is usually used to extrude points into lines, lines into surfaces and surfaces into volumes. By default it will try to fix the connectivity ordering where appropriate. If autofix is switched off, the connectivities are merely stacked, and the user may have to fix it himself.
Currently, this function produces the correct element type, but the geometry .
Return a smoothened mesh.
Smoothing algorithm based on lowpass filters.
If edg is True, the algorithm tries to smooth the outer border of the mesh seperately to reduce mesh shrinkage.
Higher values of k can reduce shrinkage even more (up to a point where the mesh expands), but will result in less smoothing per iteration.
Concatenate a list of meshes of the same plexitude and eltype
Merging of the nodes can be tuned by specifying extra arguments that will be passed to Coords:fuse().
This is a class method, and should be invoked as follows:
Mesh.concatenate([mesh0,mesh1,mesh2])
Flag elements having nodal coordinates between min and max.
This function is very convenient in clipping a Mesh 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 Mesh
The test plane can be defined 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 compaitble 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.
nodes specifies which nodes are taken into account in the comparisons. It should be one of the following:
The default (‘all’) will flag all the elements that have all their nodes between the planes x=min and x=max, i.e. the elements that fall completely between these planes. One of the two clipping planes may be left unspecified.
Return a Mesh with all the elements where t>0.
t should be a 1-D integer array with length equal to the number of elements of the Mesh. The resulting Mesh will contain all elements where t > 0.
This is the complement of clip, returning a Mesh where t<=0.
Return the Mesh clipped at plane (p,n).
This is a convenience function returning the part of the Mesh at one side of the plane (p,n)
Return the signed volume of all the mesh elements
For a ‘tet4’ tetraeder Mesh, the volume of the elements is calculated as 1/3 * surface of base * height.
For other Mesh types the volumes are calculated by first splitting the elements into tetraeder elements.
The return value is an array of float values with length equal to the number of elements. If the Mesh conversion to tetraeder does not succeed, the return value is None.
Return the total volume of a Mesh.
If the Mesh can not be converted to tet4 type, 0 is returned
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
Functions defined in module mesh
Merge all the nodes of a list of node sets.
Merging the nodes creates a single Coords object containing all nodes, and the indices to find the points of the original node sets in the merged set.
Parameters:
Returns:
The merging operation can be tuned by specifying extra arguments that will be passed to Coords.fuse().
Merge all the nodes of a list of Meshes.
Each item in meshes is a Mesh instance. The return value is a tuple with:
The merging operation can be tuned by specifying extra arguments that will be passed to Coords:fuse(). Setting fuse=False will merely concatenate all the mesh.coords, but not fuse them.
This module defines classes and functions specialized for handling one-dimensional geometry in pyFormex. These may be straight lines, polylines, higher order curves and collections thereof. In general, the curves are 3D, but special cases may be created for handling plane curves.
Classes defined in module curve
Base class for curve type classes.
This is a virtual class intended to be subclassed. It defines the common definitions for all curve types. The subclasses should at least define the following:
sub_points(t,j)
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values t in part j
t can be an array of parameter values, j is a single segment number.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values t in part j
t can be an array of parameter values, j is a single segment number.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a PolyLine approximation of the curve
If no ntot is given, the curve is approximated by ndiv straight segments over each part of the curve. If ntot is given, the curve is approximated by ntot straight segments over the total curve. This is based on a first approximation with ndiv segments over each part.
Convert a curve to a Formex.
This creates a polyline approximation as a plex-2 Formex. This is mainly used for drawing curves that do not implement their own drawing routines.
The method can be passed the same arguments as the approx method.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return a deep copy of the object.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
A class representing a series of straight line segments.
coords is a (npts,3) shaped array of coordinates of the subsequent vertices of the polyline (or a compatible data object). If closed == True, the polyline is closed by connecting the last point to the first. This does not change the vertex data.
The control parameter has the same meaning as coords and is added for symmetry with other Curve classes. If specified, it will override the coords argument.
Close a PolyLine.
If the PolyLine is already closed, it is returned unchanged. Else it is closed by adding a segment from the last to the first point (even if these are coincident).
..warning :: This method changes the PolyLine inplace.
Open a closed PolyLine.
If the PolyLine is closed, it is opened by removing the last segment. Else, it is returned unchanged.
..warning :: This method changes the PolyLine inplace.
Use split() if you want to open the PolyLine without losing a segment.
Return the polyline as a Formex.
Convert the polyLine to a plex-2 Mesh.
The returned Mesh is equivalent with the PolyLine.
Return the points at values t in part j
Return the points at value,part pairs (t,j)
Return the unit direction vectors at values t in part j.
Return the vectors of each point to the next one.
The vectors are returned as a Coords object. If the curve is not closed, the number of vectors returned is one less than the number of points.
Returns unit vectors in the direction of the next point.
This directions are returned as a Coords object with the same number of elements as the point set.
If two subsequent points are identical, the first one gets the direction of the previous segment. If more than two subsequent points are equal, an invalid direction (NaN) will result.
If the curve is not closed, the last direction is set equal to the penultimate.
If return_doubles is True, the return value is a tuple of the direction and an index of the points that are identical with their follower.
Returns the average directions at points.
For each point the returned direction is the average of the direction from the preceding point to the current, and the direction from the current to the next point.
If the curve is open, the first and last direction are equal to the direction of the first, resp. last segment.
Where two subsequent points are identical, the average directions are set equal to those of the segment ending in the first and the segment starting from the last.
Return the length of the parts of the curve.
Returns the parameter values for relative curve lengths div.
div is a list of relative curve lengths (from 0.0 to 1.0). As a convenience, a single integer value may be specified, in which case the relative curve lengths are found by dividing the interval [0.0,1.0] in the specified number of subintervals.
The function returns a list with the parameter values for the points at the specified relative lengths.
Return the same curve with the parameter direction reversed.
Split the curve at the point i.
Returns a list of open PolyLines: one, if the PolyLine is closed or i is one of the endpoints of an open PolyLine, two in other cases.
Return the parts of the polyline at one or both sides of a plane.
If side is ‘+’ or ‘-‘, return a list of PolyLines with the parts at the positive or negative side of the plane.
For any other value, returns a tuple of two lists of PolyLines, the first one being the parts at the positive side.
p is a point specified by 3 coordinates. n is the normal vector to a plane, specified by 3 components.
Append another PolyLine to this one.
Returns the concatenation of two open PolyLines. Closed PolyLines cannot be concatenated.
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return a deep copy of the object.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a PolyLine approximation of the curve
If no ntot is given, the curve is approximated by ndiv straight segments over each part of the curve. If ntot is given, the curve is approximated by ntot straight segments over the total curve. This is based on a first approximation with ndiv segments over each part.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
A Line is a PolyLine with exactly two points.
Parameters:
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return a deep copy of the object.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a PolyLine approximation of the curve
If no ntot is given, the curve is approximated by ndiv straight segments over each part of the curve. If ntot is given, the curve is approximated by ntot straight segments over the total curve. This is based on a first approximation with ndiv segments over each part.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Close a PolyLine.
If the PolyLine is already closed, it is returned unchanged. Else it is closed by adding a segment from the last to the first point (even if these are coincident).
..warning :: This method changes the PolyLine inplace.
Open a closed PolyLine.
If the PolyLine is closed, it is opened by removing the last segment. Else, it is returned unchanged.
..warning :: This method changes the PolyLine inplace.
Use split() if you want to open the PolyLine without losing a segment.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
Return the polyline as a Formex.
Convert the polyLine to a plex-2 Mesh.
The returned Mesh is equivalent with the PolyLine.
Return the points at values t in part j
Return the points at value,part pairs (t,j)
Return the unit direction vectors at values t in part j.
Return the vectors of each point to the next one.
The vectors are returned as a Coords object. If the curve is not closed, the number of vectors returned is one less than the number of points.
Returns unit vectors in the direction of the next point.
This directions are returned as a Coords object with the same number of elements as the point set.
If two subsequent points are identical, the first one gets the direction of the previous segment. If more than two subsequent points are equal, an invalid direction (NaN) will result.
If the curve is not closed, the last direction is set equal to the penultimate.
If return_doubles is True, the return value is a tuple of the direction and an index of the points that are identical with their follower.
Returns the average directions at points.
For each point the returned direction is the average of the direction from the preceding point to the current, and the direction from the current to the next point.
If the curve is open, the first and last direction are equal to the direction of the first, resp. last segment.
Where two subsequent points are identical, the average directions are set equal to those of the segment ending in the first and the segment starting from the last.
Return the length of the parts of the curve.
Returns the parameter values for relative curve lengths div.
div is a list of relative curve lengths (from 0.0 to 1.0). As a convenience, a single integer value may be specified, in which case the relative curve lengths are found by dividing the interval [0.0,1.0] in the specified number of subintervals.
The function returns a list with the parameter values for the points at the specified relative lengths.
Return the same curve with the parameter direction reversed.
Split the curve at the point i.
Returns a list of open PolyLines: one, if the PolyLine is closed or i is one of the endpoints of an open PolyLine, two in other cases.
Return the parts of the polyline at one or both sides of a plane.
If side is ‘+’ or ‘-‘, return a list of PolyLines with the parts at the positive or negative side of the plane.
For any other value, returns a tuple of two lists of PolyLines, the first one being the parts at the positive side.
p is a point specified by 3 coordinates. n is the normal vector to a plane, specified by 3 components.
Append another PolyLine to this one.
Returns the concatenation of two open PolyLines. Closed PolyLines cannot be concatenated.
A class representing a Bezier spline curve of degree 1, 2 or 3.
A Bezier spline of degree d is a continuous curve consisting of nparts successive parts, where each part is a Bezier curve of the same degree. Currently pyFormex can model linear, quadratic and cubic BezierSplines. A linear BezierSpline is equivalent to a PolyLine, which has more specialized methods than the BezierSpline, so it might be more sensible to use a PolyLine instead of the linear BezierSpline.
A Bezier curve of degree d is determined by d+1 control points, of which the first and the last are on the curve, while the intermediate d-1 points are not. Since the end point of one part is the begin point of the next part, a BezierSpline is described by ncontrol=d*nparts+1 control points if the curve is open, or ncontrol=d*nparts if the curve is closed.
The constructor provides different ways to initialize the full set of control points. In many cases the off-curve control points can be generated automatically.
Parameters:
coords : array_like (npoints,3) The points that are on the curve. For an open curve, npoints=nparts+1, for a closed curve, npoints = nparts. If not specified, the on-curve points should be included in the control argument.
deriv : array_like (npoints,3) or (2,3) If specified, it gives the direction of the curve at all points or at the endpoints only for a shape (2,3) array. For points where the direction is left unspecified or where the specified direction contains a NaN value, the direction is calculated as the average direction of the two line segments ending in the point. This will also be used for points where the specified direction contains a value NaN. In the two endpoints of an open curve however, this average direction can not be calculated: the two control points in these parts are set coincident.
curl : float The curl parameter can be set to influence the curliness of the curve in between two subsequent points. A value curl=0.0 results in straight segments. The higher the value, the more the curve becomes curled.
control : array(nparts,2,3) or array(ncontrol,3) If coords was specified, this should be a (nparts,2,3) array with the intermediate control points, two for each part.
If coords was not specified, this should be the full array of ncontrol control points for the curve. The number of points should be a multiple of 3 plus 1. If the curve is closed, the last point is equal to the first and does not need to a multiple of 3 is also allowed, in which case the first point will be appended as last.
If not specified, the control points are generated automatically from the coords, deriv and curl arguments. If specified, they override these parameters.
closed : boolean If True, the curve will be continued from the last point back to the first to create a closed curve.
degree: int (1, 2 or 3) Specfies the degree of the curve. Default is 3.
endzerocurv : boolean or tuple of two booleans. Specifies the end conditions for an open curve. If True, the end curvature will be forced to zero. The default is to use maximal continuity of the curvature. The value may be set to a tuple of two values to specify different conditions for both ends. This argument is ignored for a closed curve.
Return the points on the curve.
This returns a Coords object of shape [nparts+1]. For a closed curve, the last point will be equal to the first.
Return the points off the curve (the control points)
This returns a Coords object of shape [nparts,ndegree-1], or an empty Coords if degree <= 1.
Returns the points defining part j of the curve.
Return the points at values t in part j.
Return the unit direction vectors at values t in part j.
Return the curvature at values t in part j.
Return the arc length integrand at value t in part j.
Return the length of the parts of the curve.
Convert the BezierSpline to a Mesh.
For degrees 1 or 2, the returned Mesh is equivalent with the BezierSpline, and will have element type ‘line1’, resp. ‘line2’.
For degree 3, the returned Mesh will currently be a quadratic approximation with element type ‘line2’.
Return a PolyLine approximation of the curve.
tol is a tolerance value for the flatness of the curve. The flatness of each part is calculated as the maximum orthogonal distance of its intermediate control points from the straight segment through its end points.
Parts for which the distance is larger than tol are subdivided using de Casteljau’s algorithm. The subdivision stops if all parts are sufficiently flat. The return value is a PolyLine connecting the end points of all parts.
Extend the curve beyond its endpoints.
This function will add a Bezier curve before the first part and/or after the last part by applying de Casteljau’s algorithm on this part.
Return the same curve with the parameter direction reversed.
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return a deep copy of the object.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a PolyLine approximation of the curve
If no ntot is given, the curve is approximated by ndiv straight segments over each part of the curve. If ntot is given, the curve is approximated by ntot straight segments over the total curve. This is based on a first approximation with ndiv segments over each part.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Convert a curve to a Formex.
This creates a polyline approximation as a plex-2 Formex. This is mainly used for drawing curves that do not implement their own drawing routines.
The method can be passed the same arguments as the approx method.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
A class representing a cardinal spline.
Create a natural spline through the given points.
The Cardinal Spline with given tension is a Bezier Spline with curl :math: curl = ( 1 - tension) / 3 The separate class name is retained for compatibility and convenience. See CardinalSpline2 for a direct implementation (it misses the end intervals of the point set).
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return a deep copy of the object.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a PolyLine approximation of the curve
If no ntot is given, the curve is approximated by ndiv straight segments over each part of the curve. If ntot is given, the curve is approximated by ntot straight segments over the total curve. This is based on a first approximation with ndiv segments over each part.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Convert a curve to a Formex.
This creates a polyline approximation as a plex-2 Formex. This is mainly used for drawing curves that do not implement their own drawing routines.
The method can be passed the same arguments as the approx method.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
Return the points on the curve.
This returns a Coords object of shape [nparts+1]. For a closed curve, the last point will be equal to the first.
Return the points off the curve (the control points)
This returns a Coords object of shape [nparts,ndegree-1], or an empty Coords if degree <= 1.
Returns the points defining part j of the curve.
Return the points at values t in part j.
Return the unit direction vectors at values t in part j.
Return the curvature at values t in part j.
Return the arc length integrand at value t in part j.
Return the length of the parts of the curve.
Convert the BezierSpline to a Mesh.
For degrees 1 or 2, the returned Mesh is equivalent with the BezierSpline, and will have element type ‘line1’, resp. ‘line2’.
For degree 3, the returned Mesh will currently be a quadratic approximation with element type ‘line2’.
Return a PolyLine approximation of the curve.
tol is a tolerance value for the flatness of the curve. The flatness of each part is calculated as the maximum orthogonal distance of its intermediate control points from the straight segment through its end points.
Parts for which the distance is larger than tol are subdivided using de Casteljau’s algorithm. The subdivision stops if all parts are sufficiently flat. The return value is a PolyLine connecting the end points of all parts.
Extend the curve beyond its endpoints.
This function will add a Bezier curve before the first part and/or after the last part by applying de Casteljau’s algorithm on this part.
Return the same curve with the parameter direction reversed.
A class representing a cardinal spline.
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values t in part j
t can be an array of parameter values, j is a single segment number.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return a deep copy of the object.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a PolyLine approximation of the curve
If no ntot is given, the curve is approximated by ndiv straight segments over each part of the curve. If ntot is given, the curve is approximated by ntot straight segments over the total curve. This is based on a first approximation with ndiv segments over each part.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Convert a curve to a Formex.
This creates a polyline approximation as a plex-2 Formex. This is mainly used for drawing curves that do not implement their own drawing routines.
The method can be passed the same arguments as the approx method.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
A class representing a natural spline.
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values t in part j
t can be an array of parameter values, j is a single segment number.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return a deep copy of the object.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a PolyLine approximation of the curve
If no ntot is given, the curve is approximated by ndiv straight segments over each part of the curve. If ntot is given, the curve is approximated by ntot straight segments over the total curve. This is based on a first approximation with ndiv segments over each part.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Convert a curve to a Formex.
This creates a polyline approximation as a plex-2 Formex. This is mainly used for drawing curves that do not implement their own drawing routines.
The method can be passed the same arguments as the approx method.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
A class representing a circular arc.
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values t in part j
t can be an array of parameter values, j is a single segment number.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return a deep copy of the object.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a PolyLine approximation of the curve
If no ntot is given, the curve is approximated by ndiv straight segments over each part of the curve. If ntot is given, the curve is approximated by ntot straight segments over the total curve. This is based on a first approximation with ndiv segments over each part.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Convert a curve to a Formex.
This creates a polyline approximation as a plex-2 Formex. This is mainly used for drawing curves that do not implement their own drawing routines.
The method can be passed the same arguments as the approx method.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
A class representing a circular arc.
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values t in part j
t can be an array of parameter values, j is a single segment number.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return a deep copy of the object.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Convert a curve to a Formex.
This creates a polyline approximation as a plex-2 Formex. This is mainly used for drawing curves that do not implement their own drawing routines.
The method can be passed the same arguments as the approx method.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
Return a PolyLine approximation of the Arc.
Approximates the Arc by a sequence of inscribed straight line segments.
If ndiv is specified, the arc is divided in pecisely ndiv segments.
If ndiv is not given, the number of segments is determined from the chordal distance tolerance. It will guarantee that the distance of any point of the arc to the chordal approximation is less or equal than chordal times the radius of the arc.
A class representing a spiral curve.
Return start and end points of the curve.
Returns a Coords with two points, or None if the curve is closed.
Return the points at values t in part j
t can be an array of parameter values, j is a single segment number.
Return the points at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the directions at values t in part j
t can be an array of parameter values, j is a single segment number.
Return the directions at values,parts given by zip(t,j)
t and j can both be arrays, but should have the same length.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return the points at parameter values t.
Parameter values are floating point values. Their integer part is interpreted as the curve segment number, and the decimal part goes from 0 to 1 over the segment.
Return a sequence of points on the Curve.
The extend parameter allows to extend the curve beyond the endpoints. The normal parameter space of each part is [0.0 .. 1.0]. The extend parameter will add a curve with parameter space [-extend[0] .. 0.0] for the first part, and a curve with parameter space [1.0 .. 1 + extend[0]] for the last part. The parameter step in the extensions will be adjusted slightly so that the specified extension is a multiple of the step size. If the curve is closed, the extend parameter is disregarded.
Return a deep copy of the object.
Return the total length of the curve.
This is only available for curves that implement the ‘lengths’ method.
Return a PolyLine approximation of the curve
If no ntot is given, the curve is approximated by ndiv straight segments over each part of the curve. If ntot is given, the curve is approximated by ntot straight segments over the total curve. This is based on a first approximation with ndiv segments over each part.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Convert a curve to a Formex.
This creates a polyline approximation as a plex-2 Formex. This is mainly used for drawing curves that do not implement their own drawing routines.
The method can be passed the same arguments as the approx method.
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
Functions defined in module curve
Create a spline approximation of a circle.
The returned circle lies in the x,y plane, has its center at (0,0,0) and has a radius 1.
In the current implementation it is approximated by a bezier spline with curl 0.375058 through 8 points.
Convert a Formex to a Curve.
The following Formices can be converted to a Curve: - plex 2 : to PolyLine - plex 3 : to BezierSpline with degree=2 - plex 4 : to BezierSpline
Classes defined in module timer
A class for measuring elapsed time.
A Timer object measures elapsed real time since a specified time, which by default is the time of the creation of the Timer.
Parameters:
(Re)Start the timer.
Sets the start time of the timer to the specified value, or to the current time by default.
Parameters:
Read the timer.
Returns the elapsed time since the last reset (or the creation of the timer) as a datetime.timedelta object.
If reset=True, the timer is reset to the time of reading.
Return the timer readings in seconds.
The default return value is a rounded integer number of seconds. With rounded == False, a floating point value with granularity of 1 microsecond is returned.
If reset=True, the timer is reset at the time of reading.
Functions defined in module timer
The nurbs module defines functions and classes to manipulate NURBS curves and surface in pyFormex.
Classes defined in module nurbs
A collection of points represented by their homogeneous coordinates.
While most of the pyFormex implementation is based on the 3D Cartesian coordinates class Coords, some applications may benefit from using homogeneous coordinates. The class Coords4 provides some basic functions and conversion to and from cartesian coordinates. Through the conversion, all other pyFormex functions, such as transformations, are available.
Coords4 is implemented as a float type numpy.ndarray whose last axis has a length equal to 4. Each set of 4 values (x,y,z,w) along the last axis represents a single point in 3D space. The cartesian coordinates of the point are obtained by dividing the first three values by the fourth: (x/w, y/w, z/w). A zero w-value represents a point at infinity. Converting such points to Coords will result in Inf or NaN values in the resulting object.
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.
Just like Coords, the class Coords4 is derived from numpy.ndarray.
Parameters
Normalize the homogeneous coordinates.
Two sets of homogeneous coordinates that differ only by a multiplicative constant refer to the same points in cartesian space. Normalization of the coordinates is a way to make the representation of a single point unique. Normalization is done so that the last component (w) is equal to 1.
The normalization of the coordinates is done in place.
Warning
Normalizing points at infinity will result in Inf or NaN values.
Denormalizes the homogeneous coordinates.
This multiplies the homogeneous coordinates with the values w. w normally is a constant or an array with shape self.shape[:-1] + (1,). It then multiplies all 4 coordinates of a point with the same value, thus resulting in a denormalization while keeping the position of the point unchanged.
The denormalization of the coordinates is done in place. If the Coords4 object was normalized, it will have precisely w as its 4-th coordinate value after the call.
Convert homogeneous coordinates to cartesian coordinates.
Returns a Coords object with the cartesian coordinates of the points. Points at infinity (w=0) will result in Inf or NaN value. If there are no points at infinity, the resulting Coords point set is equivalent to the Coords4 one.
Return the total number of points.
Return the total number of points.
Return the x-plane
Return the y-plane
Return the z-plane
Return the w-plane
Return the bounding box of a set of points.
Returns the bounding box of the cartesian coordinates of the object.
Graphical representation
A NURBS curve
The Nurbs curve is defined by nctrl control points, a degree (>= 1) and a knot vector with knots = nctrl+degree+1 parameter values.
The knots vector should hold nknots values in ascending order. The values are only defined upon a multiplicative constant and will be normalized to set the last value to 1. Sensible default values are constructed automatically by calling knotVector().
If no knots are given and no degree is specified, the degree is set to the number of control points - 1 if the curve is blended. If not blended, the degree is not set larger than 3.
Return the bounding box of the NURBS curve.
Return the points on the Nurbs curve at given parametric values.
Parameters:
Returns: (nu,3) shaped Coords with nu points at the specified parametric values.
Returns the points and derivatives up to d at parameter values at
Returns the points at the knot values.
The multiplicity of the knots is retained in the points set.
Insert a set of knots in the curve.
u is a vector with knot parameter values to be inserted into the curve. The control points are adapted to keep the curve unchanged.
Returns a Nurbs curve equivalent with the original but with the specified knot values inserted in the knot vector, and the control points adapted.
Decomposes a curve in subsequent Bezier curves.
Returns an equivalent unblended Nurbs.
Graphical representation
A NURBS surface
The Nurbs surface is defined as a tensor product of NURBS curves in two parametrical directions u and v. The control points form a grid of (nctrlu,nctrlv) points. The other data are like those for a NURBS curve, but need to be specified as a tuple for the (u,v) directions.
The knot values are only defined upon a multiplicative constant, equal to the largest value. Sensible default values are constructed automatically by a call to the knotVector() function.
If no knots are given and no degree is specified, the degree is set to the number of control points - 1 if the curve is blended. If not blended, the degree is not set larger than 3.
Warning
This is a class under development!
Return the bounding box of the NURBS surface.
Return the points on the Nurbs surface at given parametric values.
Parameters:
Returns: (nu,3) shaped Coords with nu points at the specified parametric values.
Graphical representation
Functions defined in module nurbs
Create a global interpolation NurbsCurve.
Given an ordered set of points Q, the globalInterpolationCurve is a NURBS curve of the given degree, passing through all the points.
Returns a NurbsCurve through the given point set. The number of control points is the same as the number of input points.
The procedure works by computing the control points that will produce a NurbsCurve with the given points occurring at predefined parameter values. The strategy to set this values uses a parameter as exponent. Different values produce (slighly) different curves. Typical values are:
0.0: equally spaced (not recommended) 0.5: centripetal (default, recommended) 1.0: chord length (often used)
Create a set of uniformly distributed parameter values in a range.
Parameters:
Example:
>>> uniformParamValues(4).tolist()
[0.0, 0.25, 0.5, 0.75, 1.0]
>>> uniformParamValues(0).tolist()
[0.5]
>>> uniformParamValues(-1).tolist()
[]
>>> uniformParamValues(2,1.5,2.5).tolist()
[1.5, 2.0, 2.5]
Compute sensible knot vector for a Nurbs curve.
A knot vector is a sequence of non-decreasing parametric values. These values define the knots, i.e. the points where the analytical expression of the Nurbs curve may change. The knot values are only meaningful upon a multiplicative constant, and they are usually normalized to the range [0.0..1.0].
A Nurbs curve with nctrl points and of given degree needs a knot vector with nknots = nctrl+degree+1 values. A degree curve needs at least nctrl = degree+1 control points, and thus at least nknots = 2*(degree+1) knot values.
To make an open curve start and end in its end points, it needs knots with multiplicity degree+1 at its ends. Thus, for an open blended curve, the default policy is to set the knot values at the ends to 0.0, resp. 1.0, both with multiplicity degree+1, and to spread the remaining nctrl - degree - 1 values equally over the interval.
For a closed (blended) curve, the knots are equally spread over the interval, all having a multiplicity 1 for maximum continuity of the curve.
For an open unblended curve, all internal knots get multiplicity degree. This results in a curve that is only one time continuously derivable at the knots, thus the curve is smooth, but the curvature may be discontinuous. There is an extra requirement in this case: nctrl sohuld be a multiple of degree plus 1.
Example:
>>> print knotVector(7,3)
[ 0. 0. 0. 0. 0.25 0.5 0.75 1. 1. 1. 1. ]
>>> print knotVector(7,3,closed=True)
[ 0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
>>> print knotVector(7,3,blended=False)
[ 0. 0. 0. 0. 1. 1. 1. 2. 2. 2. 2.]
Convert cartesian coordinates to homogeneous
Returns a Coords4 object corresponding to the input cartesian coordinates.
Compute points on a Bezier curve
Parameters: P is an array with n+1 points defining a Bezier curve of degree n. u is a vector with nu parameter values between 0 and 1.
Returns: An array with the nu points of the Bezier curve corresponding with the specified parametric values. ERROR: currently u is a single paramtric value!
See also: examples BezierCurve, Casteljou
Compute points on a Bezier curve using deCasteljou algorithm
Parameters: P is an array with n+1 points defining a Bezier curve of degree n. u is a single parameter value between 0 and 1.
Returns: A list with point sets obtained in the subsequent deCasteljou approximations. The first one is the set of control points, the last one is the point on the Bezier curve.
This function works with Coords as well as Coords4 points.
Convert a BezierSpline to NurbsCurve
Returns the 3 Frenet vectors and the curvature.
d1,d2 are the first and second derivatives at points of a curve. d3, if given, is the third derivative. Returns 3 normalized vectors along tangent, normal, binormal plus the curvature. if d3 is give, also returns the torsion of the curve.
This module contains some functions, data and classes for generating Formex structures representing simple geometric shapes. You need to import this module in your scripts to have access to its contents.
Classes defined in module simple
Functions defined in module simple
Return a Formex with one of the predefined named shapes.
This is a convenience function returning a plex-2 Formex constructed from one of the patterns defined in the simple.Pattern dictionary. Currently, the following pattern names are defined: ‘line’, ‘angle’, ‘square’, ‘plus’, ‘cross’, ‘diamond’, ‘rtriangle’, ‘cube’, ‘star’, ‘star3d’. See the Pattern example.
Create a regular grid between points x0 and x1.
x0 and x1 are n-dimensional points (usually 1D, 2D or 3D). The space between x0 and x1 is divided in nx equal parts. nx should have the same dimension as x0 and x1. The result is a rectangular grid of coordinates in an array with shape ( nx[0]+1, nx[1]+1, ..., n ).
Return a Formex which is a point, by default at the origin.
Each of the coordinates can be specified and is zero by default.
Return a Formex which is a line between two specified points.
p1: first point, p2: second point The line is split up in n segments.
Return a Formex which is a the circumference of a rectangle.
p1 and p2 are two opposite corner points of the rectangle. The edges of the rectangle are in planes parallel to the z-axis. There will always be two opposite edges that are parallel with the x-axis. The other two will only be parallel with the y-axis if both points have the same z-value, but in any case they will be parallel with the y-z plane.
The edges parallel with the x-axis are divide in nx parts, the other ones in ny parts.
Return a Formex representing a rectangluar surface.
The rectangle has a size(b,h) divided into (nx,ny) cells.
The default b/h values are equal to nx/ny, resulting in a modular grid. The rectangle lies in the (x,y) plane, with one corner at [0,0,0]. By default, the elements are quads. By setting diag=’u’,’d’ of ‘x’, diagonals are added in /, resp. and both directions, to form triangles.
A polygonal approximation to a circle or arc.
All points generated by this function lie on a circle with unit radius at the origin in the x-y-plane.
All angles are given in degrees and are measured in the direction from x- to y-axis. The first point of the first segment is always on the x-axis.
The default values produce a full circle (approximately). If $a3 < 360$, the result is an arc. Large values of a1 and a2 result in polygones. Thus circle(120.) is an equilateral triangle and circle(60.) is regular hexagon.
Remark that the default a2 == a1 produces a continuous line, while a2 > a1 results in a dashed line.
Three optional arguments can be added to scale and position the circle in 3D space:
A regular polygon with n sides.
Creates the circumference of a regular polygon with $n$ sides, inscribed in a circle with radius 1 and center at the origin. The first point lies on the axis 0. All points are in the (0,1) plane. The return value is a plex-2 Formex. This function is equivalent to circle(360./n).
An equilateral triangle with base [0,1] on axis 0.
Returns an equilateral triangle with side length 1. The first point is the origin, the second points is on the axis 0. The return value is a plex-3 Formex.
Create a collection of curves.
x is a (3,3) shaped array of coordinates, specifying 3 points.
Return an array with 2*n+1 points lying on the quadratic curve through the points x. Each of the intervals [x0,x1] and [x1,x2] will be divided in n segments.
Return a sphere consisting of line elements.
A sphere with radius r is modeled by a regular grid of nx longitude circles, ny latitude circles and their diagonals.
The 3 sets of lines can be distinguished by their property number: 1: diagonals, 2: meridionals, 3: horizontals.
The sphere caps can be cut off by specifying top and bottom latitude angles (measured in degrees from 0 at north pole to 180 at south pole.
Return a sphere consisting of surface triangles
A sphere with radius r is modeled by the triangles fromed by a regular grid of nx longitude circles, ny latitude circles and their diagonals.
The two sets of triangles can be distinguished by their property number: 1: horizontal at the bottom, 2: horizontal at the top.
The sphere caps can be cut off by specifying top and bottom latitude angles (measured in degrees from 0 at north pole to 180 at south pole.
Connect two curves to form a surface.
curve1, curve2 are plex-2 Formices with the same number of elements. The two curves are connected by a surface of quadrilaterals, with n elements in the direction between the curves.
Constructs a Formex which is a sector of a circle/cone.
A sector with radius r and angle t is modeled by dividing the radius in nr parts and the angle in nt parts and then creating straight line segments. If a nonzero value of h is given, a conical surface results with its top at the origin and the base circle of the cone at z=h. The default is for all points to be in the (x,y) plane.
By default, a plex-4 Formex results. The central quads will collapse into triangles. If diag=’up’ or diag = ‘down’, all quads are divided by an up directed diagonal and a plex-3 Formex results.
Create a cylindrical, conical or truncated conical surface.
Returns a Formex representing (an approximation of) a cylindrical or (possibly truncated) conical surface with its axis along the z-axis. The resulting surface is actually a prism or pyramid, and only becomes a good approximation of a cylinder or cone for high values of nt.
Parameters:
Create a rectangular prism
Creates a rectangular prism with faces parallel to the global axes through the points xmin and xmax.
Returns a single element Formex with eltype ‘hex8’.
Part of this code was borrowed from the TrollTech Qt examples.
Classes defined in module imageViewer
Functions defined in module imageViewer
While most of these functions look (and work) like set operations, their result differs from using Python builtin Sets in that they preserve the order of the items in the lists.
Classes defined in module olist
Functions defined in module olist
Roll the elements of a list n positions forward (backward if n < 0)
Return a list with all items in a or in b, in the order of a,b.
Return a list with all items in a but not in b, in the order of a.
Return a list with all items in a or b but not in both.
Return a list with all items in a and in b, in the order of a.
Concatenate a list of lists
Flatten a nested list.
By default, lists are flattened one level deep. If recurse=True, flattening recurses through all sublists.
>>> flatten([[[3.,2,],6.5,],[5],6,'hi'])
[[3.0, 2], 6.5, 5, 6, 'hi']
>>> flatten([[[3.,2,],6.5,],[5],6,'hi'],True)
[3.0, 2, 6.5, 5, 6, 'hi']
Return a subset of items from a list.
Returns a list with the items of a for which the index is in b.
Collect items of a list in separate bins according to the item length.
items is a list of items of any type having the len() method. The items are put in separate lists according to their length.
The return value is a dict where the keys are item lengths and the values are lists of items with this length.
If return_indices is True, a second dict is returned, with the same keys, holding the original indices of the items in the lists.
Classes defined in module isopar
A class representing an isoparametric transformation
type is one of the keys in Isopar.isodata coords and oldcoords can be either arrays, Coords or Formex instances, but should be of equal shape, and match the number of atoms in the specified transformation type
The following three formulations are equivalent
trf = Isopar(eltype,coords,oldcoords)
G = F.isopar(trf)
trf = Isopar(eltype,coords,oldcoords)
G = trf.transform(F)
G = isopar(F,eltype,coords,oldcoords)
Apply isoparametric transform to a set of coordinates.
Returns a Coords array with same shape as X
Functions defined in module isopar
Build a matrix of functions of coords.
Returns a matrix with nvalues rows and natoms colums.
This is a support module for other pyFormex plugins.
Classes defined in module objects
A selection of objects from the pyFormex Globals().
The class provides facilities to filter the global objects by their type and select one or more objects by their name(s). The values of these objects can be changed and the changes can be undone.
Return the type of objects in this selection.
Set the selection to a list of names.
namelist can be a single object name or a list of names. This will also store the current values of the variables.
Add a name,value to a selection.
If no value is given, its current value is used. If a value is given, it is exported.
Clear the selection.
Return a list with all selectable objects.
This lists all the global names in pyformex.PF that match the class and/or filter (if specified).
Remember the current values of the variables in selection.
If copy==True, the values are copied, so that the variables’ current values can be changed inplace without affecting the remembered values.
Replace the current values of selection by new ones.
The old values are stored locally, to enable undo operations.
This is only needed to change the values of objects that can not be changed inplace!
Undo the last changes of the values.
Check that we have a current selection.
Returns the list of Objects corresponding to the current selection. If single==True, the selection should hold exactly one Object name and a single Object instance is returned. If there is no selection, or more than one in case of single==True, an error message is displayed and None is returned
Return the currently selected items as a dictionary.
Returns an ODict with the currently selected objects in the order of the selection.names.
Show the names of known objects and let the user select one or more.
mode can be set to’single’ to select a single item. Return a list with the selected names, possibly empty (if nothing was selected by the user), or None if there is nothing to choose from. This also sets the current selection to the selected names, unless the return value is None, in which case the selection remains unchanged.
Select a single object from the list.
Returns the object, not its name!
Remove the selection from the globals.
Remove everything except the selection from the globals.
Print the selection.
Print the bbox of the current selection.
Write objects to a geometry file.
Read objects from a geometry file.
A selection of drawable objects from the globals().
This is a subclass of Objects. The constructor has the same arguments as the Objects class, plus the following:
annotations: a set of functions that draw annotations of the objects. Each function should take an object name as argument, and draw the requested annotation for the named object. If the object does not have the annotation, it should be silently ignored. Default annotation functions available are:
No annotation functions are activated by default.
Interactively sets the current selection.
Draws old and new version of a Formex with different colors.
old and new can be a either Formex instances or names or lists thereof. old are drawn in yellow, new in the current color.
Undo the last changes of the values.
Toggle the display of an annotation On or Off.
If given, onoff is True or False. If no onoff is given, this works as a toggle.
Draw some annotation for the current selection.
Remove the annotation f.
Return the status of annotation f
Set the property of the current selection.
prop should be a single integer value or None. If None is given, a value will be asked from the user. If a negative value is given, the property is removed. If a selected object does not have a setProp method, it is ignored.
Delete the property of the current selection.
This well reset the prop attribute of all selected objects to None.
Return the type of objects in this selection.
Set the selection to a list of names.
namelist can be a single object name or a list of names. This will also store the current values of the variables.
Add a name,value to a selection.
If no value is given, its current value is used. If a value is given, it is exported.
Clear the selection.
Return a list with all selectable objects.
This lists all the global names in pyformex.PF that match the class and/or filter (if specified).
Remember the current values of the variables in selection.
If copy==True, the values are copied, so that the variables’ current values can be changed inplace without affecting the remembered values.
Replace the current values of selection by new ones.
The old values are stored locally, to enable undo operations.
This is only needed to change the values of objects that can not be changed inplace!
Check that we have a current selection.
Returns the list of Objects corresponding to the current selection. If single==True, the selection should hold exactly one Object name and a single Object instance is returned. If there is no selection, or more than one in case of single==True, an error message is displayed and None is returned
Return the currently selected items as a dictionary.
Returns an ODict with the currently selected objects in the order of the selection.names.
Select a single object from the list.
Returns the object, not its name!
Remove the selection from the globals.
Remove everything except the selection from the globals.
Print the selection.
Print the bbox of the current selection.
Write objects to a geometry file.
Read objects from a geometry file.
Functions defined in module objects
Draw the name of an object at its center.
Draw the numbers of an object’s elements.
Draw the nodes of an object.
Draw the numbers of an object’s nodes.
Draw the feature edges of an object.
Draw the bbox of an object.
Classes defined in module canvas
A collection of settings for an OpenGL Canvas.
The canvas settings are a collection of settings and default values affecting the rendering in an individual viewport. There are two type of settings:
Currently the following mode settings are defined:
The list of default settings includes:
Any of these values can be set in the constructor using a keyword argument. All items that are not set, will get their value from the configuration file(s).
Reset the CanvasSettings to its defaults.
The default values are taken from the configuration files. An optional dictionary may be specified to override (some of) these defaults.
Update current values with the specified settings
Returns the sanitized update values.
Transform a dict to acceptable settings.
Activate the mode canvas settings in the GL machine.
Activate the default canvas settings in the GL machine.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
A canvas for OpenGL rendering.
The Canvas is a class holding all global data of an OpenGL scene rendering. This includes colors, line types, rendering mode. It also keeps lists of all the actors and decorations in the scene. It always has a Camera object holding import viewing parameters. And finally it stores the lighting information.
It does not however contain the viewport size and position.
Toggle lights on/off.
Return the status of the lighting.
Return all the settings to their default values.
Set the global ambient lighting for the canvas
Set the default material light properties for the canvas
Change the light parameters
Set the rendering mode.
This sets or changes the rendermode and lighting attributes. If lighting is not specified, it is set depending on the rendermode.
If the canvas has not been initialized, this merely sets the attributes self.rendermode and self.lighting. If the canvas was already initialized (it has a camera), and one of the specified settings is fdifferent from the existing, the new mode is set, the canvas is re-initialized according to the newly set mode, and everything is redrawn with the new mode.
Set the linewidth for line rendering.
Set the linestipple for line rendering.
Set the size for point drawing.
Set the background color.
If one color is specified, a solid background is set. If two colors are specified, a graded background is set and an object is created to display the background.
Create the background object.
Set the default foreground color.
Set the highlight color.
Toggle the display of the global axes on or off.
If on is True, a triade of global axes is displayed, if False it is removed. The default (None) toggles between on and off.
Initialize the rendering machine.
The rendering machine is initialized according to: - self.rendermode: one of - self.lighting
Flush all OpenGL commands, making sure the display is updated.
Clear the canvas to the background color.
Activate the canvas settings in the GL machine.
(Re)display all the actors in the scene.
This should e.g. be used when actors are added to the scene, or after changing camera position/orientation or lens.
Set up the canvas for 2D drawing on top of 3D canvas.
The 2D drawing operation should be ended by calling end_2D_drawing. It is assumed that you will not try to change/refresh the normal 3D drawing cycle during this operation.
Cancel the 2D drawing mode initiated by begin_2D_drawing.
Set the bounding box of the scene you want to be visible.
Add a 3D actor to the 3D scene.
Remove a 3D actor from the 3D scene.
Add a 3D actor highlight to the 3D scene.
Remove a 3D actor highlight from the 3D scene.
Add an annotation to the 3D scene.
Remove an annotation from the 3D scene.
Add a 2D decoration to the canvas.
Remove a 2D decoration from the canvas.
Remove a list of any actor/highlights/annotation/decoration items.
This will remove the items from any of the canvas lists in which the item appears. itemlist can also be a single item instead of a list.
Remove all actors in actorlist (default = all) from the scene.
Remove all highlights in actorlist (default = all) from the scene.
Remove all annotations in actorlist (default = all) from the scene.
Remove all decorations in actorlist (default = all) from the scene.
Remove all actors and decorations
Redraw all actors in the scene.
Sets the camera looking under angles at bbox.
This function sets the camera angles and adjusts the zooming. The camera distance remains unchanged.
If a bbox is specified, the camera will be zoomed to make the whole bbox visible. If no bbox is specified, the current scene bbox will be used. If no current bbox has been set, it will be calculated as the bbox of the whole scene.
If no camera angles are given, the camera orientation is kept. angles can be a set of 3 angles, or a string
Map the object coordinates (x,y,z) to window coordinates.
Map the window coordinates (x,y,z) to object coordinates.
Dolly zooming.
Zooms in with a factor f by moving the camera closer to the scene. This does noet change the camera’s FOV setting. It will change the perspective view though.
Rectangle zooming.
Zooms in/out by changing the area and position of the visible part of the lens. Unlike zoom(), this does not change the perspective view.
x0,y0,x1,y1 are pixel coordinates of the lower left and upper right corners of the area of the lens that will be mapped on the canvas viewport. Specifying values that lead to smaller width/height will zoom in.
Rectangle zooming with specified center.
This is like zoomRectangle, but the zoom rectangle is specified by its center and size, which may be more appropriate when using off-center zooming.
Rectangle zoom to make full scene visible.
Save the current OpenGL buffer
Show the saved buffer
Draw the focus rectangle.
The specified width is HALF of the line width
draw the cursor
Functions defined in module canvas
Return a list of the 2nd numbers in the openGL pick buffer.
Set the line stipple pattern.
When drawing lines, OpenGl can use a stipple pattern. The stipple is defined by two values: a pattern (on/off) of maximum 16 bits, used on the pixel level, and a multiplier factor for each bit.
If factor <= 0, the stippling is disabled.
Enable smooth shading
Disable smooth shading
Convert On/Off strings to a boolean
Enable/Disable an OpenGL facility, depending on onoff value
facility is an OpenGL facility. onoff can be True or False to enable, resp. disable the facility, or None to leave it unchanged.
Classes defined in module colorscale
Mapping floating point values into colors.
A colorscale maps floating point values within a certain range into colors and can be used to provide visual representation of numerical values. This is e.g. quite useful in Finite Element postprocessing (see the postproc plugin).
The ColorLegend class provides a way to make the ColorScale visible on the canvas.
Scale a value to the range -1...1.
If the ColorScale has only one exponent, values in the range mival..maxval are scaled to the range -1..+1.
If two exponents were specified, scaling is done independently in the intervals minval..midval and midval..maxval, mapped resp. using exp2 and exp onto the intevals -1..0 and 0..1.
Return the color representing a value val.
The returned color is a tuple of three RGB values in the range 0-1. The color is obtained by first scaling the value to the -1..1 range using the ‘scale’ method, and then using that result to pick a color value from the palet. A palet specifies the three colors corresponding to the -1, 0 and 1 values.
A colorlegend divides a in a number of subranges.
Parameters:
For a ColorScale without midval, the full range is divided in n subranges; for a scale with midval, each of the two ranges is divided in n/2 subranges. In each case the legend has n subranges limited by n+1 values. The n colors of the legend correspond to the middle value of each subrange.
Raise a runtime error if oflow == None, else return oflow.
Return the color representing a value val.
The color is that of the subrange holding the value. If the value matches a subrange limit, the lower range color is returned. If the value falls outside the colorscale range, a runtime error is raised, unless the corresponding underflowcolor or overflowcolor attribute has been set, in which case this attirbute is returned. Though these attributes can be set to any not None value, it will usually be set to some color value, that will be used to show overflow values. The returned color is a tuple of three RGB values in the range 0-1.
Functions defined in module colorscale
Functions for managing a project in pyFormex.
Classes defined in module project
Project: a persistent storage of pyFormex data.
A pyFormex Project is a regular Python dict that can contain named data of any kind, and can be saved to a file to create persistence over different pyFormex sessions.
The Project class is used by pyFormex for the pyformex.PF global variable that collects variables exported from pyFormex scripts. While projects are mostly handled through the pyFormex GUI, notably the File menu, the user may also create and handle his own Project objects from a script.
Because of the way pyFormex Projects are written to file, there may be problems when trying to read a project file that was created with another pyFormex version. Problems may occur if the project contains data of a class whose implementation has changed, or whose definition has been relocated. Our policy is to provide backwards compatibility: newer versions of pyFormex will normally read the older project formats. Saving is always done in the newest format, and these can generally not be read back by older program versions (unless you are prepared to do some hacking).
Warning
Compatibility issues.
Occasionally you may run into problems when reading back an old project file, especially when it was created by an unreleased (development) version of pyFormex. Because pyFormex is evolving fast, we can not test the full compatibility with every revision You can file a support request on the pyFormex support tracker. and we will try to add the required conversion code to pyFormex.
The project files are mainly intended as a means to easily save lots of data of any kind and to restore them in the same session or a later session, to pass them to another user (with the same or later pyFormex version), to store them over a medium time period. Occasionally opening and saving back your project files with newer pyFormex versions may help to avoid read-back problems over longer time.
For a problemless long time storage of Geometry type objects you may consider to write them to a pyFormex Geometry file (.pgf) instead, since this uses a stable ascii based format. It can (currently) not deal with other data types however.
Parameters:
filename: the name of the file where the Project data will be saved. If the file exists (and access is not w), it should be a previously saved Project and an attempt will be made to load the data from this file into the Project. If this fails, an error is raised.
If the file exists and access is w, it will be overwritten, destroying any previous contents.
If no filename is specified, a temporary file will be created when the Project is saved for the first time. The file with not be automatically deleted. The generated name can be retrieved from the filename attribute.
access: One of ‘wr’ (default), ‘rw’, ‘w’ or ‘r’. If the string contains an ‘r’ the data from an existing file will be read into the dict. If the string starts with an ‘r’, the file should exist. If the string contains a ‘w’, the data can be written back to the file. The ‘r’ access mode is a read-only mode.
access |
File must exist |
File is read |
File can be written |
---|---|---|---|
r |
yes |
yes |
no |
rw |
yes |
yes |
yes |
wr |
no |
if it exists |
yes |
w |
no |
no |
yes |
convert: if True (default), and the file is opened for reading, an attempt is made to open old projects in a compatibility mode, doing the necessary conversions to new data formats. If convert is set False, only the latest format can be read and older formats will generate an error.
signature: A text that will be written in the header record of the file. This can e.g. be used to record format version info.
compression: An integer from 0 to 9: compression level. For large data sets, compression leads to much smaller files. 0 is no compression, 9 is maximal compression. The default is 4.
binary: if False and no compression is used, storage is done in an ASCII format, allowing to edit the file. Otherwise, storage uses a binary format. Using binary=False is deprecated.
data: a dict-like object to initialize the Project contents. These data may override values read from the file.
Construct the data to be saved in the header.
Save the project to file.
Read the header from a project file.
Tries to read the header from different legacy formats, and if succesfull, adjusts the project attributes according to the values in the header. Returns the open file if succesfull.
Load a project from file.
The loaded definitions will update the current project.
Convert an old format project file.
The project file is read, and if successfull, is immediately saved. By default, this will overwrite the original file. If a filename is specified, the converted data are saved to that file. In both cases, access is set to ‘wr’, so the tha saved data can be read back immediately.
Uncompress a compressed project file.
The project file is read, and if successfull, is written back in uncompressed format. This allows to make conversions of the data inside.
Unrecoverably delete the project file.
Functions defined in module project
Override the import path of some classes
Load data from pickle file f.
A triangulated surface is a surface consisting solely of triangles. Any surface in space, no matter how complex, can be approximated with a triangulated surface.
Classes defined in module trisurface
A class representing a triangulated 3D surface.
The surface contains ntri triangles, each having 3 vertices with 3 coordinates. The surface can be initialized from one of the following:
Additionally, a keyword argument prop= may be specified to set property values.
area of elements
For surface element the faces’ area is returned. For volume elements the sum of the faces’areas is returned.
Return the number of edges of the TriSurface.
Return the number of faces of the TriSurface.
Return the coordinates of the nodes of the TriSurface.
Return the number of points, edges, faces of the TriSurface.
Get the faces’ edge numbers.
Change the coords.
Change the elems.
Change the edges and faces.
Merge another surface with self.
This just merges the data sets, and does not check whether the surfaces intersect or are connected! This is intended mostly for use inside higher level functions.
Read a surface from file.
If no file type is specified, it is derived from the filename extension. Currently supported file types:
Write the surface to file.
If no filetype is given, it is deduced from the filename extension. If the filename has no extension, the ‘gts’ file type is used.
Compute the average normals at the vertices.
Compute the area and normal vectors of the surface triangles.
The normal vectors are normalized. The area is always positive.
The values are returned and saved in the object.
Return the area of the surface triangles.
Return the area of the surface
Return the enclosed volume of the surface.
This will only be correct if the surface is a closed manifold.
Return the curvature parameters at the nodes.
This uses the nodes that are connected to the node via a shortest path of ‘neighbours’ edges. Eight values are returned: the Gaussian and mean curvature, the shape index, the curvedness, the principal curvatures and the principal directions.
Return inertia related quantities of the surface.
This returns the center of gravity, the principal axes of inertia, the principal moments of inertia and the inertia tensor.
Check whether the TriSurface is a manifold and if it’s closed.
Detect the border elements of TriSurface.
The border elements are the edges having less than 2 connected elements. Returns True where edge is on the border.
Returns the numbers of the border edges.
Detect the border nodes of TriSurface.
The border nodes are the vertices belonging to the border edges. Returns a list of vertex numbers.
Check whether the TriSurface is a manifold.
A surface is a manifold if a small sphere exists that cuts the surface to a surface that can continously be deformed to an open disk.
Finds edges and faces that are not Manifold.
Returns a tuple of:
Check whether the TriSurface is a closed manifold.
Return the border of TriSurface as a set of segments.
Return the border(s) of TriSurface.
The complete border of the surface is returned as a list of plex-2 Meshes. Each Mesh constitutes a continuous part of the border.
Fill the border areas of a surface to make it closed.
Returns a list of surfaces, each of which fills a singly connected part of the border of the input surface. Adding these surfaces to the original will create a closed surface. The surfaces will have property values set above those used in the parent surface. If the surface is already closed, an empty list is returned.
There are two methods, ‘radial’ and ‘border’ corresponding with the methods of the surfaceInsideBorder.
Return the cos of the angles over all edges.
The surface should be a manifold (max. 2 elements per edge). Edges adjacent to only one element get cosangles = 1.0.
Return the angles over all edges (in degrees). It is the angle (0 to 180) between 2 face normals.
Return the apect ratio of the triangles of the surface.
The aspect ratio of a triangle is the ratio of the longest edge over the smallest altitude of the triangle.
Equilateral triangles have the smallest edge ratio (2 over square root 3).
Return the smallest altitude of the triangles of the surface.
Return the longest edge of the triangles of the surface.
Return the shortest edge of the triangles of the surface.
Return a text with full statistics.
Find the distances of points X to the TriSurface.
The distance of a point is either: - the closest perpendicular distance to the facets; - the closest perpendicular distance to the edges; - the closest distance to the vertices.
X is a (nX,3) shaped array of points. If return_points = True, a second value is returned: an array with the closest (foot)points matching X.
Offset a surface with a certain distance.
All the nodes of the surface are translated over a specified distance along their normal vector.
Generator function returning the frontal elements.
startat is an element number or list of numbers of the starting front. On first call, this function returns the starting front. Each next() call returns the next front. front_increment determines how the property increases at each frontal step. There is an extra increment +1 at each start of a new part. Thus, the start of a new part can always be detected by a front not having the property of the previous plus front_increment.
Grow a selection using a frontal method.
Starting from element startat, grow a selection nsteps times following the common edges of the triangles.
The property of each new front is augmented by front_increment.
Grow a selection of a surface.
p is a single element number or a list of numbers. The return value is a list of element numbers obtained by growing the front nsteps times. The mode argument specifies how a single frontal step is done:
Detect different parts of the surface using a frontal method.
okedges flags the edges where the two adjacent triangles are to be in the same part of the surface. startat is a list of elements that are in the first part. The partitioning is returned as a property type array having a value corresponding to the part number. The lowest property number will be firstprop.
Partition the surface by splitting it at sharp edges.
The surface is partitioned in parts in which all elements can be reach without ever crossing a sharp edge angle. More precisely, any two elements that can be connected by a line not crossing an edge between two elements having their normals differ more than angle (in degrees), will belong to the same part.
The partitioning is returned as a property type array having a value corresponding to the part number. The lowest property number will be firstprop.
By default the parts are assigned property numbers in decreasing order of the number of triangles in the part. Setting the sort argument to ‘area’ will sort the parts according to decreasing area. Any other value will return the parts unsorted.
Cut a surface with a plane or a set of planes.
Cuts the surface with one or more plane and returns either one side or both.
Parameters:
The parameters are the same as in Formex.CutWithPlane(). The returned surface will have its normals fixed wherever possible.
Return the elements from list connected with target
Return the intersection lines with plane (p,n).
Returns a plex-2 mesh with the line segments obtained by cutting all triangles of the surface with 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 plex-2 Mesh where the line segments defining the intersection are sorted to form continuous lines. The Mesh has property numbers such that all segments forming a single continuous part have the same property value. The splitProp() method can be used to get a list of Meshes.
Intersect a surface with a sequence of planes.
A sequence of nplanes planes with normal dir is constructed at equal distances spread over the bbox of the surface.
The return value is a list of intersectionWithPlane() return values, i.e. a list of Meshes, one for every cutting plane. In each Mesh the simply connected parts are identified by property number.
Smooth the surface.
Returns a TriSurface which is a smoothed version of the original. Three smoothing methods are available: ‘lowpass’, ‘laplace’, and ‘gts’. The first two are built-in, the latter uses the external command gtssmooth.
Parameters:
Extra parameters for ‘lowpass’ and ‘laplace’:
Extra parameters for ‘laplace’:
Extra parameters for ‘gts’:
Returns: the smoothed TriSurface
Apply a low pass smoothing to the surface.
Apply Laplace smoothing with shrinkage compensation to the surface.
Fix the orientation of the normals.
Some surface operations may result in improperly oriented normals. This tries to reverse improperly oriented normals so that a single oriented surface is achieved. It only works on a closed surface.
In the current version, this uses the external program admesh, so this should be installed on the machine.
If the surface was a (possibly non-orientable) manifold, the result will be an orientable manifold. This is a necessary condition for the gts methods to be applicable.
Check the surface using gtscheck.
Uses gtscheck to check whether the surface is an orientable, non self-intersecting manifold.
This is a necessary condition the gts methods: split, coarsen, refine, boolean. (Additionally, the surface should be closed, wich can be checked with isClosedManifold()).
Returns a tuple of:
check self intersections using tetgen
Returns couples of intersecting triangles
Split the surface using gtssplit.
Splits the surface into connected and manifold components. This uses the external program gtssplit. The surface should be a closed orientable non-intersecting manifold. Use the check() method to find out.
This method creates a series of files with given base name, each file contains a single connected manifold.
Coarsen the surface using gtscoarsen.
Construct a coarsened version of the surface. This uses the external program gtscoarsen. The surface should be a closed orientable non-intersecting manifold. Use the check() method to find out.
Parameters:
Refine the surface using gtsrefine.
Construct a refined version of the surface. This uses the external program gtsrefine. The surface should be a closed orientable non-intersecting manifold. Use the check() method to find out.
Parameters:
Perform a boolean operation with another surface.
Boolean operations between surfaces are a basic operation in free surface modeling. Both surfaces should be closed orientable non-intersecting manifolds. Use the check() method to find out.
The boolean operations are set operations on the enclosed volumes: union(‘+’), difference(‘-‘) or intersection(‘*’).
Parameters:
Create a report on the Mesh shape and size.
The report contains the number of nodes, number of elements, plexitude, element type, bbox and size.
Generator function returning the frontal elements.
startat is an element number or list of numbers of the starting front. On first call, this function returns the starting front. Each next() call returns the next front.
Detects different parts of the Mesh using a frontal method.
okedges flags the edges where the two adjacent elems are to be in the same part of the Mesh. startat is a list of elements that are in the first part. The partitioning is returned as a property type array having a value corresponding to the part number. The lowest property number will be firstprop.
Detect the connected parts of a Mesh.
The Mesh is partitioned in parts in which all elements are connected. Two elements are connected if it is possible to draw a continuous (poly)line from a point in one element to a point in the other element without leaving the Mesh. The partitioning is returned as a property type array having a value corresponding to the part number. The lowest property number will be firstprop.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Split the Mesh into connected parts.
Returns a list of Meshes that each form a connected part.
Set the eltype from a character string.
This function allows the user to change the element type of the Mesh. The input is a character string with the name of one of the element defined in elements.py. The function will only allow to set a type matching the plexitude of the Mesh.
This method is seldom needed, because the applications should normally set the element type at creation time.
Return the largest connected part of the Mesh.
Create or destroy the property array for the Mesh.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Mesh. You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Mesh.
It finds the rings of elems connected to sources by node.
Sources is a list of elem indices. A list of rings is returned, from zero (equal to sources) to step. If step is -1, all rings are returned.
Modify the connectivity of negative-volume elements to make positive-volume elements.
Negative-volume elements (hex or tet with inconsistent face orientation) may appear by error during geometrical trnasformations (e.g. reflect, sweep, extrude, revolve). This function fixes those elements. Currently it only works with linear tet and hex.
Returns a quality measure for volume meshes.
If scaled if False, it returns the Jacobian at the corners of each element. If scaled is True, it returns a quality metrics, being the minumum value of the scaled Jacobian in each element (at one corner, the Jacobian divided by the volume of a perfect brick). Each tet or hex element gives a value between -1 and 1. Acceptable elements have a positive scaled Jacobian. However, good quality requires a minimum of 0.2. Quadratic meshes are first converted to linear. If the mesh contain mainly negative Jacobians, it probably has negative volumes and can be fixed with the correctNegativeVolumes.
Return the properties as a numpy array (ndarray)
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Return the highest property value used, or None
Return a list with unique property values.
Return a copy using the same data arrays
Convert a Mesh to a Formex.
The Formex inherits the element property numbers and eltype from the Mesh. Node property numbers however can not be translated to the Formex data model.
Convert a Mesh to a Surface.
If the plexitude of the mesh is 3, returns a TriSurface equivalent with the Mesh. Else, an error is raised.
Return the centroids of all elements of the Mesh.
The centroid of an element is the point whose coordinates are the mean values of all points of the element. The return value is a Coords object with nelems points.
Get the coords data.
Returns the full array of coordinates stored in the Mesh object. Note that this may contain points that are not used in the mesh. compact() will remove the unused points.
Get the elems data.
Returns the element connectivity data as stored in the object.
Get the entities of a lower dimensionality.
If the element type is defined in the elements module, this returns a Connectivity table with the entities of a lower dimensionality. The full list of entities with increasing dimensionality 0,1,2,3 is:
['points', 'edges', 'faces', 'cells' ]
If level is negative, the dimensionality returned is relative to that of the caller. If it is positive, it is taken absolute. Thus, for a Mesh with a 3D element type, getLowerEntities(-1) returns the faces, while for a 2D element type, it returns the edges. For both meshes however, getLowerEntities(+1) returns the edges.
By default, all entities for all elements are returned and common entities will appear multiple times. Specifying unique=True will return only the unique ones.
The return value may be an empty table, if the element type does not have the requested entities (e.g. the ‘point’ type). If the eltype is not defined, or the requested entity level is outside the range 0..3, the return value is None.
Return the set of unique node numbers in the Mesh.
This returns only the node numbers that are effectively used in the connectivity table. For a compacted Mesh, it is equal to `arange(self.nelems)`. This function also stores the result internally so that future requests can return it without the need for computing it again.
Return the nodal coordinates of the Mesh.
This returns only those points that are effectively used in the connectivity table. For a compacted Mesh, it is equal to the coords attribute.
Return the unique edges of all the elements in the Mesh.
This is a convenient function to create a table with the element edges. It is equivalent to `self.getLowerEntities(1,unique=True)`, but this also stores the result internally so that future requests can return it without the need for computing it again.
Return the unique faces of all the elements in the Mesh.
This is a convenient function to create a table with the element faces. It is equivalent to `self.getLowerEntities(2,unique=True)`, but this also stores the result internally so that future requests can return it without the need for computing it again.
Return the cells of the elements.
This is a convenient function to create a table with the element cells. It is equivalent to `self.getLowerEntities(3,unique=True)`, but this also stores the result internally so that future requests can return it without the need for computing it again.
Return the border of the Mesh.
Returns a Connectivity table with the free entities of the specified level of the Mesh. Free entities are entities that are only connected with a single element.
If return_indices==True, also returns an (nentities,2) index for inverse lookup of the higher entity (column 0) and its local lower entity number (column 1).
Return a Mesh with lower entities.
Returns a Mesh representing the lower entities of the specified level. If the Mesh has property numbers, the lower entities inherit the property of the element to which they belong.
By default, the resulting Mesh is compacted. Compaction can be switched off by setting compact=False.
Return the border of the Mesh.
This returns a Connectivity table with the border of the Mesh. The border entities are of a lower hierarchical level than the mesh itself. These entities become part of the border if they are connected to only one element.
If return_indices==True, it returns also an (nborder,2) index for inverse lookup of the higher entity (column 0) and its local border part number (column 1).
This is a convenient shorthand for
self.getFreeEntities(level=-1,return_indices=return_indices)
Return a Mesh with the border elements.
The returned Mesh is of the next lower hierarchical level and contains all the free entitites of that level. If the Mesh has property numbers, the border elements inherit the property of the element to which they belong.
By default, the resulting Mesh is compacted. Compaction can be switched off by setting compact=False.
This is a convenient shorthand for
self.getFreeEntitiesMesh(level=-1,compact=compact)
Return a Mesh with the free edge elements.
The returned Mesh is of the hierarchical level 1 (no mather what the level of the parent Mesh is) and contains all the free entitites of that level. If the Mesh has property numbers, the border elements inherit the property of the element to which they belong.
By default, the resulting Mesh is compacted. Compaction can be switched off by setting compact=False.
This is a convenient shorthand for
self.getFreeEntitiesMesh(level=1,compact=compact)
Return a Mesh where all elements have been reversed.
Reversing an element has the following meaning:
The reflect() method by default calls this method to undo the element reversal caused by the reflection operation.
Reflect the coordinates in one of the coordinate directions.
Parameters:
Find and store the elems connected to nodes.
Find the number of elems connected to nodes.
Find and store the elems connected to edges.
Find the number of elems connected to edges.
Find the elems adjacent to each elem via one or more nodes.
Find the number of elems which are adjacent by node to each elem.
Find the elems adjacent to elems via an edge.
Find the number of adjacent elems.
Fuse the nodes of a Meshes.
All nodes that are within the tolerance limits of each other are merged into a single node.
The merging operation can be tuned by specifying extra arguments that will be passed to Coords:fuse().
Match nodes of Mesh with nodes of self.
This is a convenience function equivalent to:
self.coords.match(mesh.coords,**kargs)
See also Coords.match()
Match elems of Mesh with elems of self.
self and Mesh are same eltype meshes and are both without duplicates.
Elems are matched by their centroids.
Match faces of mesh with faces of self.
self and Mesh can be same eltype meshes or different eltype but of the same hierarchical type (i.e. hex8-quad4 or tet4 - tri3) and are both without duplicates.
Returns the indices array of the elems of self that matches the faces of mesh
Remove unconnected nodes and renumber the mesh.
Returns a mesh where all nodes that are not used in any element have been removed, and the nodes are renumbered to a compacter scheme.
Return a Mesh only holding the selected elements.
Returns a Mesh (or subclass) with only the selected elements.
See cselect for the complementary operation.
Return a mesh without the selected elements.
Returns a Mesh with all but the selected elements.
This is the complimentary operation of select.
Create average nodes from the existing nodes of a mesh.
nodsel is a local node selector as in selectNodes() Returns the (weighted) average coordinates of the points in the selector as (nelems*nnod,3) array of coordinates, where nnod is the length of the node selector. wts is a 1-D array of weights to be attributed to the points. Its length should be equal to that of nodsel.
Create nodes from the existing nodes of a mesh.
nodsel is a local node selector as in selectNodes() Returns the mean coordinates of the points in the selector as (nelems*nnod,3) array of coordinates, where nnod is the length of the node selector.
Add new nodes to elements.
newcoords is an (nelems,nnod,3) or`(nelems*nnod,3)` array of coordinates. Each element gets exactly nnod extra nodes from this array. The result is a Mesh with plexitude self.nplex() + nnod.
Add new nodes to elements by averaging existing ones.
nodsel is a local node selector as in selectNodes() Returns a Mesh where the mean coordinates of the points in the selector are added to each element, thus increasing the plexitude by the length of the items in the selector. The new element type should be set to correct value.
Return a mesh with subsets of the original nodes.
nodsel is an object that can be converted to a 1-dim or 2-dim array. Examples are a tuple of local node numbers, or a list of such tuples all having the same length. Each row of nodsel holds a list of local node numbers that should be retained in the new connectivity table.
Return a Mesh which holds only the elements with property val.
val is either a single integer, or a list/array of integers. The return value is a Mesh holding all the elements that have the property val, resp. one of the values in val. The returned Mesh inherits the matching properties.
If the Mesh has no properties, a copy with all elements is returned.
Return a Mesh without the elements with property val.
This is the complementary method of Mesh.withProp(). val is either a single integer, or a list/array of integers. The return value is a Mesh holding all the elements that do not have the property val, resp. one of the values in val. The returned Mesh inherits the matching properties.
If the Mesh has no properties, a copy with all elements is returned.
Partition a Mesh according to its propery values.
Returns a dict with the property values as keys and the corresponding partitions as values. Each value is a Mesh instance. It the Mesh has no props, an empty dict is returned.
Split a mesh in n parts, distributing the elements randomly.
Returns a list of n Mesh objects, constituting together the same Mesh as the original. The elements are randomly distributed over the subMeshes.
By default, the Meshes are compacted. Compaction may be switched off for efficiency reasons.
Convert a Mesh to another element type.
Converting a Mesh from one element type to another can only be done if both element types are of the same dimensionality. Thus, 3D elements can only be converted to 3D elements.
The conversion is done by splitting the elements in smaller parts and/or by adding new nodes to the elements.
Not all conversions between elements of the same dimensionality are possible. The possible conversion strategies are implemented in a table. New strategies may be added however.
The return value is a Mesh of the requested element type, representing the same geometry (possibly approximatively) as the original mesh.
If the requested conversion is not implemented, an error is raised.
Convert choosing randomly between choices
Reduce degenerate elements to lower plexitude elements.
This will try to reduce the degenerate elements of the mesh to elements of a lower plexitude. If a target element type is given, only the matching reduce scheme is tried. Else, all the target element types for which a reduce scheme from the Mesh eltype is available, will be tried.
The result is a list of Meshes of which the last one contains the elements that could not be reduced and may be empty. Property numbers propagate to the children.
Split a Mesh in degenerate and non-degenerate elements.
If autofix is True, the degenerate elements will be tested against known degeneration patterns, and the matching elements will be transformed to non-degenerate elements of a lower plexitude.
The return value is a list of Meshes. The first holds the non-degenerate elements of the original Mesh. The last holds the remaining degenerate elements. The intermediate Meshes, if any, hold elements of a lower plexitude than the original. These may still contain degenerate elements.
Remove the degenerate elements from a Mesh.
Returns a Mesh with all degenerate elements removed.
Remove the duplicate elements from a Mesh.
Duplicate elements are elements that consist of the same nodes, by default in no particular order. Setting permutations=False will only consider elements with the same nodes in the same order as duplicates.
Returns a Mesh with all duplicate elements removed.
Renumber the nodes of a Mesh in the specified order.
order is an index with length equal to the number of nodes. The index specifies the node number that should come at this position. Thus, the order values are the old node numbers on the new node number positions.
order can also be a predefined value that will generate the node index automatically:
Renumber the elements of a Mesh.
Parameters:
See also: Connectivity.reorder()
Connect a sequence of toplogically congruent Meshes into a hypermesh.
Parameters:
coordslist: either a list of Coords instances, all having the same shape as self.coords, or a single Mesh instance whose coords attribute has the same shape.
If it is a list of Coords, consider a list of Meshes obtained by combining each Coords object with the connectivity table, element type and property numbers of the current Mesh. The return value then is the hypermesh obtained by connecting each consecutive slice of (degree+1) of these meshes. The hypermesh has a dimensionality that is one higher than the original Mesh (i.e. points become lines, lines become surfaces, surfaces become volumes). The resulting elements will be of the given degree in the direction of the connection. Notice that the coords of the current Mesh are not used, unless these coords are explicitely included into the specified coordslist. In many cases self.coords will be the first item in coordslist, but it could occur anywhere in the list or even not at all. The number of Coords items in the list should be a multiple of degree plus 1.
Specifying a single Mesh instead of a list of Coords is just a convenience for the often occurring situation of connecting a Mesh (self) with another one (mesh) having the same connectivity: in this case the list of Coords will automatically be set to [ self.coords, mesh.coords ]. The degree should be 1 in this case.
degree: degree of the connection. Currently only degree 1 and 2 are supported.
loop: if True, the connections with loop around the list and connect back to the first. This is accomplished by adding the first Coords item back at the end of the list.
div: Either an integer, or a sequence of float numbers (usually in the range ]0.0..1.0]). With this parameter the generated elements can be further subdivided along the connection direction. If an int is given, the connected elements will be divided into this number of elements along the connection direction. If a sequence of float numbers is given, the numbers specify the relative distance along the connection direction where the elements should end. If the last value in the sequence is not equal to 1.0, there will be a gap between the consecutive connections.
eltype: the element type of the constructed hypermesh. Normally, this is set automatically from the base element type and the connection degree. If a different element type is specified, a final conversion to the requested element type is attempted.
Extrude a Mesh in one of the axes directions.
Returns a new Mesh obtained by extruding the given Mesh over n steps of length step in direction of axis dir.
Revolve a Mesh around an axis.
Returns a new Mesh obtained by revolving the given Mesh over an angle around an axis in n steps, while extruding the mesh from one step to the next. This extrudes points into lines, lines into surfaces and surfaces into volumes.
Sweep a mesh along a path, creating an extrusion
Returns a new Mesh obtained by sweeping the given Mesh over a path. The returned Mesh has double plexitude of the original. The operation is similar to the extrude() method, but the path can be any 3D curve.
This function is usually used to extrude points into lines, lines into surfaces and surfaces into volumes. By default it will try to fix the connectivity ordering where appropriate. If autofix is switched off, the connectivities are merely stacked, and the user may have to fix it himself.
Currently, this function produces the correct element type, but the geometry .
Concatenate a list of meshes of the same plexitude and eltype
Merging of the nodes can be tuned by specifying extra arguments that will be passed to Coords:fuse().
This is a class method, and should be invoked as follows:
Mesh.concatenate([mesh0,mesh1,mesh2])
Flag elements having nodal coordinates between min and max.
This function is very convenient in clipping a Mesh 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 Mesh
The test plane can be defined 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 compaitble 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.
nodes specifies which nodes are taken into account in the comparisons. It should be one of the following:
The default (‘all’) will flag all the elements that have all their nodes between the planes x=min and x=max, i.e. the elements that fall completely between these planes. One of the two clipping planes may be left unspecified.
Return a Mesh with all the elements where t>0.
t should be a 1-D integer array with length equal to the number of elements of the Mesh. The resulting Mesh will contain all elements where t > 0.
This is the complement of clip, returning a Mesh where t<=0.
Return the Mesh clipped at plane (p,n).
This is a convenience function returning the part of the Mesh at one side of the plane (p,n)
Return the signed volume of all the mesh elements
For a ‘tet4’ tetraeder Mesh, the volume of the elements is calculated as 1/3 * surface of base * height.
For other Mesh types the volumes are calculated by first splitting the elements into tetraeder elements.
The return value is an array of float values with length equal to the number of elements. If the Mesh conversion to tetraeder does not succeed, the return value is None.
Functions defined in module trisurface
Transform an .stl file to .off or .gts format.
If outname is given, it is either ‘.off’ or ‘.gts’ or a filename ending on one of these extensions. If it is only an extension, the stlname will be used with extension changed.
If the outname file exists and its mtime is more recent than the stlname, the outname file is considered uptodate and the conversion programwill not be run.
The conversion program will be choosen depending on the extension. This uses the external commands ‘admesh’ or ‘stl2gts’.
The return value is a tuple of the output file name, the conversion program exit code (0 if succesful) and the stdout of the conversion program (or a ‘file is already uptodate’ message).
Read a GTS surface mesh.
Return a coords,edges,faces tuple.
Read an OFF surface mesh.
The mesh should consist of only triangles! Returns a nodes,elems tuple.
Read a surface from .stl file.
This is done by first coverting the .stl to .gts or .off format. The name of the intermediate file may be specified. If not, it will be generated by changing the extension of fn to ‘.gts’ or ‘.off’ depending on the setting of the ‘surface/stlread’ config setting.
Return a coords,edges,faces or a coords,elems tuple, depending on the intermediate format.
Read a triangular surface mesh in Gambit neutral format.
The .neu file nodes are numbered from 1! Returns a nodes,elems tuple.
Export an x[n,3,3] float array as an ascii .stl file.
Write a tetgen surface model to .node and .smesh files.
The provided file name is the .node or the .smesh filename.
Return the volume inside a 3-plex Formex.
Returns an (ntri) shaped array with the volume of the tetraeders formed by the triangles and the point pt. If x represents a closed surface, the sum of this array will represent the volume inside the surface.
Calculate curvature parameters at the nodes.
Algorithms based on Dong and Wang 2005; Koenderink and Van Doorn 1992. This uses the nodes that are connected to the node via a shortest path of ‘neighbours’ edges. Eight values are returned: the Gaussian and mean curvature, the shape index, the curvedness, the principal curvatures and the principal directions.
Create a surface inside a given closed border line.
The border line is a closed polygonal line and can be specified as one of the following:
The return value is a TriSurface filling the hole inside the border.
There are currently two fill methods available:
The ‘radial’ method produces nice results if the border is relative smooth, nearly convex and nearly planar. It adds an extra point though, which may be unwanted. On irregular 3D borders there is a high change that the result contains intersecting triangles.
This ‘border’ method is slower on large borders, does not introduce any new point and has a better chance of avoiding intersecting triangles on irregular 3D borders.
The resulting surface can be checked for intersecting triangles by the check() method.
Raise an error on reading the stl file.
Return a list of the degenerate faces according to area and normals.
A face is degenerate if its surface is less or equal to zero or the normal has a nan.
Read an ascii .stl file into an [n,3,3] float array.
If the .stl is large, read_ascii_large() is recommended, as it is a lot faster.
Read an ascii .stl file into an [n,3,3] float array.
This is an alternative for read_ascii, which is a lot faster on large STL models. It requires the ‘awk’ command though, so is probably only useful on Linux/UNIX. It works by first transforming the input file to a .nodes file and then reading it through numpy’s fromfile() function.
Transform an .off model to tetgen (.node/.smesh) format.
Find all rows in matrix matching given row.
Find nodes with given coordinates in a node set.
nodes is a (nnodes,3) float array of coordinates. coords is a (npts,3) float array of coordinates.
Returns a (n,) integer array with ALL the node numbers matching EXACTLY ALL the coordinates of ANY of the given points.
Find nodes with given coordinates in a node set.
nodes is a (nnodes,3) float array of coordinates. coords is a (npts,3) float array of coordinates.
Returns a (n,) integer array with THE FIRST node number matching EXACTLY ALL the coordinates of EACH of the given points.
Find triangles with given node numbers in a surface mesh.
elems is a (nelems,3) integer array of triangles. triangles is a (ntri,3) integer array of triangles to find.
Returns a (ntri,) integer array with the triangles numbers.
Remove triangles from a surface mesh.
elems is a (nelems,3) integer array of triangles. remove is a (nremove,3) integer array of triangles to remove.
Returns a (nelems-nremove,3) integer array with the triangles of nelems where the triangles of remove have been removed.
Create a plane rectangular surface consisting of a nx,ny grid.
Create the surface of a cube
Returns a TriSurface representing the surface of a unit cube. Each face of the cube is represented by two triangles.
Create a spherical surface by calling the gtssphere command.
If a filename is given, it is stored under that name, else a temporary file is created. Beware: this may take a lot of time if level is 8 or higher.
This module was mainly aimed at the drawing of Lindenmayer products (see plugins.lima and the Lima example).
The idea is that a turtle can be moved in 2D from one position to another, thereby creating a line between start and endpoint or not.
The current state of the turtle is defined by
The start conditions are: pos=(0,0), step=1., angle=0.
The followin example turtle script creates a unit square:
fd();ro(90);fd();ro(90);fd();ro(90);fd()
Classes defined in module turtle
Functions defined in module turtle
Return the sine of an angle in degrees.
Return the cosine of an angle in degrees.
Reset the turtle graphics engine to start conditions.
This resets the turtle’s state to the starting conditions pos=(0,0), step=1., angle=0., removes everything from the state save stack and empties the resulting path.
Save the current state of the turtle.
The turtle state includes its position, step and angle.
Restore the turtle state to the last saved state.
Move forward over a step d, with or without drawing.
The direction is the current direction. If d is not given, the step size is the current step.
By default, the new position is connected to the previous with a straight line segment.
Move over step d without drawing.
Rotate over angle a. The new direction is incremented with a
Go to position p (without drawing).
While the mv method performs a relative move, this is an absolute move. p is a tuple of (x,y) values.
Set the step size.
Set the angle
Play all the commands in the script scr
The script is a string of turtle commands, where each command is ended with a semicolon (‘;’).
If a dict glob is specified, it will be update with the turtle module’s globals() after each turtle command.
This module defines some basic operations on simple geometrical entities such as lines, triangles, circles, planes.
Classes defined in module geomtools
Functions defined in module geomtools
Compute the area and normal vectors of a collection of triangles.
x is an (ntri,3,3) array of coordinates.
Returns a tuple of areas,normals. The normal vectors are normalized. The area is always positive.
Compute area inside a polygon.
Parameters:
Returns: a single float value with the area inside the polygon. If a direction vector is given, the area projected in that direction is returned.
Note that if the polygon is nonplanar and no direction is given, the area inside the polygon is not well defined.
Compute normals in all points of polygons in x.
x is an (nel,nplex,3) coordinate array representing nel (possibly nonplanar) polygons.
The return value is an (nel,nplex,3) array with the unit normals on the two edges ending in each point.
Compute the incircles of the triangles x
The incircle of a triangle is the largest circle that can be inscribed in the triangle.
x is a Coords array with shape (ntri,3,3) representing ntri triangles.
Returns a tuple r,C,n with the radii, Center and unit normals of the incircles.
Compute the circumcircles of the triangles x
x is a Coords array with shape (ntri,3,3) representing ntri triangles.
Returns a tuple r,C,n with the radii, Center and unit normals of the circles going through the vertices of each triangle.
If bounding=True, this returns the triangle bounding circle.
Compute the bounding circles of the triangles x
The bounding circle is the smallest circle in the plane of the triangle such that all vertices of the triangle are on or inside the circle. If the triangle is acute, this is equivalent to the triangle’s circumcircle. It the triangle is obtuse, the longest edge is the diameter of the bounding circle.
x is a Coords array with shape (ntri,3,3) representing ntri triangles.
Returns a tuple r,C,n with the radii, Center and unit normals of the bounding circles.
Checks for obtuse triangles
x is a Coords array with shape (ntri,3,3) representing ntri triangles.
Returns an (ntri) array of True/False values indicating whether the triangles are obtuse.
Finds the intersection of 2 coplanar lines.
The lines (P1,D1) and (P2,D2) are defined by a point and a direction vector. Let a and b be unit vectors along the lines, and c = P2-P1, let ld and d be the length and the unit vector of the cross product a*b, the intersection point X is then given by X = 0.5(P1+P2+sa*a+sb*b) where sa = det([c,b,d])/ld and sb = det([c,a,d])/ld
Move all lines (A,N) over a distance a in the direction of point C.
A,N are arrays with points and directions defining the lines. C is a point. d is a scalar or a list of scalars. All line elements of F are translated in the plane (line,C) over a distance d in the direction of the point C. Returns a new set of lines (A,N).
Determine the orientation of a set of line segments.
vertices and vertices2 are matching sets of points. point is a single point. All arguments are Coords objects.
Line segments run between corresponding points of vertices and vertices2. If vertices2 is None, it is obtained by rolling the vertices one position foreward, thus corresponding to a closed polygon through the vertices). If point is None, it is taken as the center of vertices.
The orientation algorithm checks whether the line segments turn positively around the point.
Returns an array with +1/-1 for positive/negative oriented segments.
Return rotation angles and vectors for rotations of A to B.
A and B are (n,3) shaped arrays where each line represents a vector. This function computes the rotation from each vector of A to the corresponding vector of B. If m is None, the return value is a tuple of an (n,) shaped array with rotation angles (by default in degrees) and an (n,3) shaped array with unit vectors along the rotation axis. If m is a (n,3) shaped array with vectors along the rotation axis, the return value is a (n,) shaped array with rotation angles. Specify angle_spec=Rad to get the angles in radians.
Return arbitrary vectors perpendicular to vectors of A.
A is a (n,3) shaped array of vectors. The return value is a (n,3) shaped array of perpendicular vectors.
The returned vector is always a vector in the x,y plane. If the original is the z-axis, the result is the x-axis.
Return vectors perpendicular on both A and B.
Return the projection of vector of A on vector of B.
Return the projection of vector of A on plane of B.
Return the points of lines (q,m) at parameter values t.
Parameters:
Returns: An array with the points at parameter values t.
Return the points of line segments S at parameter values t.
Parameters:
Returns: An array with the points at parameter values t.
Return the intersection of lines (q1,m1) and lines (q2,m2)
with the perpendiculars between them.
Parameters:
Returns: A tuple of (nq1,nq2) shaped (mode=all) arrays of parameter values t1 and t2, such that the intersection points are given by q1+t1*m1 and q2+t2*m2.
Return the intersection points of lines (q1,m1) and lines (q2,m2)
with the perpendiculars between them.
This is like intersectionTimesLWL but returns a tuple of (nq1,nq2,3) shaped (mode=all) arrays of intersection points instead of the parameter values.
Return the intersection of lines (q,m) with planes (p,n).
Parameters:
Returns: A (nq,np) shaped (mode=all) array of parameter values t, such that the intersection points are given by q+t*m.
Return the intersection points of lines (q,m) with planes (p,n).
This is like intersectionTimesLWP but returns a (nq,np,3) shaped (mode=all) array of intersection points instead of the parameter values.
Return the intersection of line segments S with planes (p,n).
Parameters:
Returns: A (nS,np) shaped (mode=all) array of parameter values t, such that the intersection points are given by (1-t)*S[...,0,:] + t*S[...,1,:].
This function is comparable to intersectionTimesLWP, but ensures that parameter values 0<=t<=1 are points inside the line segments.
Return the intersection points of line segments S with planes (p,n).
Parameters:
Returns: if return_all==True, a (nS,np,3) shaped (mode=all) array of intersection points, else, a tuple of intersection points with shape (n,3) and line and plane indices with shape (n), where n <= nS*np.
Return the intersection of lines (q,m) with triangles F.
Parameters:
Returns: A (nq,nF) shaped (mode=all) array of parameter values t, such that the intersection points are given q+tm.
Return the intersection points of lines (q,m) with triangles F.
Parameters:
Returns: if return_all==True, a (nq,nF,3) shaped (mode=all) array of intersection points, else, a tuple of intersection points with shape (n,3) and line and plane indices with shape (n), where n <= nq*nF.
Return the intersection of lines segments S with triangles F.
Parameters:
Returns: A (nS,nF) shaped (mode=all) array of parameter values t, such that the intersection points are given by (1-t)*S[...,0,:] + t*S[...,1,:].
Return the intersection points of lines segments S with triangles F.
Parameters:
Returns: if return_all==True, a (nS,nF,3) shaped (mode=all) array of intersection points, else, a tuple of intersection points with shape (n,3) and line and plane indices with shape (n), where n <= nS*nF.
Return the intersection points of planes (p1,n1), (p2,n2) and (p3,n3).
Parameters:
Returns: A (np1,np2,np3,3) shaped (mode=all) array of intersection points.
Return the intersection lines of planes (p1,n1) and (p2,n2).
Parameters:
Returns: A tuple of (np1,np2,3) shaped (mode=all) arrays of intersection points q and vectors m, such that the intersection lines are given by q+t*m.
Return the intersection of perpendiculars from points X on planes (p,n).
Parameters:
Returns: A (nX,np) shaped (mode=all) array of parameter values t, such that the intersection points are given by X+t*n.
Return the intersection points of perpendiculars from points X on planes (p,n).
This is like intersectionTimesPOP but returns a (nX,np,3) shaped (mode=all) array of intersection points instead of the parameter values.
Return the intersection of perpendiculars from points X on lines (q,m).
Parameters:
Returns: A (nX,nq) shaped (mode=all) array of parameter values t, such that the intersection points are given by q+t*m.
Return the intersection points of perpendiculars from points X on lines (q,m).
This is like intersectionTimesPOL but returns a (nX,nq,3) shaped (mode=all) array of intersection points instead of the parameter values.
Return the distances of points X from lines (q,m).
Parameters:
Returns: A (nX,nq) shaped (mode=all) array of distances.
Return the distances of points X from line segments S.
Parameters:
Returns: A (nX,nS) shaped (mode=all) array of distances.
Checks whether the points P are inside triangles x.
x is a Coords array with shape (ntri,3,3) representing ntri triangles. P is a Coords array with shape (npts,ntri,3) representing npts points in each of the ntri planes of the triangles. This function checks whether the points of P fall inside the corresponding triangles.
Returns an array with (npts,ntri) bool values.
Compute the closest perpendicular distance to a set of triangles.
X is a (nX,3) shaped array of points. Fp is a (nF,3,3) shaped array of triangles.
Note that some points may not have a normal with footpoint inside any of the facets.
The return value is a tuple OKpid,OKdist,OKpoints where:
Compute the closest perpendicular distance of points X to a set of edges.
X is a (nX,3) shaped array of points. Ep is a (nE,2,3) shaped array of edge vertices.
Note that some points may not have a normal with footpoint inside any of the edges.
The return value is a tuple OKpid,OKdist,OKpoints where:
Compute the closest distance of points X to a set of vertices.
X is a (nX,3) shaped array of points. Vp is a (nV,3) shaped array of vertices.
The return value is a tuple OKdist,OKpoints where:
Compute the barycentric coordinates of points P wrt. simplexes S.
S is a (nel,nplex,3) shaped array of n-simplexes (n=nplex-1): - 1-simplex: line segment - 2-simplex: triangle - 3-simplex: tetrahedron P is a (npts,3), (npts,nel,3) or (npts,1,3) shaped array of points.
The return value is a (nplex,npts,nel) shaped array of barycentric coordinates.
Check if points are in simplexes.
BC is an array of barycentric coordinates (along the first axis), which sum up to one. If bound = True, a point lying on the boundary is considered to be inside the simplex.
This module provides functions and classes to export finite element models from pyFormex in the Abaqus™ input format (.inp). The exporter handles the mesh geometry as well as model, node and element properties gathered in a PropertyDB database (see module properties).
While this module provides only a small part of the Abaqus input file format, it suffices for most standard jobs. While we continue to expand the interface, depending on our own necessities or when asked by third parties, we do not intend to make this into a full implementation of the Abaqus input specification. If you urgently need some missing function, there is always the possibility to edit the resulting text file or to import it into the Abaqus environment for further processing.
The module provides two levels of functionality: on the lowest level, there are functions that just generate a part of an Abaqus input file, conforming to the Abaqus™ Keywords manual.
Then there are higher level functions that read data from the property module and write them to the Abaqus input file and some data classes to organize all the data involved with the finite element model.
Classes defined in module fe_abq
A request for output to .odb and history.
Parameters:
For kind==’‘:
For kind==’NODE’ or ‘ELEMENT’:
Format an output request.
Return a string with the formatted output command.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
A request for output of results on nodes or elements.
Parameters:
Extra keyword arguments are available: see the writeNodeResults and writeElemResults methods for details.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
A Dict for setting surface interactions pressureoverclosure is an array = [‘hard’/’soft’,’linear’/’nonlinear’/’exponential’/’tabular’/.., value1,value2,value3,... ] Leave empty for default hard contact ‘hard’ will set penalty contact, either ‘linear’ or ‘nonlinear’ ‘soft’ will set soft pressure-overclosure, combine with ‘linear’/’exponential’/’tabular’/’scale factor’ for needed values on dataline: see abaqus keyword manual
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
Contains all data required to write the Abaqus input file.
Write an Abaqus input file.
Functions defined in module fe_abq
Returns corresponding Abq jobname and input filename.
job can be either a jobname or input file name, with or without directory part, with or without extension (.inp)
The Abq jobname is the basename without the extension. The abq filename is the abspath of the job with extension ‘.inp’
Determine the name for writing a node set property.
Determine the name for writing an element set property.
Format a command.
Format numerical data in lines with maximum npl items.
data is a numeric array. The array is flattened and then the data are formatted in lines with maximum npl items, separated by sep. Lines are separated by linesep.
Format numerical data in lines with maximum npl items.
data is a numeric array, which is coerced to be a 2D array, either by adding a first axis or by collapsing the first ndim-1 axies. Then the data are formatted in lines with maximum npl items, separated by sep. Lines are separated by linesep.
Format the options of an Abaqus command line.
Returns a comma-separated string of ‘keyword’ or ‘keyword=value’ fields. The string includes an initial comma.
Format the heading of the Abaqus input file.
Start a new Part.
Write a material section.
mat is the property dict of the material. The following keys are recognized and output accordingly:
name: if specified, and a material with this name has already been written, this function does nothing.
elasticity: one of ‘LINEAR’, ‘HYPERELASTIC’, ‘ANISOTROPIC HYPERELASTIC’, ‘USER’. Default is ‘LINEAR’. Defines the elastic behavior class of the material. The requirements for the other keys depend on this type. The fields labeled (opt) are optional.
‘LINEAR’:
‘HYERELASTIC’:
required:
optional:
order: order of the model. If blank will be automatically calculated from the len of the constants list
example:
intimaMat = {
'name': 'intima',
'density': 0.1, # Not Used, but Abaqus does not like a material without
'elasticity':'hyperelastic',
'type':'reduced polynomial',
'constants': [6.79E-03, 5.40E-01, -1.11, 10.65, -7.27, 1.63, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
}
‘ANISOTROPIC HYPERELASTIC’:
‘USER’:
Write transform command for the given set.
Write a frame section for the named element set.
Recognized data fields in the property record:
Write a general beam section for the named element set.
To specify a beam section when numerical integration over the section is not required.
Recognized data fields in the property record:
Write a beam section for the named element set.
To specify a beam section when numerical integration over the section is required.
Recognized data fields in the property record:
Write a connector section.
Optional data:
Write a connector behavior. Implemented: Elasticity, Stop Examples: Elasticity P.Prop(name=’connbehavior1’,ConnectorBehavior=’‘,Elasticity=dict(component=[1,2,3,4,5,6],value=[1,1,1,1,1,1])) Stop: P.Prop(name=’connbehavior3’,ConnectorBehavior=’‘,Stop=dict(component=[1,2,3,4,5,6],lowerlimit=[1,1,1,1,1,1], upperlimit=[2, 2, 2, 2,2,2]))
Format the surface definitions.
Required:
This label can be a string, or a list of strings. This allows to use different identifiers for the different elements in the surface. Thus:
Prop(name='mysurf',set=[0,1,2,6],surftype='element',label=['S1','S2','S1','S3')
will get exported to Abaqus as:
*SURFACE, NAME=mysurf, TYPE=element
1, S1
2, S2,
1, S1
7, S3
Format the analytical surface rigid body.
Required:
Example:
>>> P.Prop(name='AnalySurf', nodeset = 'REFNOD', analyticalsurface='')
Format the interactions.
Required:
-name
Optional:
Format the general contact.
Only implemented on model level
Required:
Optional:
Example:
>>> P.Prop(generalinteraction=Interaction(name ='contactprop1'),exl =[['surf11', 'surf12'],['surf21',surf22]])
Format the contact pair.
Required:
Example:
>>> P.Prop(name='contact0',interaction=Interaction(name ='contactprop', surfacebehavior=True, pressureoverclosure=['hard','linear',0.0, 0.0, 0.001]), master ='quadtubeINTSURF1', slave='hexstentEXTSURF', contacttype='NODE TO SURFACE')
Format Tie constraint
Required:
-name -adjust (yes or no) -slave -master
Optional:
-type (surf2surf, node2surf) -no rotation
Example:
>>> P.Prop(constraint='1', name = 'constr1', adjust = 'no', master = 'hexstentbarSURF', slave = 'hexstentEXTSURF',type='NODE TO SURFACE')
Format initial conditions
Required:
-type -nodes -data
Example:
P.Prop(initialcondition='', nodes ='Nall', type = 'TEMPERATURE', data = 37.)
Format the orientation.
Optional:
Format multi-point constraint using an equation
Required:
Equation should be a list, which contains the different terms of the equation. Each term is again a list with three values:
Example:
P.nodeProp(equation=[[209,1,1],[32,1,-1]])
This forces the displacement in Y-direction of nodes 209 and 32 to be equal.
Write nodal coordinates.
The nodes are added to the named node set. If a name different from ‘Nall’ is specified, the nodes will also be added to a set named ‘Nall’. The nofs specifies an offset for the node numbers. The default is 1, because Abaqus numbering starts at 1.
Write element group of given type.
elems is the list with the element node numbers. The elements are added to the named element set. If a name different from ‘Eall’ is specified, the elements will also be added to a set named ‘Eall’. The eofs and nofs specify offsets for element and node numbers. The default is 1, because Abaqus numbering starts at 1. If eid is specified, it contains the element numbers increased with eofs.
Write a named set of nodes or elements (type=NSET|ELSET)
set : an ndarray. set can be a list of node/element numbers, in which case the ofs value will be added to them, or a list of names the name of another already defined set.
Write an element section.
prop is a an element property record with a section and eltype attribute
Write boundary conditions of type BOUNDARY, TYPE=DISPLACEMENT
prop is a list of node property records that should be scanned for displ attributes to write.
By default, the boundary conditions are applied as a modification of the existing boundary conditions, i.e. initial conditions and conditions from previous steps remain in effect. The user can set op=’NEW’ to remove the previous conditions. This will also remove initial conditions!
Write cloads.
prop is a list of node property records that should be scanned for displ attributes to write.
By default, the loads are applied as new values in the current step. The user can set op=’MOD’ to add the loads to already existing ones.
Write Dloads.
prop is a list property records having an attribute dload
By default, the loads are applied as new values in the current step. The user can set op=’MOD’ to add the loads to already existing ones.
Write Dsloads.
prop is a list property records having an attribute dsload
By default, the loads are applied as new values in the current step. The user can set op=’MOD’ to add the loads to already existing ones.
Write a request for nodal result output to the .odb file.
Write a request for nodal result output to the .fil or .dat file.
Extra arguments:
Extra arguments for output=``PRINT``:
Remark: the kind argument is not used, but is included so that we can easily call it with a Results dict as arguments
Write a request for element output to the .odb file.
Write a request for element result output to the .fil or .dat file.
Extra arguments:
pos: Position of the points in the elements at which the results are written. Should be one of:
Non-default values are only available for ABAQUS/Standard.
Extra arguments for output=’PRINT’:
Remark: the kind argument is not used, but is included so that we can easily call it with a Results dict as arguments
Write the FILE OUTPUT command for Abaqus/Explicit
Export a finite element mesh in Abaqus .inp format.
This is a convenience function to quickly export a mesh to Abaqus without having to go through the whole setup of a complete finite element model. This just writes the nodes and elements specified in the mesh to the file with the specified name. The resulting file can then be imported in Abaqus/CAE or manual be edited to create a full model. If an eltype is specified, it will oerride the value stored in the mesh. This should be used to set a correct Abaqus element type matchin the mesh.
Classes defined in module odict
An ordered dictionary.
This is a dictionary that keeps the keys in order. The default order is the insertion order. The current order can be changed at any time.
The ODict can be initialized with a Python dict or another ODict object. If a plain Python dict is used, the resulting order is undefined.
Add a dictionary to the ODict object.
The new keys will be appended to the existing, but the order of the added keys is undetemined if data is a dict object. If data is an ODict its order will be respected..
Set the order of the keys.
keys should be a list containing exactly all the keys from self.
Return the keys in order.
Return the values in order of the keys.
Return the key,value pairs in order of the keys.
Return the position of the specified key.
If the key is not in the ODict, None is returned
A named item list.
A KeyedList is a list of lists or tuples. Each item (sublist or tuple) should at least have 2 elements: the first one is used as a key to identify the item, but is also part of the information (value) of the item.
Return the key+value lists in order of the keys.
Add a dictionary to the ODict object.
The new keys will be appended to the existing, but the order of the added keys is undetemined if data is a dict object. If data is an ODict its order will be respected..
Set the order of the keys.
keys should be a list containing exactly all the keys from self.
Return the keys in order.
Return the values in order of the keys.
Return the position of the specified key.
If the key is not in the ODict, None is returned
Functions defined in module odict
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
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:
Example:
>>> Coords([1.,0.])
Coords([ 1., 0., 0.], dtype=float32)
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.
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.
Return the total number of points.
Return the total number of points.
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]
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]
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]
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.]]
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()
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. ]]
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()
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.]
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
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
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.
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.]]
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.]]
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.]]
Return the point closest to point p.
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.
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.
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.
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:
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.]]
Formatted printing of a Coords object.
The supplied format should contain 3 formatting sequences for the three coordinates of a point.
Set the coordinates from those in the given array.
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 a Coords object.
Translates the Coords in the direction dir over a distance step * length(dir).
Parameters:
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.]
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 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:
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 .
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’.
Return a copy skewed in the direction dir of plane (dir,dir1).
The coordinate dir is replaced with (dir + skew * dir1).
Reflect the coordinates in direction dir against plane at pos.
Parameters:
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.
Position an object so that points x are aligned with y.
Parameters as for arraytools.trfMatrix
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.
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.
Converts from spherical to cartesian after scaling.
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.
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.
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.
Return a Coords with a one-dimensional bump.
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.
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.
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.
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.]]
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.
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.
Maps the coordinates to an egg-shape
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.
Swap coordinate axes i and j.
Beware! This is different from numpy’s swapaxes() method !
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.
Project a Coords on a plane (or planes).
Parameters:
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..
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:
If successful, a Coords with the same structure as the input is returned.
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.
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)
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 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 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.
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 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 points form another Coords object.
This method finds the points from coords that coincide with (or are very close to) points of self.
Parameters:
This method works by concatenating the serialized point sets of both Coords and then fusing them.
Returns:
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.
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.
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.
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.
Create interpolations between two Coords.
Parameters:
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))
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’.
Translate a Coords object.
Translates the Coords in the direction dir over a distance step * length(dir).
Parameters:
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.]
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.
A collection of bound vectors in a 3D Cartesian space.
Parameters:
The default constructs a unit vector along the global x-axis.
Return the initial points of the BoundVectors.
Return the endpoints of the BoundVectors.
Return the vectors of the BoundVectors.
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.
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.
Return the total number of points.
Return the total number of points.
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]
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]
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]
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.]]
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()
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. ]]
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()
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.]
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
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
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.
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.]]
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.]]
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.]]
Return the point closest to point p.
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.
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.
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.
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:
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.]]
Formatted printing of a Coords object.
The supplied format should contain 3 formatting sequences for the three coordinates of a point.
Set the coordinates from those in the given array.
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 a Coords object.
Translates the Coords in the direction dir over a distance step * length(dir).
Parameters:
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.]
Translate a Coords object.
Translates the Coords in the direction dir over a distance step * length(dir).
Parameters:
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.]
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 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:
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 .
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’.
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’.
Return a copy skewed in the direction dir of plane (dir,dir1).
The coordinate dir is replaced with (dir + skew * dir1).
Reflect the coordinates in direction dir against plane at pos.
Parameters:
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.
Position an object so that points x are aligned with y.
Parameters as for arraytools.trfMatrix
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.
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.
Converts from spherical to cartesian after scaling.
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.
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.
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.
Return a Coords with a one-dimensional bump.
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.
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.
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.
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.]]
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.
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.
Maps the coordinates to an egg-shape
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.
Swap coordinate axes i and j.
Beware! This is different from numpy’s swapaxes() method !
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.
Project a Coords on a plane (or planes).
Parameters:
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..
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:
If successful, a Coords with the same structure as the input is returned.
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.
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)
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 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 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 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.
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 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 points form another Coords object.
This method finds the points from coords that coincide with (or are very close to) points of self.
Parameters:
This method works by concatenating the serialized point sets of both Coords and then fusing them.
Returns:
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.
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.
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.
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.
Create interpolations between two Coords.
Parameters:
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))
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.
Return the origin of the CoordinateSystem.
Return the axes of the CoordinateSystem.
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.
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.
Return the total number of points.
Return the total number of points.
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]
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]
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]
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.]]
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()
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. ]]
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()
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.]
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
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
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.
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.]]
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.]]
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.]]
Return the point closest to point p.
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.
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.
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.
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:
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.]]
Formatted printing of a Coords object.
The supplied format should contain 3 formatting sequences for the three coordinates of a point.
Set the coordinates from those in the given array.
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 a Coords object.
Translates the Coords in the direction dir over a distance step * length(dir).
Parameters:
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.]
Translate a Coords object.
Translates the Coords in the direction dir over a distance step * length(dir).
Parameters:
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.]
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 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:
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 .
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’.
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’.
Return a copy skewed in the direction dir of plane (dir,dir1).
The coordinate dir is replaced with (dir + skew * dir1).
Reflect the coordinates in direction dir against plane at pos.
Parameters:
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.
Position an object so that points x are aligned with y.
Parameters as for arraytools.trfMatrix
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.
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.
Converts from spherical to cartesian after scaling.
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.
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.
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.
Return a Coords with a one-dimensional bump.
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.
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.
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.
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.]]
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.
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.
Maps the coordinates to an egg-shape
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.
Swap coordinate axes i and j.
Beware! This is different from numpy’s swapaxes() method !
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.
Project a Coords on a plane (or planes).
Parameters:
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..
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:
If successful, a Coords with the same structure as the input is returned.
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.
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)
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 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 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 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.
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 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 points form another Coords object.
This method finds the points from coords that coincide with (or are very close to) points of self.
Parameters:
This method works by concatenating the serialized point sets of both Coords and then fusing them.
Returns:
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.
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.
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.
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.
Create interpolations between two Coords.
Parameters:
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
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:
Example:
>>> from formex import *
>>> bbox([Coords([-1.,1.,0.]),Formex('l:5')])
Coords([[-1., 0., 0.],
[ 1., 1., 0.]], dtype=float32)
Return a single point with coordinates [0.,0.,0.].
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:
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)]
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.
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.
make[2]: Map ‘/home/bene/prj’ wordt binnengegaan make[2]: Map ‘/home/bene/prj’ wordt verlaten .. $Id$ -- rst -- .. pyformex reference manual — scriptMenu .. CREATED WITH py2rst.py: DO NOT EDIT
Classes defined in module scriptMenu
A menu of pyFormex scripts in a directory or list.
This class creates a menu of pyFormex scripts collected from a directory or specified in a list. It is e.g. used in the pyFormex GUI to create the examples menu, and for the scripts history. The pyFormex scripts can then be executed from the menu. The user may use this class to add his own scripts into the pyFormex GUI.
Only files that are recognized by utils.is_pyFormex() as being pyFormex scripts will be added to the menu.
The constructor takes the following arguments:
The defaults were thus chosen to be convenient for the two most frequent uses of this class:
ScriptMenu('My Scripts',dir="/path/to/my/sciptsdir")
creates a menu will all pyFormex scripts in the specified path and its subdirectories.
ScriptMenu('History',files=["/my/script1.py","/some/other/script.pye"],recursive=False)
is typically used to create a history menu of previously visited files.
With the resulting file list, a menu is created. Selecting a menu item will make the corresponding file the current script and unless the autoplay configuration variable was set to False, the script is executed.
If the file specification was done by a directory path only, some extra options will be included in the menu. They are fairly self-explaining and mainly intended for the pyFormex developers, in order to test the functionality by running a sets of example scripts:
Furthermore, if the menu is a toplevel one, it will have the following extra options:
The first option uses the keyword specifications in the scripts docstring to make a classification of the scripts according to keywords. See the scriptKeywords() function for more info. The second option removes the classification. Both options are especially useful for the pyFormex examples.
The last option reloads a ScriptMenu. This can be used to update the menu when you created a new script file.
Return the full pathname for a scriptname.
Get a list of scripts in self.dir
Filter a list of scripts
Load the script files in this menu
Run the selected script.
Run the specified script.
Run the next script.
Run the current and all following scripts.
Run all scripts.
Run all the scripts in given list.
Run a random script.
Run all scripts in a random order.
Reload the scripts from dir.
This is only available if a directory path was specified and no files.
Add a new filename to the front of the menu.
By default, only legal pyFormex scripts can be added.
Classify the files in submenus according to keywords.
Functions defined in module scriptMenu
Extract a keyword = value pair from a string.
If the input string s is of the form keyword = value a tuple (keyword,value) is returned, else None.
Read the script keywords from a script file.
Script keywords are written in the form:
key = value
in the docstring of the script. The docstring is the first non-indented multiline string of the file. A multiline string is a string delimited by triple double-quotes. Matching lines are placed in a dictionary which becomes the return value.
If a list of keywords is given, the return dictionary will only contain the matching values.
Turn the set values in d into sorted lists.
All the values in the dictionary are checked. Those that are of type set are converted to a sorted list.
Create the menu(s) with pyFormex scripts
This creates a menu with all examples distributed with pyFormex. By default, this menu is put in the top menu bar with menu label ‘Examples’.
The user can add his own script directories through the configuration settings. In that case the ‘Examples’ menu and menus for all the configured script paths will be gathered in a top level popup menu labeled ‘Scripts’.
The menu will be placed in the top menu bar before the specified item. If a menu item named ‘Examples’ or ‘Scripts’ already exists, it is replaced.
Classes defined in module utils
A class for autogenerating sequences of names.
The name is a string including a numeric part, which is incremented at each call of the ‘next()’ method.
The constructor takes name template and a possible extension as arguments. If the name starts with a non-numeric part, it is taken as a constant part. If the name ends with a numeric part, the next generated names will be obtained by incrementing this part. If not, a string ‘-000’ will be appended and names will be generated by incrementing this part.
If an extension is given, it will be appended as is to the names. This makes it possible to put the numeric part anywhere inside the names.
Example:
>>> N = NameSequence('hallo.98')
>>> [ N.next() for i in range(3) ]
['hallo.98', 'hallo.99', 'hallo.100']
>>> NameSequence('hallo','.png').next()
'hallo-000.png'
>>> N = NameSequence('/home/user/hallo23','5.png')
>>> [ N.next() for i in range(2) ]
['/home/user/hallo235.png', '/home/user/hallo245.png']
Return the next name in the sequence
Return the next name in the sequence without incrementing.
Return a UNIX glob pattern for the generated names.
A NameSequence is often used as a generator for file names. The glob() method returns a pattern that can be used in a UNIX-like shell command to select all the generated file names.
Functions defined in module utils
Checks a version of a program/module.
name is either a module or an external program whose availability has been registered. Default is to treat name as a module. Add external=True for a program.
Return value is -1, 0 or 1, depending on a version found that is <, == or > than the requested values. This should normally understand version numbers in the format 2.10.1 Returns -2 if no version found.
Test if we have the named module available.
Returns a nonzero (version) string if the module is available, or an empty string if it is not.
By default, the module is only checked on the first call. The result is remembered in the the_version dict. The optional argument check==True forces a new detection.
Test if we have the external command ‘name’ available.
Returns a nonzero string if the command is available, or an empty string if it is not.
The external command is only checked on the first call. The result is remembered in the the_external dict.
Check if the named Python module is available, and record its version.
The version string is returned, empty if the module could not be loaded. The (name,version) pair is also inserted into the the_version dict.
Check if the named external command is available on the system.
name is the generic command name, command is the command as it will be executed to check its operation, answer is a regular expression to match positive answers from the command. answer should contain at least one group. In case of a match, the contents of the match will be stored in the the_external dict with name as the key. If the result does not match the specified answer, an empty value is inserted.
Usually, command will contain an option to display the version, and the answer re contains a group to select the version string from the result.
As a convenience, we provide a list of predeclared external commands, that can be checked by their name alone. If no name is given, all commands in that list are checked, and no value is returned.
Normalize a string.
Text normalization removes all ‘&’ characters and converts it to lower case.
Prepend a prefix to a list of filenames.
Return multiple regular expression matches of the same target string.
Return the number of matches of target to regexps.
Check whether target matches any of the regular expressions.
Check whether targes matches none of the regular expressions.
Check whether targets matches all of the regular expressions.
List all files in path.
If dirs==False, directories are not listed. By default the tree is listed top down and entries in the same directory are unsorted.
exludedirs and excludefiles are lists of regular expressions with dirnames, resp. filenames to exclude from the result.
includedirs and includefiles can be given to include only the directories, resp. files matching any of those patterns.
Note that ‘excludedirs’ and ‘includedirs’ force top down handling.
Remove all files below path. If top==True, also path is removed.
Return a list of the pyformex source .py files.
Set a sane local configuration for LC_NUMERIC.
localestring is the locale string to be set, e.g. ‘en_US.UTF-8’
This will change the LC_ALL setting to the specified string, and set the LC_NUMBERIC to ‘C’.
Changing the LC_NUMERIC setting is a very bad idea! It makes floating point values to be read or written with a comma instead of a the decimal point. Of course this makes input and output files completely incompatible. You will often not be able to process these files any further and create a lot of troubles for yourself and other people if you use an LC_NUMERIC setting different from the standard.
Because we do not want to help you shoot yourself in the foot, this function always sets LC_NUMERIC back to a sane value and we call this function when pyFormex is starting up.
Return a list with all known image extensions.
Return a description of the specified file type.
The description of known types are listed in a dict file_description. If the type is unknown, the returned string has the form TYPE files (*.type)
Normalize a filetype string.
The string is converted to lower case and a leading dot is removed. This makes it fit for use with a filename extension.
Example:
>>> fileType('pdf')
'pdf'
>>> fileType('.pdf')
'pdf'
>>> fileType('PDF')
'pdf'
>>> fileType('.PDF')
'pdf'
Derive the file type from the file name.
The derived file type is the file extension part in lower case and without the leading dot.
Example:
>>> fileTypeFromExt('pyformex.pdf')
'pdf'
>>> fileTypeFromExt('.pyformexrc')
''
>>> fileTypeFromExt('pyformex')
''
Return the file name for an icon with given name.
If no icon file is found, returns the question mark icon.
Derive a project name from a file name.
The project name is the basename f the file without the extension.
Return the (UNIX) time of last change of file fn.
Return the time needed for evaluating a string.
s is a string with a valid Python instructions. The string is evaluated using Python’s eval() and the difference in seconds between the current time before and after the evaluation is printed. The result of the evaluation is returned.
This is a simple method to measure the time spent in some operation. It should not be used for microlevel instructions though, because the overhead of the time calls. Use Python’s timeit module to measure microlevel execution time.
Return the number of lines in a text file.
Run a command and raise error if exited with error.
cmd is a string with the command to be run. The command is run in the background, waiting for the result. If no error occurs, the exit status and stdout are returned. Else an error is raised by default.
Spawn a child process.
Send the specified signal to the processes in list
Change the extension of a file name.
The extension is the minimal trailing part of the filename starting with a ‘.’. If the filename has no ‘.’, the extension will be appended. If the given extension does not start with a dot, one is prepended.
Perform tilde expansion on a filename.
Bash, the most used command shell in Linux, expands a ‘~’ in arguments to the users home direction. This function can be used to do the same for strings that did not receive the bash tilde expansion, such as strings in the configuration file.
Find the name of the user.
Checks whether a file is a pyFormex script.
A script is considered to be a pyFormex script if its first line starts with ‘#!’ and contains the substring ‘pyformex’ A file is considered to be a pyFormex script if its name ends in ‘.py’ and the first line of the file contains the substring ‘pyformex’. Typically, a pyFormex script starts with a line:
#!/usr/bin/pyformex
Split a string in any prefix and a numerical end sequence.
A string like ‘abc-0123’ will be split in ‘abc-‘ and ‘0123’. Any of both can be empty.
Split a string in a numerical sequence and any suffix.
A string like ‘0123-abc’ will be split in ‘0123’ and ‘-abc’. Any of both can be empty.
Prefix all the keys of a dict with the given prefix.
The return value is a dict with all the items of d, but where the keys have been prefixed with the given string.
Return a dict with the items whose key starts with prefix.
The return value is a dict with all the items from d whose key starts with prefix. The keys in the returned dict will have the prefix stripped off, unless strip=False is specified.
Return a dict with the items whose key is in keys.
The return value is a dict with all the items from d whose key is in keys. See removeDict() for the complementary operation.
Example:
>>> d = dict([(c,c*c) for c in range(6)])
>>> selectDict(d,[4,0,1])
{0: 0, 1: 1, 4: 16}
Remove a set of keys from a dict.
The return value is a dict with all the items from d whose key is not in keys. This is the complementary operation of selectDict.
Example:
>>> d = dict([(c,c*c) for c in range(6)])
>>> removeDict(d,[4,0])
{1: 1, 2: 4, 3: 9, 5: 25}
Refresh a dict with values from another dict.
The values in the dict d are update with those in src. Unlike the dict.update method, this will only update existing keys but not add new keys.
Returns a (non)linear response on the input x.
xval and yval should be lists of 3 values: [xmin,x0,xmax], [ymin,y0,ymax]. Together with the exponent exp, they define the response curve as function of x. With an exponent > 0, the variation will be slow in the neighbourhood of (x0,y0). For values x < xmin or x > xmax, the limit value ymin or ymax is returned.
Print useful information about item.
A simple database stored as a flat text file.
Classes defined in module flatkeydb
A database stored as a dictionary of dictionaries.
Each record is a dictionary where keys and values are just strings. The field names (keys) can be different for each record, but there is at least one field that exists for all records and will be used as the primary key. This field should have unique values for all records.
The database itself is also a dictionary, with the value of the primary key as key and the full record as value.
On constructing the database a list of keys must be specified that will be required for each record. The first key in this list will be used as the primary key. Obviously, the list must at least have one required key.
The database is stored in a flat text file. Each field (key,value pair) is put on a line by itself. Records are delimited by a (beginrec, endrec) pair. The beginrec marker can be followed by a (key,value) pair on the same line. The endrec marker should be on a line by itself. If endrec is an empty string, each occurrence of beginrec will implicitly end the previous record.
Lines starting with the comment string are ignored. They can occur anywhere between or inside records. Blank lines are also ignored (except they serve as record delimiter if endrec is empty)
Thus, with the initialization:
FlatDB(req_keys=['key1'], comment = 'com', key_sep = '=',
beginrec = 'rec', endrec = '')
the following is a legal database:
com This is a comment
com
rec key1=val1
key2=val2
rec
com Yes, this starts another record
key1=val3
key3=val4
The readFile function can even be instructed to ignore anything not between a (beginrec,endrec) pair. This allows for multiple databases being stored on the same file, even with records intermixed.
Keys and values can be any strings, except that a key can not begin nor end with a blank, and can not be equal to any of the comment, beginrec or endrec markers. Whitespace around the key is always stripped. By default, this is also done for the value (though this can be switched off.) If strip_quotes is True (default), a single pair of matching quotes surrounding the value will be stripped off. Whitespace is stripped before stripping the quotes, so that by including the value in quotes, you can keep leading and trailing whitespace in the value.
A record checking function can be specified. It takes a record as its argument. It is called whenever a new record is inserted in the database (or an existing one is replaced). Before calling this check_func, the system will already have checked that the record is a dictionary and that it has all the required keys.
Two error handlers may be overridden by the user:
The default for both is to raise an error. Overriding is done by changing the instance attibute.
Returns a new (empty) record.
The new record is a temporary storage. It should be added to the database by calling append(record). This method can be overriden in subclasses.
Check that record has the required keys.
Check a record.
This function checks that the record is a dictionary type, that the record has the required keys, and that check_func(record) returns True (if a check_func was specified). If the record passes, just return True. If it does not, call the record_error_handler and (if it returns) return False. This method can safely be overriden in subclasses.
Error handler called when a check error on record is discovered.
Default is to raise a runtime error. This method can safely be overriden in subclasses.
Error handler called when a duplicate key is found.
Default is to raise a runtime error. This method can safely be overriden in subclasses.
Insert a record to the database, overwriting existing records.
This is equivalent to __setitem__ but using the value stored in the the primary key field of the record as key for storing the record. This is also similar to append(), but overwriting an old record with the same primary key.
Add a record to the database.
Since the database is a dictionary, keys are unique and appending a record with an existing key is not allowed. If you want to overwrite the old record, use insert() instead.
Split a line in key,value pair.
The field is split on the first occurrence of the key_sep. Key and value are then stripped of leading and trailing whitespace. If there is no key_sep, the whole line becomes the key and the value is an empty string. If the key_sep is the first character, the key becomes an empty string.
Parse a line of the flat database file.
A line starting with the comment string is ignored. Leading whitespace on the remaining lines is ignored. Empty (blank) lines are ignored, unless the ENDREC mark was set to an empty string, in which case they count as an end of record if a record was started. Lines starting with a ‘BEGINREC’ mark start a new record. The remainder of the line is then reparsed. Lines starting with an ‘ENDREC’ mark close and store the record. All lines between the BEGINREC and ENDREC should be field definition lines of the type ‘KEY [ = VALUE ]’. This function returns 0 if the line was parsed correctly. Else, the variable self.error_msg is set.
Read a database from text.
lines is an iterater over text lines (e.g. a text file or a multiline string splitted on ‘n’) Lines starting with a comment string are ignored. Every record is delimited by a (beginrec,endrec) pair. If ignore is True, all lines that are not between a (beginrec,endrec) pair are simply ignored. Default is to raise a RuntimeError.
Read a database from file.
Lines starting with a comment string are ignored. Every record is delimited by a (beginrec,endrec) pair. If ignore is True, all lines that are not between a (beginrec,endrec) pair are simply ignored. Default is to raise a RuntimeError.
Write the database to a text file.
Default mode is ‘w’. Use ‘a’ to append to the file. The header is written at the start of the database. Make sure to start each line with a comment marker if you want to read it back!
Return a list of records matching key=value.
This returns a list of primary keys of the matching records.
Functions defined in module flatkeydb
Return the first word of a string.
Words are delimited by blanks. If the string does not contain a blank, the whole string is returned.
Remove one level of quotes from a string.
If the string starts with a quote character (either single or double) and ends with the SAME character, they are stripped of the string.
Split a string in a (key,value) on occurrence of key_sep.
The string is split on the first occurrence of the substring key_sep. Key and value are then stripped of leading and trailing whitespace. If there is no key_sep, the whole string becomes the key and the value is an empty string. If the string starts with key_sep, the key becomes an empty string.
This function can be used to override the default error handlers.
The effect will be to ignore the error (duplicate key, invalid record) and to not add the affected data to the database.
Properties can really be just about any Python object. Properties can be attributed to a set of geometrical elements.
Classes defined in module properties
A class for storing properties in a database.
Import all records from a database file.
For now, it can only read databases using flatkeydb. args and kargs can be used to specify arguments for the FlatDB constructor.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
A class for storing material properties.
Import all records from a database file.
For now, it can only read databases using flatkeydb. args and kargs can be used to specify arguments for the FlatDB constructor.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
A class for storing section properties.
Import all records from a database file.
For now, it can only read databases using flatkeydb. args and kargs can be used to specify arguments for the FlatDB constructor.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
Properties related to the section of an element.
An element section property can hold the following sub-properties:
the geometric properties of the section. This can be a dict or a string. If it is a string, its value is looked up in the global section database. The required data in the dict depend on the sectiontype. Currently the following keys are used by fe_abq.py:
the type of section: should be one of following:
!! Currently only ‘solid’ and ‘general’ are allowed.
Create or replace the section properties of the element.
If ‘section’ is a dict, it will be added to ‘self.secDB’. If ‘section’ is a string, this string will be used as a key to search in ‘self.secDB’.
Compute the section characteristics of specific sections.
Create or replace the material properties of the element.
If the argument is a dict, it will be added to ‘self.matDB’. If the argument is a string, this string will be used as a key to search in ‘self.matDB’.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
Distributed loading on an element.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
Distributed loading on an element edge.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
A class for storing coordinate systems.
A class for storing an amplitude.
The amplitude is a list of tuples (time,value).
A database class for all properties.
This class collects all properties that can be set on a geometrical model.
This should allow for storing:
Set the materials database to an external source
Set the sections database to an external source
Create a new property, empty by default.
A property can hold almost anything, just like any Dict type. It has however four predefined keys that should not be used for anything else than explained hereafter:
Besides these, any other fields may be defined and will be added without checking.
Return all properties of type kind matching tag and having attr.
kind is either ‘’, ‘n’, ‘e’ or ‘m’ If rec is given, it is a list of record numbers or a single number. If a tag or a list of tags is given, only the properties having a matching tag attribute are returned.
attr and noattr are lists of attributes. Only the properties having all the attributes in attr and none of the properties in noattr are returned. Attributes whose value is None are treated as non-existing.
If delete==True, the returned properties are removed from the database.
Delete properties.
This is equivalent to getProp() but the returned properties are removed from the database.
Create a new node property, empty by default.
A node property can contain any combination of the following fields:
Create a new element property, empty by default.
An elem property can contain any combination of the following fields:
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
Functions defined in module properties
Check that a variable is a list of (id,value) tuples
id should be convertible to an int, value to a float. If ok, return the values as a list of (int,float) tuples.
Check that a variable is an list of values or (id,value) tuples
This convenience function checks that the argument is either:
If ok, return the values as a list of (int,float) tuples.
Check that a string a has one of the valid values.
This is case insensitive, and returns the upper case string if valid. Else, an error is raised.
Find the item p in the list l.
If p is an item in the list (not a copy of it!), this returns its position. Else, -1 is returned.
Matches are found with a ‘is’ function, not an ‘==’. Only the first match will be reported.
Remove the item p from the list l.
If p is an item in the list (not a copy of it!), it is removed from the list. Matches are found with a ‘is’ comparison. This is different from the normal Python list.remove() method, which uses ‘==’. As a result, we can find complex objects which do not allow ‘==’, such as ndarrays.
CDict is a Dict with lookup cascading into the next level Dict’s if the key is not found in the CDict itself.
(C) 2005,2008 Benedict Verhegghe Distributed under the GNU GPL version 3 or later
Classes defined in module mydict
A Python dictionary with default values and attribute syntax.
Dict is functionally nearly equivalent with the builtin Python dict, but provides the following extras:
There are a few caveats though:
Keys that are also attributes of the builtin dict type, can not be used with the attribute syntax to get values from the Dict. You should use the dictionary syntax to access these items. It is possible to set such keys as attributes. Thus the following will work:
C['get'] = 'foo'
C.get = 'foo'
print(C['get'])
but this will not:
print(C.get)
This is done so because we want all the dict attributes to be available with their normal binding. Thus,
print(C.get('get'))
will print foo
To avoid name clashes with user defines, many Python internal names start and end with ‘__’. The user should avoid such names. The Python dict has the following attributes not enclosed between ‘__’, so these are the ones to watch out for: ‘clear’, ‘copy’, ‘fromkeys’, ‘get’, ‘has_key’, ‘items’, ‘iteritems’, ‘iterkeys’, ‘itervalues’, ‘keys’, ‘pop’, ‘popitem’, ‘setdefault’, ‘update’, ‘values’.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
A cascading Dict: properties not in Dict are searched in all Dicts.
This is equivalent to the Dict class, except that if a key is not found and the CDict has items with values that are themselves instances of Dict or CDict, the key will be looked up in those Dicts as well.
As you expect, this will make the lookup cascade into all lower levels of CDict’s. The cascade will stop if you use a Dict. There is no way to guarantee in which order the (Cascading)Dict’s are visited, so if multiple Dicts on the same level hold the same key, you should know yourself what you are doing.
Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
Return the value for key or a default.
This is the equivalent of the dict get method, except that it returns only the default value if the key was not found in self, and there is no _default_ method or it raised a KeyError.
Replaces the setdefault function of a normal dictionary.
This is the same as the get method, except that it also sets the default value if get found a KeyError.
Functions defined in module mydict
Cascading lookup in a dictionary.
This is equivalent to the dict lookup, except that when the key is not found, a cascading lookup through lower level dict’s is started and the first matching key found is returned.
Always returns None.
Raise a KeyError.
The draw module provides the basic user interface to the OpenGL rendering capabilities of pyFormex. The full contents of this module is available to scripts running in the pyFormex GUI without the need to import it.
Classes defined in module draw
Functions defined in module draw
Close the GUI.
Calling this function from a script closes the GUI and terminates pyFormex.
Close the named dialog.
Closes the InputDialog with the given name. If multiple dialogs are open with the same name, all these dialogs are closed.
This only works for dialogs owned by the pyFormex GUI.
Show a short message widget and wait for user acknowledgement.
There are three levels of messages: ‘info’, ‘warning’ and ‘error’. They differ only in the icon that is shown next to the test. By default, the message widget has a single button with the text ‘OK’. The dialog is closed if the user clicks a button. The return value is the button text.
Show an informational message and wait for user acknowledgement.
Show a warning message and wait for user acknowledgement.
Show an error message and wait for user acknowledgement.
Ask a question and present possible answers.
Return answer if accepted or default if rejected. The remaining arguments are passed to the InputDialog getResult method.
Show a Yes/No question and return True/False depending on answer.
Display a text and wait for user response.
This opens a TextBox widget and displays the text in the widget. Scrollbars will be added if the text is too large to display at once.
The text can be plain text format. Some rich text formats will be recognized and rendered appropriately. See widgets.TextBox.
mono=True forces the use of a monospaced font.
Display a text file.
This will use the showText() function to display a text read from a file. By default this uses a monospaced font. Other arguments may also be passed to ShowText.
Show the Description part of the docstring of a pyFormex script.
If no file name is specified, the current script is used. If the script’s docstring has no Description part, a default text is shown.
Ask the value of some items to the user.
Create an interactive widget to let the user set the value of some items. ‘items’ is a list of input items (basically [key,value] pairs). See the widgets.InputDialog class for complete description of the available input items.
Two InputDialog classes are defined in gui.widgets. The OldInputDialog class is deprecated in favor of InputDialog, which has become the default as of pyFormex 0.8.3. The two classes differ in how the input is specified. In the new format, each input item is either a simpleInputItem, a groupInputItem or a tabInputItem.
You can specify ‘legacy=False’ to indicate that you are using the new format, or ‘legacy=True’ if your data are in the old format. The default (‘legacy = None’), will make this function try to detect the format and convert the input items to the proper new format. This conversion will work on most, but not all legacy formats that have been used in the past by pyFormex. Since the legacy format is scheduled to be withdrawn in future, users are encouraged to change their input to the new format.
The remaining arguments are keyword arguments that are passed to the InputDialog.getResult method. A timeout (in seconds) can be specified to have the input dialog interrupted automatically.
Return a dictionary with the results: for each input item there is a (key,value) pair. Returns an empty dictionary if the dialog was canceled. Sets the dialog timeout and accepted status in global variables.
Returns the current dialog widget.
This returns the dialog widget created by the askItems() function, while the dialog is still active. If no askItems() has been called or if the user already closed the dialog, None is returned.
Returns True if the last askItems() dialog was accepted.
Returns True if the last askItems() dialog was rejected.
Returns True if the last askItems() dialog timed out.
Ask for a file name or multiple file names using a file dialog.
cur is a directory or filename. All the files matching the filter in that directory (or that file’s directory) will be shown. If cur is a file, it will be selected as the current filename.
Unless the user cancels the operation, or the change parameter was set to False, the parent directory of the selected file will become the new working directory.
Ask a single new filename.
This is a convenience function for calling askFilename with the arguments exist=False.
Interactively select a directory and change the current workdir.
The user is asked to select a directory through the standard file dialog. Initially, the dialog shows all the subdirectories in the specified path, or by default in the current working directory.
The selected directory becomes the new working directory, unless the user canceled the operation, or the change parameter was set to False.
Ask the user to change the current workdir if it is not writable.
Returns True if the new workdir is writable.
Print a message on the message board.
If a logfile was opened, the message is also written to the log file.
Print a message on the message board.
If a logfile was opened, the message is also written to the log file.
Flatten a list of geometric objects.
Each item in the list should be either:
This function will flatten the lists and replace the string items with the object they point to. The result is a single list of drawable objects. This function does not enforce the objects to be drawable. That should be done by the caller.
Filters the drawable objects from a list.
The input is a list, usually of drawable objects. For each item in the list, the following is done:
The result is a list of drawable objects (since a Formex is drawable).
Draw object(s) with specified settings and direct camera to it.
The first argument is an object to be drawn. All other arguments are settings that influence how the object is being drawn.
F is one of:
The variables are replaced with their value and the lists are flattened, to create a single list of objects. This then filtered for the drawable objects, and the resulting list of drawables is drawn using the remaining arguments.
The remaining arguments are drawing options. If None, they are filled in from the current viewport drawing options.
view is either the name of a defined view or ‘last’ or None. Predefined views are ‘front’,’back’,’top’,’bottom’,’left’,’right’,’iso’. With view=None the camera settings remain unchanged (but might be changed interactively through the user interface). This may make the drawn object out of view! With view=’last’, the camera angles will be set to the same camera angles as in the last draw operation, undoing any interactive changes. The initial default view is ‘front’ (looking in the -z direction).
bbox specifies the 3D volume at which the camera will be aimed (using the angles set by view). The camera position wil be set so that the volume comes in view using the current lens (default 45 degrees). bbox is a list of two points or compatible (array with shape (2,3)). Setting the bbox to a volume not enclosing the object may make the object invisible on the canvas. The special value bbox=’auto’ will use the bounding box of the objects getting drawn (object.bbox()), thus ensuring that the camera will focus on these objects. The special value bbox=None will use the bounding box of the previous drawing operation, thus ensuring that the camera’s target volume remains unchanged.
color,colormap,linewidth,alpha,marksize are passed to the creation of the 3D actor.
if color is None, it is drawn with the color specified on creation. if color == ‘prop’ and a colormap was installed, props define color. else, color should be an array of RGB values, either with shape (3,) for a single color, or (nelems,3) for differently colored elements
shrink is a floating point shrink factor that will be applied to object before drawing it.
If the Formex has properties and a color list is specified, then the the properties will be used as an index in the color list and each member will be drawn with the resulting color. If color is one color value, the whole Formex will be drawn with that color. Finally, if color=None is specified, the whole Formex is drawn in black.
Each draw action activates a locking mechanism for the next draw action, which will only be allowed after drawdelay seconds have elapsed. This makes it easier to see subsequent images and is far more elegant that an explicit sleep() operation, because all script processing will continue up to the next drawing instruction. The value of drawdelay is set in the config, or 2 seconds by default. The user can disable the wait cycle for the next draw operation by specifying wait=False. Setting drawdelay=0 will disable the waiting mechanism for all subsequent draw statements (until set >0 again).
Move the camera thus that object comes fully into view.
object can be anything having a bbox() method or a list thereof. if no view is given, the default is used.
The camera is moved with fixed axis directions to a place where the whole object can be viewed using a 45. degrees lens opening. This technique may change in future!
Set default values for the draw options.
Draw options are a set of options that hold default values for the draw() function arguments and for some canvas settings. The draw options can be specified either as a dictionary, or as keyword arguments.
Interactively ask the Drawing options from the user.
A dictionary may be specified to override the current defaults.
Draw a set of vectors.
If size==None, draws the vectors v at the points P. If size is specified, draws the vectors size*normalize(v) P, v and size are single points or sets of points. If sets, they should be of the same size.
Other drawoptions can be specified and will be passed to the draw function.
Draw a list of marks at points X.
X is a Coords array. M is a list with the same length as X. The string representation of the marks are drawn at the corresponding 3D coordinate.
Draw the feature edges of a Mesh
Draw numbers on all elements of F.
numbers is an array with F.nelems() integer numbers. If no numbers are given, the range from 0 to nelems()-1 is used. Normally, the numbers are drawn at the centroids of the elements. A translation may be given to put the numbers out of the centroids, e.g. to put them in front of the objects to make them visible, or to allow to view a mark at the centroids. If an offset is specified, it is added to the shown numbers.
Draw property numbers on all elements of F.
This calls drawNumbers to draw the property numbers on the elements. All arguments of drawNumbers except numbers may be passed. If the object F thus not have property numbers, -1 values are drawn.
Draw (local) numbers on all vertices of F.
Normally, the numbers are drawn at the location of the vertices. A translation may be given to put the numbers out of the location, e.g. to put them in front of the objects to make them visible, or to allow to view a mark at the vertices.
Draw a text at a 3D point P.
Draw the axes of a CoordinateSystem.
This draws an AxesActor corresponding to the specified Coordinatesystem. The arguments are the same as those of the AxesActor constructor.
Draw an image as a colored Formex
Draws a raster image as a colored Formex. While there are other and better ways to display an image in pyFormex (such as using the imageView widget), this function allows for interactive handling the image using the OpenGL infrastructure.
Parameters:
Draw two viewport axes at a 3D position.
Draw the bbox of the actor A.
Draw an actor and update the screen.
Remove an item or a number of items from the canvas.
Use the return value from one of the draw... functions to remove the item that was drawn from the canvas. A single item or a list of items may be specified.
Show a named view, either a builtin or a user defined.
This shows the current scene from another viewing angle. Switching views of a scene is much faster than redrawing a scene. Therefore this function is prefered over draw() when the actors in the scene remain unchanged and only the camera viewpoint changes.
Just like draw(), this function obeys the drawing lock mechanism, and by default it will restart the lock to retard the next draing operation.
Toggle the display of the global axes on or off.
If on is True, the axes triade is displayed, if False it is removed. The default (None) toggles between on and off.
Show a text at position x,y using font.
Draw an annotation.
Draw a decoration.
Create a new named view (or redefine an old).
The angles are (longitude, latitude, twist). By default, the view is local to the script’s viewport. If gui is True, it is also added to the GUI.
Set the default view for future drawing operations.
If no angles are specified, the name should be an existing view, or the predefined value ‘last’. If angles are specified, this is equivalent to createView(name,angles) followed by setView(name).
Change the background color (and redraw).
If one color is given, the background is a solid color. If two colors are given, the background color will get a vertical gradient with color on top and color2 at the bottom.
Set the default foreground color.
Gets/Sets the current canvas color map
Set the lights on or off
Set the transparency mode on or off.
Set the value of one of the material lighting parameters
typ is one of ‘ambient’,’specular’,’emission’,’shininess’ val is a value between 0.0 and 1.0
Set the linewidth to be used in line drawings.
Set the linewidth to be used in line drawings.
Set the size to be used in point drawings.
Resize the canvas to (width x height).
Clear the canvas.
This is a low level function not intended for the user.
Clear the canvas.
Removes everything from the current scene and displays an empty background.
This function waits for the drawing lock to be released, but will not reset it.
Get/Set the draw delay time.
Returns the current setting of the draw wait time (in seconds). This drawing delay is obeyed by drawing and viewing operations.
A parameter may be given to set the delay time to a new value. It should be convertable to a float. The function still returns the old setting. This may be practical to save that value to restore it later.
Wait until the drawing lock is released.
This uses the drawing lock mechanism to pause. The drawing lock ensures that subsequent draws are retarded to give the user the time to view. This use of this function is prefered over that of pause() or sleep(), because it allows your script to continue the numerical computations while waiting to draw the next screen.
This function can be used to retard other functions than `
Releases the drawing lock mechanism indefinely.
Releasing the drawing lock indefinely means that the lock will not be set again and your script will execute till the end.
Perform one step of a script.
A step is a set of instructions until the next draw operation. If a script is running, this just releases the draw lock. Else, it starts the script in step mode.
Pause the execution until an external event occurs or timeout.
When the pause statement is executed, execution of the pyformex script is suspended until some external event forces it to proceed again. Clicking the STEP or CONTINUE button will produce such an event.
Sleep until key/mouse press in the canvas or until timeout
Wake up from the sleep function.
This is the only way to exit the sleep() function. Default is to wake up from the current sleep. A mode > 0 forces wakeup for longer period.
Zoom a rectangle selected by the user.
Zoom thus that the specified bbox becomes visible.
Zoom thus that all actors become visible.
Fly through the current scene along the specified path.
This function moves the camera through the subsequent elements of the Formex. For each element the first point is used as the center of the camera and the second point as the eye (the center of the scene looked at). For a 3-plex Formex, the third point is used to define the upvector (i.e. the vertical axis of the image) of the camera. For a 2-plex Formex, the upvector is constant as specified in the arguments.
Select the current viewport.
n is an integer number in the range of the number of viewports, or is one of the viewport objects in pyformex.GUI.viewports
if n is None, selects the current GUI viewport for drawing
Set the viewports layout.
Add a new viewport.
Remove the last viewport.
Link viewport vp to viewport tovp.
Both vp and tovp should be numbers of viewports.
Update the GUI.
Highlight a selection of actors on the canvas.
K is Collection of actors as returned by the pick() method. colormap is a list of two colors, for the actors not in, resp. in the Collection K.
Highlight a selection of actor elements on the canvas.
K is Collection of actor elements as returned by the pick() method. colormap is a list of two colors, for the elements not in, resp. in the Collection K.
Highlight a selection of actor edges on the canvas.
K is Collection of TriSurface actor edges as returned by the pick() method. colormap is a list of two colors, for the edges not in, resp. in the Collection K.
Highlight a selection of actor elements on the canvas.
K is Collection of actor elements as returned by the pick() method.
Highlight a selection of partitions on the canvas.
K is a Collection of actor elements, where each actor element is connected to a collection of property numbers, as returned by the partitionCollection() method.
Remove the highlights from the current viewport
Enter interactive picking mode and return selection.
See viewport.py for more details. This function differs in that it provides default highlighting during the picking operation, a button to stop the selection operation
Parameters:
Highlight a Collection of actor/elements.
K is usually the return value of a pick operation, but might also be set by the user. mode is one of the pick modes.
Set the drawing edit mode.
Enter interactive drawing mode and return the line drawing.
See viewport.py for more details. This function differs in that it provides default displaying during the drawing operation and a button to stop the drawing operation.
The drawing can be edited using the methods ‘undo’, ‘clear’ and ‘close’, which are presented in a combobox.
Show a line drawing.
L is usually the return value of an interactive draw operation, but might also be set by the user.
This module defines the Formex class, which is the major class for representing geometry in pyFormex. The Formex class implements most functionality of Formex algebra in a consistent and easy to understand syntax.
Classes defined in module formex
A Formex is a numpy array of order 3 (axes 0,1,2) and type Float. A scalar element represents a coordinate (F:uniple).
A row along the axis 2 is a set of coordinates and represents a point (node, vertex, F: signet). For simplicity’s sake, the current implementation only deals with points in a 3-dimensional space. This means that the length of axis 2 is always 3. The user can create formices (plural of Formex) in a 2-D space, but internally these will be stored with 3 coordinates, by adding a third value 0. All operations work with 3-D coordinate sets. However, a method exists to extract only a limited set of coordinates from the results, permitting to return to a 2-D environment
A plane along the axes 2 and 1 is a set of points (F: cantle). This can be thought of as a geometrical shape (2 points form a line segment, 3 points make a triangle, ...) or as an element in FE terms. But it really is up to the user as to how this set of points is to be interpreted.
Finally, the whole Formex represents a set of such elements.
Additionally, a Formex may have a property set, which is an 1-D array of integers. The length of the array is equal to the length of axis 0 of the Formex data (i.e. the number of elements in the Formex). Thus, a single integer value may be attributed to each element. It is up to the user to define the use of this integer (e.g. it could be an index in a table of element property records). If a property set is defined, it will be copied together with the Formex data whenever copies of the Formex (or parts thereof) are made. Properties can be specified at creation time, and they can be set, modified or deleted at any time. Of course, the properties that are copied in an operation are those that exist at the time of performing the operation.
Because the Formex class is derived from Geometry, the following Formex methods exist and return the value of the same method applied on the coords attribute: x, y, z, bbox, center, centroid, sizes, dsize, bsphere, distanceFromPlane, distanceFromLine, distanceFromPoint, directionalSize, directionalWidth, directionalExtremes, __str__. Refer to the correponding Coords method for their usage.
Also, the following Coords transformation methods can be directly applied to a Formex object or a derived class object. The return value is a new object identical to the original, except for the coordinates, which will have been transformed by the specified method. Refer to the correponding Coords method for the usage of these methods: scale, translate, rotate, shear, reflect, affine, cylindrical, hyperCylindrical, toCylindrical, spherical, superSpherical, toSpherical, bump, bump1, bump2, flare, map, map1, mapd, newmap, replace, swapAxes, rollAxes, projectOnSphere, projectOnCylinder, rot, trl.
Return element i of the Formex
Return point j of element i
Return coord k of point j of element i
Return the number of elements in the formex.
Return the number of points per element.
Examples:
1: unconnected points, 2: straight line elements, 3: triangles or quadratic line elements, 4: tetraeders or quadrilaterals or cubic line elements.
Return the number of dimensions.
This is the number of coordinates for each point. In the current implementation this is always 3, though you can define 2D Formices by given only two coordinates: the third will automatically be set to zero.
Return the number of points in the formex.
This is the product of the number of elements in the formex with the number of nodes per element.
Return the shape of the Formex.
The shape of a Formex is the shape of its data array, i.e. a tuple (nelems, nplex, ndim).
Return the Formex coordinates as a numpy array (ndarray).
Since the ndarray object has a method view() returning a view on the ndarray, this method allows writing code that works with both Formex and ndarray instances. The results is always an ndarray.
Return the property numbers of the element in index
Return the highest property value used, or None
Return a list with unique property values on this Formex.
Return the centroids of all elements of the Formex.
The centroid of an element is the point whose coordinates are the mean values of all points of the element. The return value is a Coords object with nelems points.
Return a tuple of nodal coordinates and element connectivity.
A tuple of two arrays is returned. The first is float array with the coordinates of the unique nodes of the Formex. The second is an integer array with the node numbers connected by each element. The elements come in the same order as they are in the Formex, but the order of the nodes is unspecified. By the way, the reverse operation of coords,elems = fuse(F) is accomplished by F = Formex(coords[elems])
There is a (very small) probability that two very close nodes are not equivalenced by this procedure. Use it multiple times with different parameters to check. You can also set the rtol /atol parameters to influence the equivalence checking of two points. The default settting for atol is rtol * self.dsize()
Convert a Formex to a Mesh.
Converts a geometry in Formex model to the equivalent Mesh model. In the Mesh model, all points with nearly identical coordinates are fused into a single point, and elements are defined by a connectivity table with integers pointing to the corresponding vertex.
Convert a Formex to a Surface.
If the plexitude of the Formex is 3, returns a TriSurface equivalent with the Formex. Else, an error is raised.
Return formatted information about a Formex.
Return a string representation of a point
Return a string representation of an element
Return string representation of a Formex as in Formian.
Coordinates are separated by commas, points are separated by semicolons and grouped between brackets, elements are separated by commas and grouped between braces:
>>> F = Formex([[[1,0],[0,1]],[[0,1],[1,2]]])
>>> print(F)
{[1.0,0.0,0.0; 0.0,1.0,0.0], [0.0,1.0,0.0; 1.0,2.0,0.0]}
Return string representation as Formex with properties.
The string representation as done by asFormex() is followed by the words “with prop” and a list of the properties.
Return string representation as a numpy array.
Choose the default formatting for printing formices.
This sets how formices will be formatted by a print statement. Currently there are two available functions: asFormex, asArray. The user may create its own formatting method. This is a class method. It should be used asfollows: Formex.setPrintFunction(Formex.asArray).
Create or destroy the property array for the Formex.
A property array is a rank-1 integer array with dimension equal to the number of elements in the Formex (first dimension of data). You can specify a single value or a list/array of integer values. If the number of passed values is less than the number of elements, they wil be repeated. If you give more, they will be ignored.
If a value None is given, the properties are removed from the Formex.
Append the members of Formex F to this one.
This function changes the original one! Use __add__ if you want to get a copy with the sum. >>> F = Formex([[[1.0,1.0,1.0]]]) >>> G = F.append(F) >>> print(F) {[1.0,1.0,1.0], [1.0,1.0,1.0]}
Concatenate all formices in Flist.
This is a class method, not an instance method! >>> F = Formex([[[1,2,3]]],1) >>> print(Formex.concatenate([F,F,F])) {[1.0,2.0,3.0], [1.0,2.0,3.0], [1.0,2.0,3.0]}
Formex.concatenate([F,G,H]) is functionally equivalent with F+G+H. The latter is simpler to write for a list with a few elements. If the list becomes large, or the number of items in the list is not fixed, the concatenate method is easier (and faster). We made it a class method and not a global function, because that would interfere with NumPy’s own concatenate function.
Return a Formex which holds only element with numbers in ids.
idx can be a single element number or a list of numbers or any other index mechanism accepted by numpy’s ndarray
Return a Formex without the elements with numbers in ids.
idx can be a single element number or a list of numbers or any other index mechanism accepted by numpy’s ndarray
This is the complementary operation of select
Return a Formex which holds only some nodes of the parent.
idx is a list of node numbers to select. Thus, if F is a plex 3 Formex representing triangles, the sides of the triangles are given by F.selectNodes([0,1]) + F.selectNodes([1,2]) + F.selectNodes([2,0]) The returned Formex inherits the property of its parent.
Return a Formex containing only the points.
This is obviously a Formex with plexitude 1. It holds the same data as the original Formex, but in another shape: the number of points per element is 1, and the number of elements is equal to the total number of points. The properties are not copied over, since they will usually not make any sense.
The vertices() method returns the same data, but as a Coords object.
Return the points of a Formex as a 2dim Coords object.
The return value holds the same coordinate data as the input Formex, but in another shape: (npoints,3).
The points() method returns the same data, but as a Formex.
Return a Formex where the elements in F have been removed.
This is also the subtraction of the current Formex with F. Elements are only removed if they have the same nodes in the same order. This is a slow operation: for large structures, you should avoid it where possible.
Return the numbers of the elements with property val.
val is either a single integer, or a list/array of integers. The return value is an array holding all the numbers of all the elements that have the property val, resp. one of the values in val.
If the Formex has no properties, a empty array is returned.
Return a Formex which holds only the elements with property val.
val is either a single integer, or a list/array of integers. The return value is a Formex holding all the elements that have the property val, resp. one of the values in val. The returned Formex inherits the matching properties.
If the Formex has no properties, a copy with all elements is returned.
Partition a Formex according to its prop values.
Returns a dict with the prop values as keys and the corresponding partitions as values. Each value is a Formex instance. It the Formex has no props, an empty dict is returned.
Return a Formex where each element is replaced by its bbox.
The returned Formex has two points for each element: two corners of the bbox.
Return a Formex which holds only the unique elements.
Two elements are considered equal when all its points are (nearly) coincident. By default any permutation of point order is also allowed.
Two coordinate value are considered equal if they are both small compared to atol or if their difference divided by the second value is small compared to rtol.
If permutations is set False, two elements are not considered equal if one’s points are a permutation of the other’s.
Flag elements having nodal coordinates between min and max.
This function is very convenient in clipping a Formex 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 Formex.
The test plane can be defined 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 compaitble 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.
nodes specifies which nodes are taken into account in the comparisons. It should be one of the following: - a single (integer) point number (< the number of points in the Formex) - a list of point numbers - one of the special strings: ‘all’, ‘any’, ‘none’ The default (‘all’) will flag all the elements that have all their nodes between the planes x=min and x=max, i.e. the elements that fall completely between these planes. One of the two clipping planes may be left unspecified.
Return a Formex with all the elements where t>0.
t should be a 1-D integer array with length equal to the number of elements of the formex. The resulting Formex will contain all elements where t > 0. This is a convenience function for the user, equivalent to F.select(t>0).
This is the complement of clip, returning a Formex where t<=0.
Transform a linear sector into a circular one.
A sector of the (0,1) plane with given angle, starting from the 0 axis, is transformed as follows: points on the sector borders remain in place. Points inside the sector are projected from the center on the circle through the intersection points of the sector border axes and the line through the point and perpendicular to the bisector of the angle. See Diamatic example.
Transforms the first octant of the 0-1 plane into 1/6 of a circle.
Points on the 0-axis keep their position. Lines parallel to the 1-axis are transformed into circular arcs. The bisector of the first quadrant is transformed in a straight line at an angle Pi/6. This function is especially suited to create circular domains where all bars have nearly same length. See the Diamatic example.
Shrinks each element with respect to its own center.
Each element is scaled with the given factor in a local coordinate system with origin at the element center. The element center is the mean of all its nodes. The shrink operation is typically used (with a factor around 0.9) in wireframe draw mode to show all elements disconnected. A factor above 1.0 will grow the elements.
Return a Formex where all elements have been reversed.
Reversing an element means reversing the order of its points. This is equivalent to:
self.selectNodes(arange(self.nplex()-1,-1,-1))
Reflect a Formex in one of the coordinate directions
This method behaves like reflect(), but adds the reflected part to the original. Setting keep_orig=False makes it behave just like reflect().
Replicate a Formex n times with fixed step in any direction.
Returns a Formex which is the concatenation of n copies, where each copy is equal to the previous one translated over (dir,step), where dir and step are interpreted just like in the translate() method. The first of the copies is equal to the original.
Return a Formex with n replications in direction dir with step.
The original Formex is the first of the n replicas.
Replicate in two directions.
n1,n2 number of replications with steps t1,t2 in directions d1,d2 bias, taper : extra step and extra number of generations in direction d1 for each generation in direction d2
Return a Formex with n rotational replications with angular step angle around an axis parallel with one of the coordinate axes going through the given point. axis is the number of the axis (0,1,2). point must be given as a list (or array) of three coordinates. The original Formex is the first of the n replicas.
Multiple subsequent translations in axis directions.
The argument list is a sequence of tuples (axis, step). Thus translatem((0,x),(2,z),(1,y)) is equivalent to translate([x,y,z]). This function is especially conveniant to translate in calculated directions.
Extrude a Formex in one of the axis directions.
Returns a Formex with doubled plexitude.
First the original Formex is translated over n steps of length step in direction dir. Then each pair of subsequent Formices is connected to form a higher plexitude structure.
Currently, this function correctly transforms: point1 to line2, line2 to quad4, tri3 to wedge6, quad4 to hex8.
See the ‘connect’ function for a more versatile tool.
Divide a plex-2 Formex at the values in div.
Replaces each member of the Formex by a sequence of members obtained by dividing the Formex at the relative values specified in div. The values should normally range from 0.0 to 1.0.
As a convenience, if an integer is specified for div, it is taken as a number of divisions for the interval [0..1].
This function only works on plex-2 Formices (line segments).
Return the intersection of a Formex with the plane (p,n).
Currently this only works for plex-2 and plex-3 Formices.
The intersection of the Formex with a plane specified by a point p and normal n is returned. For a plex-2 Formex (lines), the returned Formex will be of plexitude 1 (points). For a plex-3 Formex (triangles) the returned Fomrex has plexitude 2 (lines).
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Return a deep copy of the object.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Cut a Formex with the plane(s) (p,n).
..warning :: This method currently only works for plexitude 2 or 3!
The default return value is a tuple of two Formices of the same plexitude as the input: (Fpos,Fneg), where Fpos is the part of the Formex at the positive side of the plane (as defined by the normal vector), and Fneg is the part at the negative side. Elements of the input Formex that are lying completely on one side of the plane will return unaltered. Elements that are crossing the plane will be cut and split up into multiple parts.
When side = ‘+’ or ‘-‘ (or ‘positive’or ‘negative’), only one of the sides is returned.
The other arguments (atol,newprops) are currently specific for the plexitude. See the cut2AtPlane and cut3AtPlane, which hold the actual implementation of this method.
Split a Formex in subFormices containing n elements.
The number of elements in the Formex should be a multiple of n. Returns a list of Formices each comprising n elements.
Write a Formex to file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Formex is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
Read a Formex from file.
fil is a filename or a file object. If the file is in a valid Formex file format, the Formex is read and returned. Otherwise, None is returned. Valid Formex file formats are described in the manual.
Create a Formex from coodinates in a string.
This uses the Coords.fromstring() method to read coordinates from a string and restructures them into a Formex of the specified plexitude.
The return value is a Coords object.
Read the coordinates of a Formex from a file
Return the number of points in the formex.
This is the product of the number of elements in the formex with the number of nodes per element.
Return a Formex with n replications in direction dir with step.
The original Formex is the first of the n replicas.
Return a Formex with n rotational replications with angular step angle around an axis parallel with one of the coordinate axes going through the given point. axis is the number of the axis (0,1,2). point must be given as a list (or array) of three coordinates. The original Formex is the first of the n replicas.
Return a Formex which holds only the unique elements.
Two elements are considered equal when all its points are (nearly) coincident. By default any permutation of point order is also allowed.
Two coordinate value are considered equal if they are both small compared to atol or if their difference divided by the second value is small compared to rtol.
If permutations is set False, two elements are not considered equal if one’s points are a permutation of the other’s.
Functions defined in module formex
Return a line segment pattern created from a string.
This function creates a list of line segments where all points lie on a regular grid with unit step. The first point of the list is [0,0,0]. Each character from the input string is interpreted as a code specifying how to move to the next point. Currently defined are the following codes: 1..8 move in the x,y plane 9 remains at the same place 0 = goto origin [0,0,0] + = go back to origin without creating a line segment When looking at the plane with the x-axis to the right, 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 an element. The effect of any other character is undefined.
The resulting list is directly suited to initialize a Formex.
Return the points of a plex-2 Formex at times t.
F is a plex 2 Formex and t is an array with F.nelems() float values which are interpreted as local parameters along the edges of the Formex, such that the first node has value 0.0 and the last has value 1.0. The return value is a coords.Coords array with the points at values t.
Return the intersection lines of a plex-3 Formex with plane (p,n).
F is a Formex of plexitude 3. p is a point specified by 3 coordinates. n is the normal vector to a plane, specified by 3 components. atol is a tolerance factor defining whether an edge is intersected by the plane.
Returns all elements of the Formex cut at plane.
F is a Formex of plexitude 2. p is a point specified by 3 coordinates. n is the normal vector to a plane, specified by 3 components.
The return value is:
To avoid roundoff errors and creation of very small elements, a tolerance can be specified. Points lying within the tolerance distance will be considered lying in the plane, and no cutting near these points.
Returns all elements of the Formex cut at plane(s).
F is a Formex of plexitude 3. p is a point or a list of points. n is the normal vector to a plane or a list of normal vectors. Both p and n have shape (3) or (npoints,3).
The return value is:
Let be the signed distance of the vertices to a plane.
The elements located completely at the positive or negative side of
a plane have three vertices for which
.
The elements intersecting a plane can have one or more vertices for which
.
These vertices are projected on the plane so that their distance is zero.
If the Formex has a property set, the new elements will get the property numbers defined in newprops. This is a list of 7 property numbers flagging elements with following properties:
This function needs documentation.
Should it be called by the user? or only via cut3AtPlane? For now, lets suppose the last, so no need to check arguments here.
newprops should be a list of 7 values: each an integer or None side is either ‘+’, ‘-‘ or ‘’
Return a Formex which connects the formices in list.
Flist is a list of formices, nodid is an optional list of nod ids and bias is an optional list of element bias values. All lists should have the same length. The returned Formex has a plexitude equal to the number of formices in list. Each element of the Formex consist of a node from the corresponding element of each of the formices in list. By default this will be the first node of that element, but a nodid list may be given to specify the node id to be used for each of the formices. Finally, a list of bias values may be given to specify an offset in element number for the subsequent formices. If loop==False, the order of the Formex will be the minimum order of the formices in Flist, each minus its respective bias. By setting loop=True however, each Formex will loop around if its end is encountered, and the order of the result is the maximum order in Flist.
Create interpolations between two formices.
F and G are two Formices 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 Formex H where each coordinate Hijk is obtained from: Hijk = Fijk + v * (Gijk-Fijk). Thus, a Formex interpolate(F,G,[0.,0.5,1.0]) will contain all elements of F and G and all elements 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 swap argument sets the order of the elements in the resulting Formex. By default, if n interpolations are created of an m-element Formex, the element order is in-Formex first (n sequences of m elements). If swap==True, the order is swapped and you get m sequences of n interpolations.
This module defines a generic Geometry superclass which adds all the possibilities of coordinate transformations offered by the Coords class to the derived classes.
Classes defined in module geometry
A generic geometry object allowing transformation of coords sets.
The Geometry class is a generic parent class for all geometric classes, intended to make the Coords transformations available without explicit declaration. This class is not intended to be used directly, only through derived classes. Examples of derived classes are Formex, Mesh, Curve.
There is no initialization to be done when constructing a new instance of this class. The class just defines a set of methods which operate on the attribute coords, which should be a Coords object. Most of the transformation methods of the Coords class are thus exported through the Geometry class to its derived classes, and when called, will get executed on the coords attribute. The derived class constructor should make sure that the coords attribute exists, has the proper type and contains the coordinates of all the points that should get transformed under a Coords transformation.
Derived classes can (and in most cases should) declare a method _set_coords(coords) returning an object that is identical to the original, except for its coords being replaced by new ones with the same array shape.
The Geometry class provides two possible default implementations:
When using the first method, a statement like `B = A.scale(0.5)` will result in both A and B pointing to the same scaled object, while with the second method, A would still be the untransformed object. Since the latter is in line with the design philosophy of pyFormex, it is set as the default _set_coords method. Most derived classes that are part of pyFormex however override this default and implement a more efficient copy method.
The following Geometry methods return the value of the same method applied on the coords attribute. Refer to the correponding coords.Coords method for their precise arguments.
x(), y(), z(), bbox(), center(), centroid(), sizes(), dsize(), bsphere(), distanceFromPlane(), distanceFromLine(), distanceFromPoint(), directionalSize(), directionalWidth(), directionalExtremes(), __str__().
The following Coords transformation methods can be directly applied to a Geometry object or a derived class object. The return value is a new object identical to the original, except for the coordinates, which will have been transformed by the specified method. Refer to the correponding coords.Coords method in for the precise arguments of these methods:
scale(), translate(), centered(), rotate(), shear(), reflect(), affine(), position(), cylindrical(), hyperCylindrical(), toCylindrical(), spherical(), superSpherical(), toSpherical(), bump(), bump1(), bump2(), flare(), map(), map1(), mapd(), replace(), swapAxes(), rollAxes(), projectOnPlane(), projectOnSphere(), projectOnCylinder(), isopar(), transformCS(), addNoise(), rot(), trl().
Return a deep copy of the object.
Apply ‘scale’ transformation to the Geometry object.
See coords.Coords.scale() for details.
Return a scaled copy of the Formex with given size in all directions.
If a direction has zero size, it is not rescaled.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Apply ‘centered’ transformation to the Geometry object.
See coords.Coords.centered() for details.
Apply ‘align’ transformation to the Geometry object.
See coords.Coords.align() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘shear’ transformation to the Geometry object.
See coords.Coords.shear() for details.
Apply ‘reflect’ transformation to the Geometry object.
See coords.Coords.reflect() for details.
Apply ‘affine’ transformation to the Geometry object.
See coords.Coords.affine() for details.
Apply ‘position’ transformation to the Geometry object.
See coords.Coords.position() for details.
Apply ‘cylindrical’ transformation to the Geometry object.
See coords.Coords.cylindrical() for details.
Apply ‘hyperCylindrical’ transformation to the Geometry object.
See coords.Coords.hyperCylindrical() for details.
Apply ‘toCylindrical’ transformation to the Geometry object.
See coords.Coords.toCylindrical() for details.
Apply ‘spherical’ transformation to the Geometry object.
See coords.Coords.spherical() for details.
Apply ‘superSpherical’ transformation to the Geometry object.
See coords.Coords.superSpherical() for details.
Apply ‘egg’ transformation to the Geometry object.
See coords.Coords.egg() for details.
Apply ‘toSpherical’ transformation to the Geometry object.
See coords.Coords.toSpherical() for details.
Apply ‘bump’ transformation to the Geometry object.
See coords.Coords.bump() for details.
Apply ‘bump1’ transformation to the Geometry object.
See coords.Coords.bump1() for details.
Apply ‘bump2’ transformation to the Geometry object.
See coords.Coords.bump2() for details.
Apply ‘flare’ transformation to the Geometry object.
See coords.Coords.flare() for details.
Apply ‘map’ transformation to the Geometry object.
See coords.Coords.map() for details.
Apply ‘map1’ transformation to the Geometry object.
See coords.Coords.map1() for details.
Apply ‘mapd’ transformation to the Geometry object.
See coords.Coords.mapd() for details.
Apply ‘replace’ transformation to the Geometry object.
See coords.Coords.replace() for details.
Apply ‘swapAxes’ transformation to the Geometry object.
See coords.Coords.swapAxes() for details.
Apply ‘rollAxes’ transformation to the Geometry object.
See coords.Coords.rollAxes() for details.
Apply ‘projectOnPlane’ transformation to the Geometry object.
See coords.Coords.projectOnPlane() for details.
Apply ‘projectOnSphere’ transformation to the Geometry object.
See coords.Coords.projectOnSphere() for details.
Apply ‘projectOnCylinder’ transformation to the Geometry object.
See coords.Coords.projectOnCylinder() for details.
Apply ‘isopar’ transformation to the Geometry object.
See coords.Coords.isopar() for details.
Apply ‘transformCS’ transformation to the Geometry object.
See coords.Coords.transformCS() for details.
Apply ‘addNoise’ transformation to the Geometry object.
See coords.Coords.addNoise() for details.
Apply ‘rotate’ transformation to the Geometry object.
See coords.Coords.rotate() for details.
Apply ‘translate’ transformation to the Geometry object.
See coords.Coords.translate() for details.
Write a Geometry to a .pgf file.
If fil is a string, a file with that name is opened. Else fil should be an open file. The Geometry is then written to that file in a native format, using sep as separator between the coordinates. If fil is a string, the file is closed prior to returning.
Functions defined in module geometry
This module defines the Collection class.
Classes defined in module collection
A collection is a set of (int,int) tuples.
The first part of the tuple has a limited number of values and are used as the keys in a dict. The second part can have a lot of different values and is implemented as an integer array with unique values. This is e.g. used to identify a set of individual parts of one or more OpenGL actors.
Add new data to the collection.
data can be a 2d array with (key,val) tuples or a 1-d array of values. In the latter case, the key has to be specified separately, or a default value will be used.
Set the collection to the specified data.
This is equivalent to clearing the corresponding keys before adding.
Remove data from the collection.
Check whether the collection has an entry for the key.
Return item with given key or default.
Return a sorted array with the keys
Return a zipped list of keys and values.
Functions defined in module collection
To run pyFormex, simply enter the command pyformex in a terminal window. This will start the Graphical User Interface (GUI), from where you can launch examples or load, edit and run your own scripts.
The installation procedure may have installed into your desktop menu or even have created a start button in the desktop panel. These provide convenient shortcuts to start the GUI by the click of a mouse button.
The program takes some optional command line arguments, that modify the behaviour of the program. Appendix Command line options gives a full list of all options. For normal use however you will seldom need to use any of them. Therefore, we will only explain here the more commonly used ones.
By default, sends diagnostical and informational messages to the terminal from which the program was started. Sometimes this may be inconvenient, e.g. because the user has no access to the starting terminal. You can redirect these messages to the message window of the GUI by starting pyformex with the command pyformex --redirect. The desktop starters installed by the installation procedure use this option.
In some cases the user may want to use the mathematical power of without the GUI. This is e.g. useful to run complex automated procedures from a script file. For convenience, will automatically enter this batch mode (without GUI) if the name of a script file was specified on the command line; when a script file name is absent, start in GUI mode. Even when specifying a script file, You can still force the GUI mode by adding the option –gui to the command line.
The following is a complete list of the options for the pyformex command.This output can also be generated by the command pyformex --help.
Usage
=====
pyformex [<options>] [ [ scriptname [scriptargs] ] ...]
pyFormex is a tool for generating, manipulating and transforming large
geometrical models of 3D structures by sequences of mathematical
transformations.
Options
=======
--gui start the GUI (default if no scriptfile argument is
given)
--nogui do not load the GUI (default if a scriptfile argument
is given)
--interactive, -i Go into interactive mode after processing the command
line parameters. This is implied by the --gui option.
--force-dri Force use of Direct Rendering
--force-nodri Disables the Direct Rendering
--uselib Use the pyFormex C lib if available. This is the
default.
--nouselib Do not use the pyFormex C-lib.
--norst2html Do not try to convert rst messages to html before
displaying.
--config=CONFIG Use file CONFIG for settings
--nodefaultconfig Skip the default site and user config files. This
option can only be used in conjunction with the
--config option.
--redirect Redirect standard output to the message board (ignored
with --nogui)
--debug display debugging info to sys.stdout
--debuglevel=DEBUG display debugging info to sys.stdout
--newviewports Use the new multiple viewport canvas implementation.
This is an experimental feature only intended for
developers.
--testmodule=TESTMODULE
Run the docstring tests for module TESTMODULE.
TESTMODULE is the name of the module, using . as path
separator.
--testcamera Print camera settings whenever they change.
--testexecutor test alternate executor: only for developers!
--fastnurbs test C library nurbs drawing: only for developers!
--listfiles list the pyformex Python source files.
--search search the pyformex source for a specified pattern and
exit. This can optionally be followed by -- followed
by options for the grep command. The final argument is
the pattern to search.
--remove remove the pyformex installation and exit
--whereami show where the pyformex package is installed and exit
--detect show detected helper software and exit
--version show program's version number and exit
--help, -h show this help message and exit
If you start with the --nogui option, no Graphical User Interface is created. This is extremely useful to run automated scripts in batch mode. In this operating mode, will interprete all arguments remaining after interpreting the options, as filenames of scripts to be run (and possibly arguments to be interpreted by these scripts). Thus, if you want to run a script myscript.py in batch mode, just give the command pyformex myscript.py.
The running script has access to the remaining arguments in the global list variable argv. The script can use any arguments of it and pop them of the list. Any arguments remaining in the argv list when the script finishes, will be used for another execution cycle. This means that the first remaining argument should again be a script.
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program–to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers’ and authors’ protection, the GPL clearly explains that there is no warranty for this free software. For both users’ and authors’ sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users’ freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general- purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work’s System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work’s users, your or third parties’ legal rights to forbid circumvention of technological measures.
You may convey verbatim copies of the Program’s source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation’s users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party’s predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor’s “contributor version”.
A contributor’s “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor’s essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient’s use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
End of Terms and Conditions
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands show w and show c should show the appropriate parts of the General Public License. Of course, your program’s commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
Abstract
This document gives a short introduction on the BuMPix Live GNU/Linux system and how to use it to run pyFormex directly on nearly any computer system without having to install it.
Bumpix Live is a fully featured GNU/Linux system including pyFormex that can be run from a single removable medium such as a CD or a USB key. BuMPix is still an experimental project, but new versions are already produced at regular intervals. While those are primarily intended for our students, the install images are made available for download on the Bumpix Live GNU/Linux FTP server, so that anyone can use them.
All you need to use the Bumpix Live GNU/Linux is some proper PC hardware: the system boots and runs from the removable medium and leaves everything that is installed on the hard disk of the computer untouched.
Because the size of the image (since version 0.4) exceeds that of a CD, we no longer produce CD-images (.iso) by default, but some older images remain avaliable on the server. New (reduced) CD images will only be created on request. On the other hand, USB-sticks of 2GB and larger have become very affordable and most computers nowadays can boot from a USB stick. USB sticks are also far more easy to work with than CD’s: you can create a persistent partition where you can save your changes, while a CD can not be changed.
You can easily take your USB stick with you wherever you go, plug it into any available computer, and start or continue your previous pyFormex work. Some users even prefer this way to run pyFormex for that single reason. The Live system is also an excellent way to test and see what pyFormex can do for you, without having to install it. Or to demonstrate pyFormex to your friends or colleagues.
The numbering scheme of the BuMPix images is independent from the pyFormex numbering. Just pick the latest BuMPix image to get the most recent pyFormex available on USB stick. After you downloaded the .img file, write it to a USB stick as an image, not as file! Below, you find instructions on how to do this on a GNU/Linux system or on a Windows platform.
Warning
Make sure you’ve got the device designation correct, or you might end up overwriting your whole hard disk!
Also, be aware that the USB stick will no longer be usable to store your files under Windows.
If you have an existing GNU/Linux system available, you can write the downloaded image to the USB-stick using the command:
dd if=bumpix-VERSION.img of=USBDEV
where bumpix-VERSION.img is the downloaded file and USBDEV is the device corresponding to your USB key. This should be /dev/sda or /dev/sdb or, generally, /dev/sd? where ? is a single character from a-z. The value you should use depends on your hardware. You can find out the correct value by giving the command dmesg after you have plugged in the USB key. You will see messages mentioning the correct [sd?] device.
The dd command above will overwrite everything on the specified device, so copy your files off the stick before you start, and make sure you’ve got the device designation correct.
If you have no GNU/Linux machine available to create the USB key, there are ways to do this under Windows as well. We recommend to use dd for Windows. You can then proceed as follows.
Download dd for Windows to a folder, say C:\\download\ddWrite.
Download the latest BuMPix image to the same folder.
Mount the target USB stick and look for the number of the mounted USB. This can be done with the command c:\\download\ddWrite dd --list. Look at the description (Removable media) and the size to make sure you’ve got the correct harddisk designation (e.g. harddisk1).
Write the image to the USB stick with the command, substituting the harddisk designation found above:
dd if=c:\download\ddwrite\bumpix-0.4-b1.img of=\\?\device\harddisk1\partition0 bs=1M --progress
The dd command above will overwrite everything on the specified device, so copy your files off the stick before you start, and make sure you’ve got the device designation correct.
Alternatively,
you may be happy to know that we can provide ready-made BuMPix USB sticks with the pyformex.org logo at a cost hardly exceeding that of production and distribution. If you think this is the right choice for you, just email us for a quotation.
Once the image has been written, reboot your computer from the USB stick. You may have to change your BIOS settings or use the boot menu to do that. On success, you will have a full GNU/Linux system running, containing pyFormex ready to use. There is even a start button in the toolbar at the bottom.
Warning
More detailed documentation on how to use the system is currently under preparation. For now, feel free to email us if you have any problems or urgent questions. But first check that your question is not solved in the FAQ below.
A collection of hints and answers to frequently asked questions.
The initial user name is user and the password live.
On shutdown/reboot, the system pauses with the advice to remove the USB stick before hitting ENTER to proceed. We advice not to do this (especially when running in PERSISTENT mode): instead first hit ENTER and remove the USB stick when the screen goes black.
BuMPix 0.7.0 may contain a few user configuration files with incorrect owner settings. As a result some XFCE configuration may not be permanent. To solve the problem, you should run the following command in a terminal
sudo chown -R user:user /home/user
For BuMPix 0.7.0 (featuring pyFormex 0.8.4) with XFCE desktop, some users have reported occaional problems with starting the window manager. Windows remain undecorated and the mouse cursor keeps showing the BUSY symbol. This is probably caused by an improper previous shutdown and can be resolved as follows: open a terminal and enter the command xfwm4. That will start up the window manager for your current session and most likely will also remove the problem for your next sessions.
Install the latest pyFormex version from the SVN repository. The BuMPix stick contains a script pyformex-svn under the user’s bin directory to install a pyFormex version directly from the SVN repository. However, the repository has been relocated to a ne server and the script might still contain the old location. You can download a fixed script from ftp://bumps.ugent.be/pub/pyformex/pyformex-svn.
This describes how you can upgrade (or downgrade) the pyFormex version on your BuMPix 0.6.1 USB key. You need to have network connection to do this.
First, we need to fix some file ownerships. Open a Terminal and do the following
sudo -i
chown -R user:user /home/user
exit
Then, add your own bin directory to the PATH:
echo 'export PATH=~/bin:$PATH' >> ~/.bash_profile
Change the configuration of your teminal. Click Edit -> Profiles -> Edit -> Title and Command and check the option ‘Run command as a login shell’.
Close the terminal and open a new one. Check that the previous operation went correct:
echo $PATH
This should start with ‘/home/user/bin’. If ok, then do:
cd bin
chmod +x pyformex-svn
ls
You should now see a green ‘pyformex-svn’ script. Execute it as follows:
./pyformex-svn install makelib symlink
ls
If everything went well, you should now also have a blue ‘pyformex’ link. Test it:
cd ..
pyformex
The latest svn version of pyFormex should start. If ok, close it and you can make this the default version to start from the pyFormex button in the top panel. Right click on the button, then ‘Properties’. Change the Command to:
bin/pyformex --redirect
Now you should always have the updated pyformex running, from the command line as well as from the panel button. Next time you want to upgrade (or downgrade), you can just do:
cd pyformex-svn
svn up
or, for a downgrade, add a specific revision number:
svn up -r 1833
Date: | January 16, 2012 |
---|---|
Version: | 0.8.6 |
Author: | Benedict Verhegghe <benedict.verhegghe@ugent.be> |
Abstract
This chapter answers some frequently asked questions about pyFormex and present some nice tips to solve common problems. If you have some question that you want answered, or want to present a original solution to some problem, feel free to communicate it to us (by preference via the pyFormex Support tracker) and we’ll probably include it in the next version of this FAQ.
How was the pyFormex logo created?
We used the GNU Image Manipulation Program (GIMP). It has a wide variety of scripts to create logos. With newer versions (>= 2.6) use the menu Fille‣Create‣Logos‣Alien-neon. With older versions (<=2.4) use Xtra‣Script-Fu‣Logos‣Alien-neon.
In the Alien Neon dialog specify the following data:
Text: pyFormex
Font Size: 150
Font: Blippo-Heavy
Glow Color: 0xFF3366
Background Color: 0x000000
Width of Bands: 2
Width of Gaps: 2
Number of Bands: 7
Fade Away: Yes
Press OK to create the logo. Then switch off the background layer and save the image in PNG format. Export the image with Save Background Color option switched off!
How was the pyFormex favicon created? With FTGL, save as icon, handedited .xpm in emacs to set background color to None (transparent), then converted to .png and .ico with convert.
Why is pyFormex written in Python?
Because
Being a scripting language without the need for variable declaration, it allows for quick program development. On the other hand, Python provides numerous interfaces with established compiled libraries, so it can be surprisingly fast.
Is an interpreted language like Python fast enough with large data models?
See the question above.
Note
We should add something about NumPy and the pyFormex C-library.
Use your script path as the current working directory
Start your script with the following:
chdir(__file__)
When executing a script, pyFormex sets the name of the script file in a variable __file__ passed with the global variables to the execution environment of the script.
Import modules from your own script directories
In order for Python to find the modules in non-standard locations, you should add the directory path of the module to the sys.path variable.
A common example is a script that wants to import modules from the same directory where it is located. In that case you can just add the following two lines to the start of your script:
import os,sys
sys.path.insert(0,os.dirname(__file__))
Automatically load plugin menus on startup
Plugin menus can be loaded automatically on pyFormex startup, by adding a line to the [gui] section of your configuration file (~/.pyformexrc):
[gui]
plugins = ['surface_menu', 'formex_menu']
Automatically execute your own scripts on startup
If you create your own pugin menus for pyFormex, you cannot autoload them like the regular plugin menus from the distribution, because they are not in the plugin directory of the installation. Do not be tempted to put your own files under the installation directory (even if you can acquire the permissions to do so), because on removal or reinstall your files might be deleted! You can however automatically execute your own scripts by adding their full path names in the autorun variable of your configuration file
autorun = '/home/user/myscripts/startup/'
This script will then be run when the pyFormex GUI starts up. You can even specify a list of scripts, which will be executed in order. The autorun scripts are executed as any other pyFormex script, before any scripts specified on the command line, and before giving the input focus to the user.
Multiple viewports with unequal size
The multiple viewports are ordered in a grid layout, and you can specify relative sizes for the different columns and/or rows of viewports. You can use setColumnStretch and setRowStretch to give the columns a relative stretch compared toi the other ones. The following example produces 4 viewports in a 2x2 layout, with the right column(1) having double width of the left one(0), while the bottom row has a height equal to 1.5 times the height of the top row
layout(4)
pf.GUI.viewports.setColumnStretch(0,1)
pf.GUI.viewports.setColumnStretch(1,2)
pf.GUI.viewports.setRowStretch(0,2)
pf.GUI.viewports.setRowStretch(1,3)
Activate pyFormex debug messages from your script
import pyformex
pyformex.options.debug = True
Get a list of all available image formats
import gui.image
print image.imageFormats()
Create a movie from a sequence of recorded images
The multisave option allows you to easily record a series of images while working with pyFormex. You may want to turn this sequence into a movie afterwards. This can be done with the mencoder and/or ffmpeg programs. The internet provides comprehensive information on how to use these video encoders.
If you are looking for a quick answer, however, here are some of the commands we have often used to create movies.
Create MNPG movies from PNG To keep the quality of the PNG images in your movie, you should not encode them into a compressed format like MPEG. You can use the MPNG codec instead. Beware though that uncompressed encodings may lead to huge video files. Also, the MNPG is (though freely available), not installed by default on Windows machines.
Suppose you have images in files image-000.png, image-001.png, .... First, you should get the size of the images (they all should have the same size). The command
file image*.png
will tell you the size. Then create movie with the command
mencoder mf://image-*.png -mf w=796:h=516:fps=5:type=png -ovc copy -oac copy -o movie1.avi
Fill in the correct width(w) and height(h) of the images, and set the frame rate(fps). The result will be a movie movie1.avi.
Create a movie from (compressed) JPEG images. Because the compressed format saves a lot of space, this will be the prefered format if you have lots of image files. The quality of the compressed image movie will suffer somewhat, though.
ffmpeg -r 5 -b 800 -i image-%03d.jpg movie.mp4
Install the gl2ps extension
Note
This belongs in Installing pyFormex
Saving images in EPS format is done through the gl2ps library, which can be accessed from Python using wrapper functions. Recent versions of pyFormex come with an installation script that will also generate the required Python interface module.
Warning
The older python-gl2ps-1.1.2.tar.gz available from the web is no longer supported
You need to have the OpenGL header files installed in order to do this (on Debian: apt-get install libgl1-mesa-dev).
Permission denied error when running calpy simulation
If you have no write permission in your current working directory, running a calpy simulation will result in an error like this:
fil = file(self.tempfilename,'w')
IOError
:
[Errno 13] Permission denied: 'calpy.tmp.part-0'
You can fix this by changing your current working directory to a path where you have write permission (e.g. your home directory). You can do this using the File->Change workdir menu option. The setting will be saved when you leave pyFormex (but other scripts might change the setting again).
Reading back old Project (.pyf) files
When the implementation of some pyFormex class changes, or when the location of a module is changed, an error may result when trying to read back old Project (.pyf) files. While in principle it is possible to create the necessary interfaces to read back the old data and transform them to new ones, our current policy is to not do this by default for all classes and all changes. That would just require too much resources for maybe a few or no cases occurring. We do provide here some guidelines to help you with solving the problems yourself. And if you are not able to fix it, just file a support request at our Support tracker and we will try to help you.
If the problem is with a changed implementation of a class, it can usually be fixed by adding an appropriate __set_state__ method to the class. Currently we have this for Formex and Mesh classes. Look at the code in formex.py and mesh.py respectively.
If the problem comes from a relocation of a module (e.g. the mesh module was moved from plugins to the pyFormex core), you may get an error like this:
AttributeError: 'NoneType' object has no attribute 'Mesh'
The reason is that the path recorded in the Project file pointed to the old location of the mesh module under plugins while the mesh module is now in the top pyformex directory. This can be fixed in two ways:
The easy (but discouraged) way is to add a symbolic link in the old position, linking to the new one. We do not encourage to use this method, because it sustains the dependency on legacy versions.
The recommended way is to convert your Project file to point to the new path. To take care of the above relocation of the mesh module, you could e.g. use the following command to convert your old.pyf to a new.pyf that can be properly read. It just replaces the old module path (plugins.mesh) with the current path (mesh):
sed 's|plugins.mesh|mesh|'g old.pyf >new.pyf
Warning
This document still needs to be written!
Abstract
This chapter explains how to use projects to make your work persistent. We will explain how to create new projects, how to add or remove data from the project and how to save and reopen project files.
A pyFormex project is a persistent copy of some data created by pyFormex. These data are saved in a project file, which you can later re-open to import the data in another pyFormex session.
Warning
This document still needs some cleanup!
Sometimes you learn quicker from studying an example than from reading a tutorial or user guide. To help you we have created this collection of annotated examples. Beware that the script texts presented in this document may differ slightly from the corresponding example coming with the pyFormex distribution.
To get acquainted with the modus operandi of pyFormex, the WireStent.py script is studied step by step. The lines are numbered for easy referencing, but are not part of the script itself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | # $Id: WireStent.py 2146 2012-01-09 08:57:52Z bverheg $ *** pyformex ***
##
## This file is part of pyFormex 0.8.6 (Mon Jan 16 21:15:46 CET 2012)
## pyFormex is a tool for generating, manipulating and transforming 3D
## geometrical models by sequences of mathematical operations.
## Home page: http://pyformex.org
## Project page: http://savannah.nongnu.org/projects/pyformex/
## Copyright 2004-2011 (C) Benedict Verhegghe (benedict.verhegghe@ugent.be)
## Distributed under the GNU General Public License version 3 or later.
##
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see http://www.gnu.org/licenses/.
##
"""Wirestent.py
A pyFormex script to generate a geometrical model of a wire stent.
This version is for inclusion in the pyFormex documentation.
"""
from formex import *
class DoubleHelixStent:
"""Constructs a double helix wire stent.
A stent is a tubular shape such as used for opening obstructed
blood vessels. This stent is made frome sets of wires spiraling
in two directions.
The geometry is defined by the following parameters:
L : approximate length of the stent
De : external diameter of the stent
D : average stent diameter
d : wire diameter
be : pitch angle (degrees)
p : pitch
nx : number of wires in one spiral set
ny : number of modules in axial direction
ds : extra distance between the wires (default is 0.0 for
touching wires)
dz : maximal distance of wire center to average cilinder
nb : number of elements in a strut (a part of a wire between two
crossings), default 4
The stent is created around the z-axis.
By default, there will be connectors between the wires at each
crossing. They can be switched off in the constructor.
The returned formex has one set of wires with property 1, the
other with property 3. The connectors have property 2. The wire
set with property 1 is winding positively around the z-axis.
"""
def __init__(self,De,L,d,nx,be,ds=0.0,nb=4,connectors=True):
"""Create the Wire Stent."""
D = De - 2*d - ds
r = 0.5*D
dz = 0.5*(ds+d)
p = math.pi*D*tand(be)
nx = int(nx)
ny = int(round(nx*L/p)) # The actual length may differ a bit from L
# a single bumped strut, oriented along the x-axis
bump_z=lambda x: 1.-(x/nb)**2
base = Formex(pattern('1')).replic(nb,1.0).bump1(2,[0.,0.,dz],bump_z,0)
# scale back to size 1.
base = base.scale([1./nb,1./nb,1.])
# NE and SE directed struts
NE = base.shear(1,0,1.)
SE = base.reflect(2).shear(1,0,-1.)
NE.setProp(1)
SE.setProp(3)
# a unit cell of crossing struts
cell1 = (NE+SE).rosette(2,180)
# add a connector between first points of NE and SE
if connectors:
cell1 += Formex([[NE[0][0],SE[0][0]]],2)
# and create its mirror
cell2 = cell1.reflect(2)
# and move both to appropriate place
self.cell1 = cell1.translate([1.,1.,0.])
self.cell2 = cell2.translate([-1.,-1.,0.])
# the base pattern cell1+cell2 now has size [-2,-2]..[2,2]
# Create the full pattern by replication
dx = 4.
dy = 4.
F = (self.cell1+self.cell2).replic2(nx,ny,dx,dy)
# fold it into a cylinder
self.F = F.translate([0.,0.,r]).cylindrical(
dir=[2,0,1],scale=[1.,360./(nx*dx),p/nx/dy])
self.ny = ny
def all(self):
"""Return the Formex with all bar elements."""
return self.F
if __name__ == "draw":
# show an example
wireframe()
reset()
D = 10.
L = 80.
d = 0.2
n = 12
b = 30.
res = askItems([['Diameter',D],
['Length',L],
['WireDiam',d],
['NWires',n],
['Pitch',b]])
if not res:
exit()
D = float(res['Diameter'])
L = float(res['Length'])
d = float(res['WireDiam'])
n = int(res['NWires'])
if (n % 2) != 0:
warning('Number of wires must be even!')
exit()
b = float(res['Pitch'])
H = DoubleHelixStent(D,L,d,n,b).all()
clear()
draw(H,view='iso')
# and save it in a lot of graphics formats
if ack("Do you want to save this image (in lots of formats) ?"):
for ext in [ 'bmp', 'jpg', 'pbm', 'png', 'ppm', 'xbm', 'xpm',
'eps', 'ps', 'pdf', 'tex' ]:
image.save('WireStent.'+ext)
# End
|
As all pyFormex scripts, it starts with a comments line holding the word pyformex (line 1). This is followed more comments lines specifying the copyright and license notices. If you intend to distribute your scripts, you should give these certainly special consideration.
Next is a documentation string explaining the purpose of the script (lines 25-30). The script then starts by importing all definitions from other modules required to run the WireStent.py script (line 32).
Subsequently, the class DoubleHelixStent is defined which allows the simple use of the geometrical model in other scripts for e.g. parametric, optimization and finite element analyses of braided wire stents. Consequently, the latter scripts do not have to contain the wire stent geometry building and can be condensed and conveniently arranged. The definition of the class starts with a documentation string, explaining its aim and functioning (lines 34-60).
The constructor __init__ of the DoubleHelixStent class requires 8 arguments (line 61):
The virtual construction of the wire stent structure is defined by the following sequence of four operations: (i) Creation of a nearly planar base module of two crossing wires; (ii) Extending the base module with a mirrored and translated copy; (iii) Replicating the extended base module in both directions of the base plane; and (iv) Rolling the nearly planar grid into the cylindrical stent structure, which is easily parametric adaptable.
(lines 63-71)
Depending on the specified arguments in the constructor, the mean stent diameter
, the average stent radius
, the bump or curvature of the
wires
, the pitch
and the number of base modules in the
axial direction
are calculated with the following script. As the wire
stent structure is obtained by braiding, the wires have an undulating course and
the bump dz corresponds to the amplitude of the wave. If no extra distance
is specified, there will be exactly one wire diameter between the
centre lines of the crossing wires. The number of modules in the axial direction
is an integer, therefore, the actual length of the stent model might
differ slightly from the specified, desired length
. However, this
difference has a negligible impact on the numerical results.
Of now, all parameters to describe the stent geometry are specified and
available to start the construction of the wire stent. Initially a simple Formex
is created using the pattern()-function: a straigth line segment of length
1 oriented along the X-axis (East or -direction). The replic()-functionality replicates this line segment
times with step 1 in the
X-direction (
-direction). Subsequently, these
line
segments form a new Formex which is given a one-dimensional bump with the
bump1()-function. The Formex undergoes a deformation in the Z-direction
(
-direction), forced by the point [0,0,dz]. The bump
intensity is specified by the quadratic bump_z function and varies along the
X-axis (
-axis). The creation of this single bumped strut, oriented
along the X-axis is summarized in the next script and depicted in figures
A straight line segment, The line segment with replications and A bumped line segment,.
A straight line segment
The line segment with replications
A bumped line segment
The single bumped strut (base) is rescaled homothetically in the XY-plane to
size one with the scale()-function. Subsequently, the shear()-functionality generates a new NE Formex by skewing the base Formex in
the Y-direction (-direction) with a skew factor of
in
the YX-plane. As a result, the Y-coordinates of the base Formex are altered
according to the following rule:
. Similarly a
SE Formex is generated by a shear() operation on a mirrored copy of the
base Formex. The base copy, mirrored in the direction of the XY-plane
(perpendicular to the
-axis), is obtained by the reflect()
command. Both Formices are given a different property number by the
setProp()-function, visualised by the different color codes in Figure
Unit cell of crossing wires and connectors This number can be used as an entry in a database, which holds some
sort of property. The Formex and the database are two seperate entities, only
linked by the property numbers. The rosette()-function creates a unit cell
of crossing struts by
rotational replications with an angular step of
[180]:math:deg around the Z-axis (the original Formex is the first of the
replicas). If specified in the constructor, an additional Formex with
property
connects the first points of the NE and SE Formices.
(lines 72-83)
Rescaled bumped strut
Mirrored and skewed bumped strut
Unit cell of crossing wires and connectors
Subsequently, a mirrored copy of the base cell is generated (Figure Mirrored unit cell). Both Formices are translated to their appropriate side by side position with the translate()-option and form the complete extended base module with 4 by 4 dimensions as depicted in Figure Completed base module. Furthermore, both Formices are defined as an attribute of the DoubleHelixStent class by the self-statement, allowing their use after every DoubleHelixStent initialisation. Such further use is impossible with local variables, such as for example the NE and SE Formices.
(lines 84-89)
Mirrored unit cell
Completed base module
The fully nearly planar pattern is obtained by copying the base module in two
directions and shown in Figure Full planar topology. replic2() generates this
pattern with and
replications with steps
and
in respectively, the default X- and Y-direction.
(lines 90-93)
Full planar topology
Orthogonal view of the full planar topology
Finally the full pattern is translated over the stent radius in
Z-direction and transformed to the cylindrical stent structure by a coordinate
transformation with the Z-coordinates as distance
, the X-coordinates
as angle
and the Y-coordinates as height
. The
scale()-operator rescales the stent structure to the correct circumference
and length. The resulting stent geometry is depicted in Figure Cylindrical stent.
(lines 94-96)
In addition to the stent initialization, the DoubleHelixStent class script
contains a function all() representing the complete stent Formex.
Consequently, the DoubleHelixStent class has four attributes: the Formices
cell1, cell2 and all; and the number .
(lines 97-100)
Cylindrical stent
Orthogonal view of the cylindrical stent
An inherent feature of script-based modeling is the possibility of easily
generating lots of variations on the original geometry. This is a huge advantage
for parametric analyses and illustrated in figures
Stent variant with : these wire
stents are all created with the same script, but with other values of the
parameters ,
and
. As the script for building
the wire stent geometry is defined as a the DoubleHelixStent class in the
(WireStent.py) script, it can easily be imported for e.g. this purpose.
Stent variant with
Stent variant with
Stent variant with
Stent variant with
Stent variant with
Stent variant with
Stent variant with
Stent variant with
# $Id: WireStentParametricExample.py 2146 2012-01-09 08:57:52Z bverheg $ *** pyformex ***
##
## This file is part of pyFormex 0.8.6 (Mon Jan 16 21:15:46 CET 2012)
## pyFormex is a tool for generating, manipulating and transforming 3D
## geometrical models by sequences of mathematical operations.
## Home page: http://pyformex.org
## Project page: http://savannah.nongnu.org/projects/pyformex/
## Copyright 2004-2011 (C) Benedict Verhegghe (benedict.verhegghe@ugent.be)
## Distributed under the GNU General Public License version 3 or later.
##
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see http://www.gnu.org/licenses/.
##
from examples.WireStent import DoubleHelixStent
for De in [16.,32.]:
for nx in [6,10]:
for beta in [25,50]:
stent = DoubleHelixStent(De,40.,0.22,nx,beta).all()
draw(stent,view='iso')
pause()
clear()
Obviously, generating such parametric wire stent geometries with classical CAD methodologies is feasible, though probably (very) time consuming. However, as provides a multitude of features (such as parametric modeling, finite element pre- and postprocessing, optimization strategies, etcetera) in one single consistent environment, it appears to be the obvious way to go when studying the mechanical behavior of braided wire stents.
Besides being used for creating geometries, also offers interesting possibilities for executing specialized operations on surface meshes, usually STL type triangulated meshes originating from medical scan (CT) images. Some of the algorithms developed were included in .
A stent is a medical device used to reopen narrowed arteries. The vast majority of stents are balloon-expandable, which means that the metal structure is deployed by inflating a balloon, located inside the stent. Figure Triangulated mesh of a Cypher® stent shows an example of such a stent prior to expansion (balloon not shown). The 3D surface is obtained by micro CT and consists of triangles.
Triangulated mesh of a Cypher® stent
The structure of such a device can be quite complex and difficult to analyse. The same functions offers for creating geometries can also be employed to investigate triangulated meshes. A simple unroll operation of the stent gives a much better overview of the complete geometrical structure and allows easier analysis (see figure Result of the unroll operation).
F = F.toCylindrical().scale([1.,2*radius*pi/360,1.])
Result of the unroll operation
The unrolled geometry can then be used for further investigations. An important property of such a stent is the circumference of a single stent cell. The clip() method can be used to isolate a single stent cell. In order to obtain a line describing the stent cell, the function intersectionLinesWithPlane() has been used. The result can be seen in figures Part of the intersection with a plane.
Part of the intersection with a plane
Finally, one connected circumference of a stent cell is selected (figure Circumference of a stent cell) and the length() function returns its length, which is 9.19 mm.
Circumference of a stent cell
Date: | January 16, 2012 |
---|---|
Version: | 0.8.6 |
Author: | Benedict Verhegghe <benedict.verhegghe@ugent.be> |
Abstract
This document describes the native file formats used by pyFormex. The are currently two file formats: the pyFormex Project File (.pyf) and the pyFormex Geometry File (.pgf/.formex).
pyFormex uses two native file formats to save data on a persistent medium: the pyFormex Project File (.pyf) and the pyFormex Geometry File (.pgf).
A Project File can store any pyFormex data and is the prefered way to store your data for later reuse within pyFormex. The data in the resulting file can normally not be used by humans and can only be easily restored by pyFormex itself.
The pyFormex Geometry File on the other hand can be used to exchange data between pyFormex projects or with other software. Because of its plain text format, the data can be read and evend edited by humans. You may also wish to save data in this format to make them accessible the need for pyFormex, or to bridge incompatible changes in pyFormex.
Because the geometrical data in pyFormex can be quite voluminous, the format has been chosen so as to allow efficient read and write operations from inside pyFormex. If you want a nicer layout and efficiency is not your concern, you can used the fprint() method of the geometry object.
A pyFormex project file is just a pickled Python dictionary stored on file, possibly with compression. Any pyFormex objects can be exported and stored on the project file. The resulting file is normally not readable for humans and because all the class definitions of the exported data have to be present, the file can only be read back by pyFormex itself.
The format of the project file is therefore currently not further documented. See Using Projects for the use of project files from within pyFormex.
This describes the pyFormex Geometry File Format version 1.2 as drawn on 2010-01-04. The version numbering is such that implementations of a later version are able to read an older version with the same major numbering. Thus, the 1.2 version still can read version 1.0 and 1.1 files.
The prefered filename extension for pyFormex geometry files is ‘.pgf’, though this is not a requirement and the previously used ‘.formex’ is certainly as valid as any other.
The pyFormex Geometry File starts with a header line identify the file type and version, and possibly specifying some global variables:
# Formex File Format 1.1 (http://pyformex.org)
The remainder of the file contains one or more data blocks, each of which consists of a header line followed by the numerical data. The header line starts with a ‘#’. The remainder of the line is a sequence of ‘keyword=value’ strings separated with a semicolon and optional whitespace, such as in the following example:
# nelems=692; nplex=2; props=True; eltype=None; sep=' '
The keywords in the data header specify the type and amount of that that will be read, and how they will be structured in arrays and converted to pyFormex objects. The example above specifies a Formex of plexitude 2 having 692 elements with no specific element type but possessin property numbers. The separator used in the data is a single space.
Data blocks are written using numpy.tofile() and read back with numpy.fromfile(). All data items in a block are of the same type and are written as ASCII strings, separated by a constant string. The separator can be specified by the user and defaults to a single space, so that all data of a single block are written on one line, separated by a blank. When reading, newline characters will be silently ignored or used as a separator character as well. As a special case, if an empty string is specified as separator, the data will be written in binary mode.
Each data block is preceded with a comments line with the following structure:
Abstract
This chapter describes how to create plugins for and documents some of the standard plugins that come with the pyFormex distribution.
From its inception was intended to be easily expandable. Its open architecture allows educated users to change the behavior of and to extend its functionality in any way they want. There are no fixed rules to obey and there is no registrar to accept and/or validate the provided plugins. In , any set of functions that are not an essential part of can be called a ‘plugin’, if its functionality can usefully be called from elsewhere and if the source can be placed inside the distribution.
Thus, we distinct plugins from the vital parts of which comprehense the basic data types (Formex), the scripting facilities, the (OpenGL) drawing functionality and the graphical user interface. We also distinct plugins from normal (example and user) scripts because the latter will usually be intended to execute some specific task, while the former will often only provide some functionality without themselves performing some actions.
To clarify this distinction, plugins are located in a separate subdirectory plugins of the tree. This directory should not be used for anything else.
The extensions provided by the plugins usually fall within one of the following categories:
The next section of this chapter gives some recommendations on how to structure the plugins so that they work well with . The remainder of the chapter discusses some of the most important plugins included with .
This is the pyFormex 0.8.6 documentation, last updated on January 16, 2012.
These documents are to become a full documentation set for the installation and use of the pyFormex software. However, as pyFormex is still under active development, so is this documentation: it therefore is by no means final and complete; it does not even pretend to be accurate for any version of pyFormex.
However, since partial documentation is better than none, we decided to make this preliminary version available to the general public, to ease the use of pyFormex. The pyFormex reference manual is automatically generated from the docstrings in the Python source, so that might best reflect the latest development version of the software. The Introduction to pyFormex, Installing pyFormex, pyFormex tutorial are also fairly complete and useable. The pyFormex user guide and pyFormex example scripts are still in an embryonal state but may already contain valuable information for some users.
The new documentation is available in HTML format for interactive browsing. A PDF version of the full documentation set can be downloaded from our FTP server. From the pyFormex GUI, a local version of the HTML documentation may be accessible from the Help menu.