20. filewrite — Write geometry to file in a whole number of formats.

This module defines both the basic routines to write geometrical data to a file and the specialized exporters to write files in a number of well known standardized formats.

Most of the exporters support transparent compression of the output files by just specifying a file name that ends in ‘.gz’ or ‘.bz2’.

The basic routines are very versatile as well as optimized and allow to easily create new exporters for other formats.

20.1. Functions defined in module filewrite

filewrite.writePGF(filename, objects, sep=' ', mode='w', shortlines=False, **kargs)[source]

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.

Parameters
  • filename (path_like) – The name of the file to be written. Usually this has a suffix ‘.pgf’. If a ‘.gz’ or ‘.bz2’ is added, the file will be compressed with gzip or bzip2, respectively.

  • objects (object | list | dict) – One or more objects to be saved on the file. If it is a dictionary, the keys are saved in the file as the names of the objects. Objects that can not be exported to a pyFormex Geometry File are silently ignored.

  • mode ('w' | 'a') – The mode in which to open the file. The default ‘w’ will overwrite an existing file. Use ‘a’ to append to an existing file.

  • sep (str) – The string used to separate data. If set to an empty string, the data will be written in binary format and the resulting file will be smaller, but less portable.

  • **kargs – Extra keyword arguments are passed to write().

Returns

int – The number of objects that were written to the file.

Examples

>>> f = Path('test_filewrite.pgf')
>>> M = Mesh(eltype='quad4').convert('tri3-u')
>>> writePGF(f, M)
1
>>> print(f.read_text())
# pyFormex Geometry File (http://pyformex.org) version='2.1'; sep=' '
# objtype='Mesh'; ncoords=4; nelems=2; nplex=3; props=False; normals=False; color=None; sep=' '; name='test_filewrite-0'; eltype='tri3'
0.0 0.0 0.0 1.0 0.0 0.0 1.0 1.0 0.0 0.0 1.0 0.0
0 1 2 2 3 0

>>> f.remove()
filewrite.writeOFF(fn, mesh)[source]

Write a mesh of polygons to a file in OFF format.

Parameters
  • fn (path_like) – The output file name, commonly having a suffix ‘.off’. If the suffix ends on ‘.gz’ or ‘.bz2’, the file will transparently be compressed during writing.

  • mesh (Mesh) – The Mesh to write to the file.

Notes

See https://en.wikipedia.org/wiki/OFF_(file_format).

Examples

>>> f = Path('test_filewrite.off')
>>> M = Mesh(eltype='quad4').convert('tri3-u')
>>> writeOFF(f, M)
>>> print(f.read_text())
OFF
4 2 0
0.0 0.0 0.0
1.0 0.0 0.0
1.0 1.0 0.0
0.0 1.0 0.0
3 0 1 2
3 2 3 0

>>> f.remove()
filewrite.writeOBJ(fn, mesh, name=None)[source]

Write a mesh of polygons to a file in OBJ format.

Parameters
  • fn (path_like) – The output file name, commonly having a suffix ‘.obj’. If the suffix ends on ‘.gz’ or ‘.bz2’, the file will transparently be compressed during writing.

  • mesh (Mesh) – The Mesh to write to the file.

  • name (str, optional) – Name of the Mesh to be written into the file. If not provided None and the Mesh has an .attrib.name, that name will be used.

Notes

See https://en.wikipedia.org/wiki/OBJ_(file_format).

Examples

>>> f = Path('test_filewrite.obj')
>>> M = Mesh(eltype='quad4').convert('tri3-u')
>>> writeOBJ(f, M, name='test')
>>> print(f.read_text())
# OBJ file written by pyFormex ...
o test
v 0.0 0.0 0.0
v 1.0 0.0 0.0
v 1.0 1.0 0.0
v 0.0 1.0 0.0
f 1 2 3
f 3 4 1
# End

>>> f.remove()
filewrite.writePLY(fn, coords, faces=None, *, edges=False, comment=None, vcolor=None, fcolor=None, ecolor=None, binary=False)[source]

Write polygons to a file in PLY format.

Parameters
  • fn (path_like) – The output file name, commonly having a suffix ‘.ply’. If the suffix ends on ‘.gz’ or ‘.bz2’, the file will transparently be compressed during writing.

  • coords (coords_like | Mesh) – A float array (ncoords, 3) with the coordinates of all vertices. As a convenience, if a Mesh is specified, the coords and faces arguments are taken from the Mesh.coords and :Mesh.elems attributes.

  • faces (dict) – A dict where the keys are plexitudes (<= mplex) and the values are the Connectivity tables of all the polygons of the plexitude. This should not be provided if a Mesh was given as the coords argument.

  • comment (str, optional) – An extra comment to add in the file header.

  • binary (bool) – If True, a binary file is written. The default is ascii.

