124. plugins.vtk_itf
— Interface with VTK.¶
This module provides an interface with some functions of the Python Visualization Toolkit (VTK). Documentation for VTK can be found on http://www.vtk.org/
This module provides the basic interface to convert data structures between VTK and pyFormex.
124.1. Functions defined in module plugins.vtk_itf¶
- plugins.vtk_itf.Update(vtkobj)[source]¶
Select Update method according to the vtk version. After version 5 Update is not needed for vtkObjects, only to vtkFilter and vtkAlgortythm classes.
Note that this applies only to vtkAlgorithm instances. In all other case the use of Update is kept. For this cases this function must not be used.
- plugins.vtk_itf.array2VTK(a, vtype=None)[source]¶
Convert a numpy array to a vtk array
Parameters:
a: numpy array nx2
- vtype: vtk output array type. If None the type is derived from
the numpy array type
- plugins.vtk_itf.array2N(a, ntype=None)[source]¶
Convert a vtk array to a numpy array
Parameters:
a: a vtk array
- ntype: numpy output array type. If None the type is derived from
the vtk array type
- plugins.vtk_itf.cleanVPD(vpd)[source]¶
Clean the vtkPolyData
Clean the vtkPolyData, adjusting connectivity, removing duplicate elements and coords, renumbering the connectivity. This is often needed after setting the vtkPolyData, to make the vtkPolyData fit for use with other operations. Be aware that this operation will change the order and numbering of the original data.
Parameters:
vpd: a vtkPolyData
Returns the cleaned vtkPolyData.
- plugins.vtk_itf.checkClean(mesh)[source]¶
Check if the mesh is fused, compacted and renumbered.
If mesh is not clean (fused, compacted and renumbered), vtkCleanPolyData() will clean it before writing a vtp file. This should be avoided because the pyformex points and arrays may no longer correspond to the vtk points.
- plugins.vtk_itf.elems2VTK(elems)[source]¶
Convert pyFormex class Connectivity into VTK class vtkCellArray
- plugins.vtk_itf.convert2VPD(M, clean=False)[source]¶
Convert pyFormex data to vtkPolyData.
Convert a pyFormex Mesh or Coords or open PolyLine object into vtkPolyData. This is limited to vertices, lines, and polygons.
Parameters:
M: a Coords or Mesh or open PolyLine. If M is a Coords type it will be saved as VERTS. Else…
clean: if True, the resulting vtkPolyData will be cleaned by calling cleanVPD.
If the Mesh has a prop array the properties are added as cell data array in an array called prop. This name should be protected from the user to allow to convert properties from/to the vtk interface.
Returns a vtkPolyData.
- plugins.vtk_itf.convert2VTU(M)[source]¶
Convert pyFormex Mesh to vtk unstructured grid.
Return a VTK unstructured grid (VTU) supports any element type and is therefore an equivalent of pyFormex class Mesh.
- plugins.vtk_itf.convertVPD2Triangles(vpd)[source]¶
Convert a vtkPolyData to a vtk triangular surface.
Convert a vtkPolyData to a vtk triangular surface. This is convenient when vtkPolyData are non-triangular polygons.
Parameters:
vpd: a vtkPolyData
Returns
- plugins.vtk_itf.coordsFromVTK(vtkpoints)[source]¶
Convert VTK class vtkPoints into pyFormex class Coords
- plugins.vtk_itf.convertFromVPD(vpd, samePlex=True)[source]¶
Convert a vtkPolyData into pyFormex objects.
Parameters:
vpd: a vtkPolyData
samePlex: True if you are sure that all lines and polys have the same element type
Returns:
a list with points, cells, polygons, lines, vertices numpy arrays if samePlex is True or pyFormex varray if samePlex is False.
fielddata: a dict of {name:fielddata_numpy_array}
celldata: a dict of {name:celldata_numpy_array}
pointdata: a dict of {name:pointdata_numpy_array}
Returns None for the missing arrays, empty dict for empty data.
- plugins.vtk_itf.writeVTP(fn, mesh, fielddata={}, celldata={}, pointdata={}, checkMesh=True, writernm=None)[source]¶
Write a Mesh in .vtp or .vtk file format.
fn: a filename with .vtp or .vtk extension.
mesh: a Mesh of level 0, 1 or 2 (and volume Mesh in case of .vtk)
fielddata: dictionary of arrays associated to the fields (?).
celldata: dictionary of arrays associated to the elements.
pointdata: dictionary of arrays associated to the points (renumbered).
checkMesh: bool: if True, raises a warning if mesh is not clean.
writernm: specify which vtk writer should be used. If None the writer is selected based on fn extension.
If the Mesh has property numbers, they are stored in a vtk array named prop. Additional arrays can be added and will be written as type double.
The user should take care that the mesh is already fused, compacted and renumbered. If not, these operations will be done by vtkCleanPolyData() and the points may no longer correspond to the point data arrays.
The .vtp or .vtk file can be viewed in paraview.
VTP format can contain
polygons: triangles, quads, etc.
lines
points
VTU format has been tested with
Mesh of type: point,line2,tri3,quad4,tet4,hex8
- plugins.vtk_itf.writeVTPmany(fn, items)[source]¶
Writes many objects in vtp or vtk file format.
item can be a list of items supported by convert2VPD (mesh of coords, line2, tri3 and quad4) or convert2VTU (mesh of coords, line2, tri3, quad4, tet4 and hex8).
This is experimental!
- plugins.vtk_itf.readVTKObject(fn, samePlex=True, readernm=None)[source]¶
Read a vtp/vtk file
Read a vtp/vtk file and return coords, list of elems, and a dict of arrays.
Parameters
fn: a filename with any vtk object extension (vtp or vtk for the moment).
Returns the same output of convertFomVPD:
a list with coords, cells, polygons, lines, vertices numpy arrays
fielddata: a dict of {name:fielddata_numpy_array}
celldata: a dict of {name:celldata_numpy_array}
pointdata: a dict of {name:pointdata_numpy_array}
Returns None for the missing data. The dictionary of arrays can include the elements ids (e.g. properties).
- plugins.vtk_itf.pointInsideObject(S, P, tol=0.0, check_surface=True)[source]¶
vtk function to test which of the points P are inside surface S
Test which of the points pts are inside the surface surf.
Parameters:
S: a TriSurface specifying a closed surface
P: a Coords (npts,3) specifying npts points
tol: a tolerance applied on matching float values
- check_surface: bool. A boolean flag to first check whether the surface is
a closed manifold. If True and the surface is not a closed manifold, all points will be marked outside. Note that if this check is not performed and the surface is not closed, the results are undefined.
Returns a bool array with True/False for points inside/outside the surface.
- plugins.vtk_itf.inside(surf, pts, tol='auto')[source]¶
Test which of the points pts are inside the surface surf.
Parameters:
surf: a TriSurface specifying a closed surface
pts: a Coords (npts,3) specifying npts points
tol: a tolerance applied on matching float values
Returns an integer array with the indices of the points that are inside the surface.
See also
gts_itf.inside()
for an equivalent and faster alternative.
- plugins.vtk_itf.intersectionWithLines(self, q, q2, method='line', atol=1e-05, closest=False, reorder=False)[source]¶
Compute the intersection of surf with lines.
Parameters:
self: Formex, Mesh or TriSurface
- q,`q2`: (…,3) shaped arrays of points, defining
a set of lines.
atol: tolerance
method: a string (line) defining if the line, is a full-line. Otherwise the provided segments are used for the intersections
closest: boolean. If True returns only the closest point to the first point of each segment.
reorder: boolean. If True reorder the points according to the the line order.
Returns:
a fused set of intersection points (Coords)
a (1,3) array with the indices of intersection point, line and triangle
- plugins.vtk_itf.convertTransform4x4FromVtk(transform)[source]¶
Convert a VTK transform to numpy array
Convert a vtk transformation instance vtkTrasmorm into a 4x4 transformation matrix array
- plugins.vtk_itf.convertTransform4x4ToVtk(trMat4x4)[source]¶
Convert a numpy array to a VTK transform
Convert a 4x4 transformation matrix array into a vtkTransform instance
- plugins.vtk_itf.transform(source, trMat4x4)[source]¶
Apply a 4x4 transformation
Apply a 4x4 transformation matrix array to source whcih can be a Geometry surface or Coords class.
Returns a copy of the source object with transformed coordinates
- plugins.vtk_itf.vtkCut(self, implicitdata, method=None)[source]¶
Cut (get intersection of) a Mesh with plane(s), a sphere or a box.
Parameters:
self: a Mesh (line2,tri3,quad4).
implicitdata: list or vtkImplicitFunction. If list it must contain the parameter for the predefined implicit functions:
method = ‘plane’: a point and normal vector defining the cutting plane.
method = ‘sphere’: center and radius defining a sphere.
method = ‘box’: either a 4x4 matrix to apply affine transformation (not yet implemented) or a box (cuboid) defined by 4 points, a Formex or a Mesh. See _vtkBox.
method = ‘boxplanes’: Coords, Mesh or Formex. Coords array of shape (2,3) specifying minimal and coordinates of the box. Formex or Mesh specifying one hexahedron. See _vtkPlanesBox.
method = ‘planes’: points array_like of shape (npoints,3) and normal vectors array_like of shape (npoints,3) defining the cutting planes.
method = ‘surface’: a closed convex manifold trisurface.
method: str or None. If string allowed values are ‘plane’, ‘sphere’, ‘box’, ‘boxplanes’, ‘planes’, ‘surface’ to select the correspondent implicit functions by providing the implicitdata parameters. If None a vtkImplicitFunction must be passed directly in implicitdata.
Cutting reduces the mesh dimension by one. Returns a mesh of points if self is a line2 mesh, a mesh of lines if self is a surface tri3 or quad4 mesh, a triangular mesh if self is tet4 or hex8 mesh. If there is no intersection returns None.
- plugins.vtk_itf.vtkClip(self, implicitdata, method=None, insideout=False)[source]¶
Clip (split) a Mesh with plane(s), a sphere or a box.
Parameters:
self: a Mesh.
- implicitdata: list or vtkImplicitFunction. If list it must contains the
parameter for the predefined implicit functions:
method = ‘plane’: a point and normal vector defining the cutting plane.
method = ‘sphere’: center and radius defining a sphere.
method = ‘box’: either a 4x4 matrix to apply affine transformation (not yet implemented) or a box (cuboid) defined by 4 points, a Formex or a Mesh. See _vtkBox.
method = ‘boxplanes’: Coords, Mesh or Formex. Coords array of shape (2,3) specifying minimal and coordinates of the box. Formex or Mesh specifying one hexahedron. See _vtkPlanesBox.
method = ‘planes’: points array_like of shape (npoints,3) and normal vectors array_like of shape (npoints,3) defining the cutting planes.
method = ‘surface’: a closed convex manifold trisurface.
method: str or None. If string allowed values are ‘plane’,’planes’, ‘sphere’, ‘box’ to select the correspondent implicit functions by providing the implicitdata parameters. If None a vtkImplicitFunction must be passed directly in implicitdata
insideout: boolean or an integer with values 0 or 1 to choose which side of the mesh should be returned.
Clipping does not reduce the mesh dimension. Returns always a list of meshes, each one having the same element type. None is returned if a mesh does not exist (e.g. clipping with a box which is outside the mesh). The mesh density can influence the clipping results, especially with solid elements. In this case the corner of the implicit function can be smoothed resulting in wrong clipping at these locations.
- plugins.vtk_itf.distance(self, ref, normals=None, loctol=0.001, normtol=1e-05, return_cellids=False)[source]¶
Computes the distance of object from a reference object ref
Parameters:
self: any pyFormex Geometry or Coords object.
ref: any pyFormex Geometry or Coords object.
normals: arraylike of shape (ncoords,3). Normals at each vertex of ref. If not specified, otherwise normals are computed using vtkPolyDataNormals.
loctol: float. Tolerance for the locator precision.
normtol: float. Tolerance for the signed distance vector.
return_cellids: boolean. If True an array containing the cell ids of the ref closest to each point of self
Returns a tuple with the distances, distance vectors, and signed distances.
- plugins.vtk_itf.meshQuality(self, measure)[source]¶
Compute the quality of the elements using a given metric.
Parameters:
self: a Geometry object.
measure: string defining the quality measure. This parameter needs to complete the vtk command with the correct capitalization.
For the allowed quality metrics check: http://www.vtk.org/doc/nightly/html/classvtkMeshQuality.html
Example:
>>> from pyformex.elements import Hex8 >>> h=Hex8.toMesh() >>> meshQuality(h,'MaxAspectFrobenius') array([ 1.])
- plugins.vtk_itf.octree(surf, tol=0.0, npts=1, return_levels=False)[source]¶
Compute the octree structure of the surface.
Returns the octree structure of surf according to the maximum tolerance tol and the maximum number of points npts in each octant. It returns an hexahedral mesh containing all levels of the octree with property equal to the number of point of the in each region. If return_levels is True, it also return a list of integer arrays containing the location of all the hehahedroons of each level.
- plugins.vtk_itf.delaunay2D(object, alpha=0.0, tol=0.001, offset=1.25, bound_tri=False, constraints=None)[source]¶
Constructs a 2D Delaunay triangulation from a Coords object or a Geometry.
Parameters:
object: Coords or Geometry (or subclasses).
alpha: float. Specify alpha (or distance) value to control output of this filter. If alpha == 0, the output is a convex hull. If non-zero alpha distance value is specified will give concave hull. (The notion of alpha value is derived from Edelsbrunner’s work on “alpha shapes”.)
tol: float. Specify a tolerance to control discarding of closely spaced points.
offset: float. Specify a multiplier to control the size of the initial, bounding Delaunay triangulation.
bound_tri: boolean. Boolean controls whether bounding triangulation points (and associated triangles) are included in the output.
constraints: Geometry (or subclasses). Specify the source object used to specify constrained edges and loops. If set, and lines/polygons are defined, a constrained triangulation is created. The lines/polygons are assumed to reference points in the input point set (i.e. point ids are identical in the input and source). Note that this method does not connect the pipeline. See SetSourceConnection for connecting the pipeline.
Returns a list of Geometry (or subclass).Usually the output is a triangle mesh, but if a non-zero alpha distance value is specified the utput may result in arbitrary combinations of triangles, lines, and vertices.
- plugins.vtk_itf.delaunay3D(object, alpha=0.0, tol=0.001, offset=2.5, bound_tri=False)[source]¶
Constructs a 3D Delaunay triangulation from a Coords object or a Geometry.
Parameters:
object: Coords or Geometry (or subclasses).
- alpha: float. Specify alpha (or distance) value to control output of this filter.
If alpha == 0, the output is a convex hull. If non-zero alpha distance value is specified will give concave hull.(The notion of alpha value is derived from Edelsbrunner’s work on “alpha shapes”.)
tol: float. Specify a tolerance to control discarding of closely spaced points.
offset: float. Specify a multiplier to control the size of the initial, bounding Delaunay triangulation.
bound_tri: boolean. Boolean controls whether bounding triangulation points (and associated triangles) are included in the output.
Returns a list of Geometry (or subclass). Usually the output is a tetrahedral mesh, but if a non-zero alpha distance value is specified the utput may result in arbitrary combinations of tetrahedrons, triangles, lines, and vertices.
- plugins.vtk_itf.decimate(self, targetReduction=0.5, boundaryVertexDeletion=True)[source]¶
Decimate a surface (both tri3 or quad4) and returns a trisurface
self: is a tri3 or quad4 surface
targetReduction: float (from 0.0 to 1.0): desired number of triangles relative to input number of triangles
boundaryVertexDeletion: bool: if True it allows boundary point deletion
- plugins.vtk_itf.coarsenPolyLine(self, target=0.5)[source]¶
Coarsen a PolyLine.
self: PolyLine
target: float in range [0.0,1.0], percentage of coords to be reduced.
Returns a PolyLine with a reduced number of points.
- plugins.vtk_itf.findElemContainingPoint(self, pts)[source]¶
Find indices of elements containing points.
Parameters:
self: a Mesh (point, line, surface or volume meshes)
pts: a Coords (npts,3) specifying npts points
This is experimental! Returns an integer array with the indices of the elems containing the points, returns -1 if no cell is found. Only one elem index per points is returned, which is probably the one with lower index number. VTK FindCell seems not having tolerance in python. However, the user could enlarge (unshrink) all elems. Docs on http://www.vtk.org/doc/nightly/html/classvtkAbstractCellLocator.html#a0c980b5fcf6adcfbf06932185e89defb
- plugins.vtk_itf.import3ds(fn, vtkcolor='color')[source]¶
Import an object from a .3ds file and returns a list of colored meshes.
It reads and converts a .3ds file into a list of colored meshes, by using vtk as intermediate step.
Parameters:
fn: filename (.3ds or .3DS)
vtkcolor: select which color to read from the vtk class: color or specular. The class vtkOpenGLProperty has multiple fields with colors.
Free 3D galleries are archive3d.net archibase.net