Notes

For PLY format, see https://en.wikipedia.org/wiki/PLY_(file_format)).

Examples

>>> f = Path('test_filewrite.ply')
>>> M = Mesh(eltype='quad4').convert('tri3-u')
>>> writePLY(f, M.coords, {3:M.elems}, comment='This is a test')
>>> print(f.read_text())
ply
format ascii 1.0
comment .ply file written by pyFormex ...
comment This is a test
element vertex 4
property float x
property float y
property float z
element face 2
property list int int vertex_indices
end_header
0.0 0.0 0.0
1.0 0.0 0.0
1.0 1.0 0.0
0.0 1.0 0.0
3 0 1 2
3 2 3 0

>>> f.remove()
filewrite.writeGTS(fn, surf)[source]

Write a TriSurface to a file in GTS format.

Parameters
  • fn (path_like) – The output file name, commonly having a suffix ‘.gts’. If the suffix ends on ‘.gz’ or ‘.bz2’, the file will transparently be compressed during writing.

  • surf (TriSurface) – The TriSurface to write to the file.

Examples

>>> f = Path('test_filewrite.gts')
>>> M = Mesh(eltype='quad4').convert('tri3-u')
>>> writeGTS(f, M.toSurface())
>>> print(f.read_text())
4 5 2
0.000000 0.000000 0.000000
1.000000 0.000000 0.000000
1.000000 1.000000 0.000000
0.000000 1.000000 0.000000
1 2
3 1
4 1
2 3
3 4
1 4 2
5 3 2
#GTS file written by pyFormex ...

>>> f.remove()
filewrite.writeSTL(fn, x, n=None, binary=False, color=None)[source]

Write a collection of triangles to an STL file.

Parameters
  • fn (path_like) – The output file name, commonly having a suffix ‘.stl’ or ‘.stla’ (for ascii output) or ‘.stlb’ (for binary output). If the suffix ends on ‘.gz’ or ‘.bz2’, the file will transparently be compressed during writing.

  • x (Coords | Formex) – A Coords or Formex with shape (ntriangles,3,3) holding the coordinates of the vertices of the triangles to write to the file.

  • n (Coords, optional) – A Coords with shape (ntriangles,3) holding the normal vectors to the triangles. If not specified, they will be calculated.

  • binary (bool) – If True, the output file format will be a binary STL. The default is an ascii STL.

  • color ((4,) int array) – An int array with 4 values in the range 0..255. These are the red, green, blue and alpha components of a single color for all the triangles. It will be stored in the header of a binary STL file.

Note

The color can only be used with a binary STL format, and is not recognized by all STL processing software.

Warning

The STL format stores a loose collection of triangles and does not include connectivity information between the triangles. Therefore the use of this format for intermediate storage is strongly discouraged, as many processing algorithms will need to build the connectivity information over and again, which may lead to different results depending on round-off errors. The STL format should only be used as a final export to e.g. visualisation methods or machining processes.

Examples

>>> f = Path('test_filewrite.stl')
>>> M = Mesh(eltype='quad4').convert('tri3-u')
>>> writeSTL(f, M.toFormex())
>>> print(f.read_text())
solid  Created by pyFormex ...
  facet normal 0.0 0.0 1.0
    outer loop
      vertex 0.0 0.0 0.0
      vertex 1.0 0.0 0.0
      vertex 1.0 1.0 0.0
    endloop
  endfacet
  facet normal 0.0 0.0 1.0
    outer loop
      vertex 1.0 1.0 0.0
      vertex 0.0 1.0 0.0
      vertex 0.0 0.0 0.0
    endloop
  endfacet
endsolid

>>> f.remove()
filewrite.writeData(fil, data, fmt=None, sep='', end='\n')[source]

Write an array of numerical data to an open file.

Parameters
  • fil (file_like) – The file to write the data to. It can be any object supporting the write(bytes) method, like a file opened in binary write mode.

  • data (array_like) – A numerical array of int or float type. For output, the array will be reshaped to a 2D array, keeping the length of the last axis.

  • fmt (str, optional) – A format string compatible with the array data type. If not provided, the data are written as a single block using numpy.tofile(). If provided, the format string should contain a valid format converter for a single data item. It may also contain the necessary spacing or separator. Examples are ‘%5i ‘ for int data and ‘%f,’ or ‘%10.3e’ for float data.

  • sep (str, optional) – A string to be used as separator between single items. Only used if fmt is provided and the file is written in ascii mode.

  • end (str, optional) – A string to be written at the end of the data block (if no fmt) or at the end of each row (with fmt). The default value is a newline character. Only used if fmt is provided and the file is written in ascii mode.

Examples

>>> i = np.eye(3)
>>> f = Path('test_filewrite.out')
>>> with f.open('wb') as fil:
...     writeData(fil,i,sep=' ')
>>> f.size
35
>>> print(f.read_text())
1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0
>>> with f.open('wb') as fil:
...     writeData(fil,i,fmt='%.4f',sep=' ')
>>> f.size
63
>>> print(f.read_text())
1.0000 0.0000 0.0000
0.0000 1.0000 0.0000
0.0000 0.0000 1.0000
>>> i = np.arange(24).reshape(2,3,4)
>>> with f.open('wb') as fil:
...     writeData(fil,i,fmt='%.4f',sep=' ')
>>> print(f.read_text())
0.0000 1.0000 2.0000 3.0000
4.0000 5.0000 6.0000 7.0000
8.0000 9.0000 10.0000 11.0000
12.0000 13.0000 14.0000 15.0000
16.0000 17.0000 18.0000 19.0000
20.0000 21.0000 22.0000 23.0000
>>> f.remove()
filewrite.writeIData(fil, data, fmt, ind=1, sep=' ', end='\n')[source]

Write an indexed array of numerical data to an open file.

Parameters
  • fil (file_like) – The file to write the data to. It can be any object supporting the write(bytes) method, like a file opened in binary write mode.

  • data (array_like) – A numerical array of int or float type. For output, the array will be reshaped to a 2D array, keeping the length of the last axis.

  • fmt (str) – A format string compatible with the array data type. The format string should contain a valid format converter for a a single data item. It may also contain the necessary spacing or separator. Examples are ‘%5i ‘ for int data and ‘%f,’ or ‘%10.3e’ for float data.

  • ind (int or int array_like) – The row indices to write with the data. If an array, its length should be equal to the numbe of rows in the (2D-reshaped) data array. If a single int, it specifies the index for the first row, and the value will be automatically incremented for the other rows.

  • sep (str, optional) – A string to be used as separator between single items.

  • end (str, optional) – A string to be written at the end of the data block (if no fmt) or at the end of each row (with fmt). The default value is a newline character.

Examples

>>> i = np.eye(3)
>>> f = Path('test_filewrite.out')
>>> with f.open('wb') as fil:
...     writeIData(fil,i,fmt='%.4f',sep=' ')
>>> f.size
72
>>> print(f.read_text())
1  1.0000 0.0000 0.0000
2  0.0000 1.0000 0.0000
3  0.0000 0.0000 1.0000
>>> f.remove()
filewrite.writeText(fil, text)[source]

Write text to a file opened in text or binary mode

text can be either str or bytes. If not matching the open mode, text is encoded to/decoded from utf-8

filewrite.write_stl_asc(fil, x)[source]

Write a collection of triangles to an ascii .stl file.

Note

This is a low level routine for use in writeSTL. It is not intended to be used directly.

Parameters
  • fil (file_like) – The file to write the data to. It can be any object supporting the write(bytes) method, like a file opened in binary write mode.

  • x ((ntri,4,3) float array) – Array with 1 normal and 3 vertices and 1 normal per triangle.

filewrite.write_stl_bin(fil, x, color=None)[source]

Write a binary stl.

Note

This is a low level routine for use in writeSTL. It is not intended to be used directly.

Parameters
  • fil (file_like) – The file to write the data to. It can be any object supporting the write(bytes) method, like a file opened in binary write mode.

  • x ((ntri,4,3) float array) – Array with 1 normal and 3 vertices and 1 normal per triangle.

  • color ((4,) int array, optional) – Four color components in the range 0..255: red, green, blue and alpha. If specified, these will be stored in the header and may be recognized by some other software.

Examples

>>> f = Path('test_filewrite.stl')
>>> M = Mesh(eltype='quad4').convert('tri3-u')
>>> writeSTL(f, M.toFormex().coords, binary=True, color=[255,0,0,128])
>>> from .fileread import readSTL
>>> x, n, c = readSTL(f)
>>> print(x)
[[[0.  0.  0.]
  [1.  0.  0.]
  [1.  1.  0.]]

 [[1.  1.  0.]
  [0.  1.  0.]
  [0.  0.  0.]]]
>>> print(n)
[[0.  0.  1.]
 [0.  0.  1.]]
>>> print(c)
(1.0, 0.0, 0.0)
>>> f.remove()