polytex.io

Module contents

class polytex.io.save_krig(*args, **kwargs)[source]

Bases: dict

This class saves a dictonary of sympy expressions to a file in human readable form and then load as sympy expressions directly without other conversion. It is called by polytex.io.pk_save to save kriging expressions to a “.krig” file and by polytex.io.pk_load to load these files. Therefore, the class is not intended to be used directly by the user.

Notes

This class is taken from: https://github.com/sympy/sympy/issues/7974. A bug in exec() is fixed and some modifications are made to make it fit for the purpose of this project (store the kriging expression).

Examples

>>> import sympy
>>> from polytex.io import save_krig
>>> a, b = sympy.symbols('a, b')
>>> d = save_krig({'a':a, 'b':b})
>>> d.save('name.krig')
>>> del d
>>> d2 = save_krig.load('name.krig')

Methods

clear()

copy()

fromkeys(iterable[, value])

Create a new dictionary with keys from iterable and values set to value.

get(key[, default])

Return the value for key if key is in the dictionary, else default.

items()

keys()

pop(key[, default])

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem(/)

Remove and return a (key, value) pair as a 2-tuple.

setdefault(key[, default])

Insert key with a value of default if key is not in the dictionary.

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()

load

save

classmethod load(file_path)[source]
save(file)[source]
polytex.io.case_prepare(output_dir)[source]

Load openFoam case template and prepare the case for simulation.

Parameters
output_dirstr

The output directory where the 0 and constant folders are located.

Returns
None.
polytex.io.cell_faces(mesh, ind, neighbor=False)[source]

Get all faces of a 3D cell.

Parameters
meshvtkUnstructuredGrid

The volume mesh.

indint

The cell id.

neighborbool, optional

If True, return the neighbor cell ids. The default is False.

Returns
faceslist

A list containing all faces of the cell.

neighborslist

A list containing all neighbor cell ids of the cell. Not returned if neighbor is False.

polytex.io.choose_directory(titl='Select the target directory:')[source]

Choose a directory with GUI and return its path.

Parameters
titl: String.

The title of the open folder dialog window.

Returns
path: String.

The path of the selected directory.

polytex.io.choose_file(titl='Select the target directory:', format='csv')[source]

Choose a file with GUI and return its path.

Parameters
titl: String.

The title of the window.

Returns
path: String.

The path of the file.

polytex.io.coo_to_ply(file_coo, file_ply, interpolate=False, threshold=0.1)[source]

Convert a pcd file to ply file.

Parameters
file_coostr

The path of the coo file or pathlib.Path. File or filename to which the data is saved.

file_plystr

The path of the ply file or pathlib.Path. File or filename to which the data is to be saved.

interpolatebool, optional

Whether to interpolate the points. The default is False.

thresholdfloat, optional

The threshold of the normalized distance between the neighboring points. The default is 0.1.

Returns
None
polytex.io.create_material_data_lines(matname, rho, e, nu, sta, condition=True, materials=None)[source]

Creates lines for defining material data in the input file.

Parameters
matnamestr

Name of the material.

rhofloat

Density of the material.

efloat

Young’s modulus of the material.

nufloat

Poisson’s ratio of the material.

staint

Material state variable.

conditionbool

Condition for material type (default is True).

materials: list

List to store material data lines (default is None).

Returns
datalineslist

A list of lines for material data.

polytex.io.create_part_data_lines(prtname, nodes=[], elements=[], nodesets=[], elemsets=[])[source]

Creates lines for defining nodes, elements, and sets in the part data.

Parameters
prtnamestr

Name of the part.

nodeslist

Node data. Each node is a list containing the node label and the x, y, and z coordinates. The number of nodes can be obtained using the len() function.

elementslist

Element data. Each element is a list containing the element label and the node labels.

nodesetslist

Node sets containing the node labels.

elemsetslist

Element sets containing the element labels.

Returns
lineslist

List of lines for the part data.

polytex.io.create_solid_section_for_all_sets(Indices, fiber_material_name, orientation_name=None, controls='')[source]

Creates solid section lines for all fiber element sets in the mesh.

Parameters
Indices: int

The indices of matrix and fiber.

fiber_material_namestr

The name of the fiber material.

orientation_namestr

The name of the orientation (default is None for the matrix).

controlsstr

Control parameters for the section (default is an empty string).

Returns
lineslist

A list of lines for defining solid section properties for all fiber element sets.

polytex.io.create_solid_section_lines(elset_name, material_name, orientation_name=None, controls='')[source]

Creates lines for defining the solid section properties of a specified element set and material.

Parameters
elset_namestr

The name of the element set.

material_namestr

The name of the material.

orientation_namestr

The name of the orientation (default is None for the matrix).

controlsstr

Control parameters for the section (default is an empty string).

Returns
lineslist

A list containing lines for defining the solid section properties.

polytex.io.create_yarn_element_sets(mesh, file_handle, Indices, verbose=False)[source]

Creates element sets for each unique fiber in the mesh.

Parameters
meshpyvista.PolyData

The input mesh.

file_handlefile

The file handle to write element set lines.

Indices: int

The indices of matrix and fiber.

Returns
element_setsdict

Dictionary of element sets with the set name as the key and the lines as the value.

polytex.io.cwd_chdir(path='')[source]

Set given directory or the folder where the code file is as current working directory

Parameters
path:

the path of current working directory. if empty, the path of the code file is used.

Returns
cwd: the current working directory.
polytex.io.filenames(path, filter='csv')[source]

Get the list of files in the given folder.

Parameters
path:

the path of the folder

filter:

filter for file selection.++

Returns
flst: the list of files in the given folder.
polytex.io.get_boundary_faces(volume)[source]

Extract boundary faces from a vtkUnstructuredGrid object.

Parameters
volumepyvista.UnstructuredGrid

The volume mesh.

Returns
boundary_facesnumpy.ndarray

A numpy array containing all boundary faces.

surfpyvista.PolyData

A pyvista surface mesh object.

polytex.io.get_internel_faces(volume)[source]

Extract internel faces from a vtkUnstructuredGrid object.

Parameters
volumepyvista.UnstructuredGrid

The volume mesh.

Returns
internal_faceslist

A list containing all internal faces.

ownerlist

A list containing all owner cell ids corresponding to the internal faces.

neighbourlist

A list containing all neighbour cell ids corresponding to the internal faces.

polytex.io.get_ply_property(mesh_path, column, skip=11, type='vertex', save_vtk=False)[source]

This function get a vertex property or cell property from a mesh stored as .ply format. It is intended to be used to get the user-defined properties that most of meshing and rendering software does not support.

Parameters
mesh_pathstr

The path of the mesh file with .ply extension.

columnint or list of int

The column number of the property.

skipint, optional

The number of lines to skip in the header. The default is 11.

typestr, optional

The type of the property. The default is “vertex” for vertex property. The other possible value is “cell” for cell property.

save_vtkbool, optional

If True, the mesh is saved as a vtk file. The default is False.

Returns
propertynumpy.ndarray

The property of the mesh.

Notes

The mesh must be saved as ASCII format.

Examples

>>> import polytex as pk
>>> mesh_path = "./weft_0_lin_lin_krig_30pts.ply"
>>> quality = ptx.get_ply_property(mesh_path, -2, skip=11, type="vertex", save_vtk=False)
>>> quality
polytex.io.meshio_save(file, vertices, cells=[], point_data={}, cell_data={}, binary=False)[source]

Save surface mesh as a mesh file by definition of vertices and faces. Point data and cell data can be added. It is a wrapper of meshio.write() function.

Parameters
filestr

The path of the ply file or pathlib.Path. File or filename to which the data is saved.

verticesnumpy.ndarray

The vertices of the mesh. The shape of the array is (n, 3), where n is the number of vertices.

cellslist, optional

The faces of the mesh stored as the connectivity between vertices. The default is [].

point_datadict, optional

The point data of the mesh. The default is {}.

cell_datadict, optional

The cell data of the mesh. The default is {}. Note that the cell data should be added as a list of arrays. Each array in the list corresponds to a cell type. For example, if the mesh has 2 triangles and 1 quad, namely, cells = [(“triangle”, [0, 1, 2], [1,2,3]), (“quad”, [3, 4, 5, 6])], then the cell data should be added as cell_data = {“data”: [[1, 2], [3]}.

binarybool, optional

If True, the data is written in binary format. The default is False.

Returns
None.

Examples

>>> import numpy as np
>>> import polytex as pk
>>> vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]])
>>> cells = [("triangle", [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]])]
>>> point_data = {"a": np.array([0, 1, 2, 3])}
>>> cell_data = {"b": np.array([[0, 1, 2, 3],])}
>>> ptx.meshio_save("test.ply", vertices, cells, point_data, cell_data)
>>> print("Done")
Done
polytex.io.mkdir(path)[source]

Create the output directory if it does not exist.

Parameters
path: str

The path of the output directory.

Returns
output_dir: str

The path of the output directory.

polytex.io.pcd_to_ply(file_pcd, file_ply, binary=False)[source]

Convert a pcd file to ply file.

Parameters
file_pcdstr

The path of the pcd file or pathlib.Path. File or filename to which the data is saved.

file_plystr

The path of the ply file or pathlib.Path. File or filename to which the data is to be saved.

binarybool, optional

TODO

Returns
None
polytex.io.pk_load(file)[source]

Load a file format defined in polytex (.coo, .geo, or .stat) file and return as a pandas dataframe or a numpy.array object.

Parameters
file: str, or pathlib.Path.

File path and name to which the data is stored.

Returns
df: pandas.DataFrame or numpy.ndarray

The data to be loaded. It is a pandas dataframe if the file is a .coo/geo file. Otherwise, it is a numpy array or dict and a warning will be raised.

polytex.io.pk_save(fp, data, check_format=True)[source]

Save a Python dict or pandas dataframe as a file format defined in polytex (.coo, geo) file

Parameters
fp: str

File path and name to which the data is saved. If the file name does not end with a supported file extension, a ValueError will be raised.

data: Tow, Tex, or dict

The data to be saved. It can be several customised file formats for polytex.

Returns
None
polytex.io.read_explicit_data(filename, type='zip', sort=True, resolution=1.0, max_pts=100, verbose=False)[source]

Read ROI data from csv files exported from manual segmentation in ImageJ/FIJI. See https://www.binyang.fun/manual-segmentation-in-imagej-fiji/ for more details.

Parameters
filenamestr

The path of the roi file. The file should be either a zip of csv files or a directory containing multiple csv files. Each csv file contains the coordinates of the segmented points on a slice. see https://www.binyang.fun/manual-segmentation-in-imagej-fiji/ for more details. The parameter “type” should be set accordingly (“zip” or “dir”).

typestr, optional

The type of saved file. The default is “zip”. The other option is “dir”.

sortbool, optional

Whether to sort the coordinates according to the slice number. The default is True. Note that the coordinates on the same slice are not sorted. The sorting is only applied to the slices.

resolutionfloat, optional

The resolution of the image. The default is 1.0, the coordinates are not converted to the physical coordinates (namely the unit is pixel).

max_ptsint, optional

The maximum number of points on each slice. The default is 100. If the number of points on a slice is larger than max_pts, the points will be uniformly sampled to max_pts (approximately).

Returns
surf_pointsnumpy.ndarray

The coordinates of the segmented points on the surface of the tow in shape (N, 3), where N is the total number of points.

polytex.io.read_imagej_roi(filename, type='zip', sort=True, resolution=1.0, max_pts=100, verbose=False)[source]
polytex.io.save(file, arr, allow_pickle=True, fix_imports=True)[source]

This is an exact copy of numpy.save, except that it does not check the extensions.

Parameters
filefile, str, or pathlib.Path. File or filename to which the data is saved.
arrarray_like. Array data to be saved.
allow_picklebool, optional

Allow saving object arrays using Python pickles. Reasons for disallowing pickles include security (loading pickled data can execute arbitrary code) and portability (pickled objects may not be loadable on different Python installations, for example if the stored objects require libraries that are not available, and not all pickled data is compatible between Python 2 and Python 3). Default: True

fix_importsbool, optional

Only useful in forcing objects in object arrays on Python 3 to be pickled in a Python 2 compatible way. If fix_imports is True, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2.

polytex.io.save_csv(filename, dataset, csv_head)[source]

Save numpy array to csv file with given info in the first row.

Parameters
filename:

The path and name of the csv file.

dataset: List or numpy.ndarray

The dataset to be saved in the csv file

csv_head:

A list of headers of the csv file. The length of the list should be the same as the number of columns in the dataset.

Returns
None.
polytex.io.save_nrrd(cell_label, file_name, file_path='./')[source]

Save the labels of a hexahedral mesh to a nrrd file. The labels should be starting from 0 and increasing by 1.

Parameters
cell_label: numpy array(int, int, int)

The cell label of the mesh.

file_name: String

The name of the .nrrd file.

file_path: String

The save path of the .nrrd file.

Returns
None
polytex.io.save_ply(file, vertices, cells=[], point_data={}, cell_data={}, binary=False)[source]
polytex.io.texgen_voxel(mesh, rf, perm_model='Gebart', fiber_packing='Hex', plot=False, scalar='YarnIndex', progress_bar=True)[source]

Read the vtu voxel mesh exported from TexGen and calculate necessary information for OpenFOAM polyMesh conversion.

Parameters
meshpyvista.DataSet

The voxel mesh exported from TexGen.

rffloat

The fiber radius (m).

perm_modelstr, optional

The yarn permeability model. The default is “Gebart”.

fiber_packingstr, optional

The fiber packing pattern used for yarn permeability calculation. The default is “Hex”. Valid options are “Quad” and “Hex”.

plotbool, optional

If True, plot the mesh. The default is False.

scalarstr, optional

The scalar to plot. The default is “YarnIndex”.

Returns
meshpyvista.UnstructuredGrid

The voxel mesh with the new data.

polytex.io.voxel2foam(mesh, scale=1, outputDir='./', boundary_type=None, cell_data_list=None) None[source]

Convert a voxel mesh to OpenFOAM mesh. The cell data is converted to OpenFOAM initial conditions and saved in the 0 timestep folder.

Parameters
meshpyvista.UnstructuredGrid or pyvista.DataSet

The voxel mesh.

scalefloat, optional

The scale factor to convert the unit of points. The default is 1.0.

outputDirstr, optional

The output directory. The default is ‘./’.

boundary_typedict, optional

The type of each boundary. The default is None. If None, the type of the boundary is set as “patch”. The key is the boundary name and the value is the boundary type. The key should be the same as the face_boundary_dict.

The boundary type can be “patch”, “wall”, “empty”, “symmetryPlane”, “wedge”, “cyclic”, etc. See OpenFOAM user guide for more details.

cell_data_listlist, optional

A list containing the names of the cell data to be written. The default is None.

Returns
None.
polytex.io.voxel2img(mesh, mesh_shape, dataset='YarnIndex', save_path='./img/', scale=None, img_name='img', format='tif', scale_algrithm='linear')[source]

Convert a voxel mesh to a series of images.

Parameters
meshpyvista.UnstructuredGrid

The voxel mesh to convert.

mesh_shapelist

The number of cells in each direction of the mesh [nx, ny, nz].

datasetstr, optional

The name of the cell data to convert. The default is “YarnIndex”.

save_pathstr, optional

The path to save the images. The default is “./img/”.

scaleint

The scale factor of the image. The default is None.

img_namestr, optional

The name of the output image. The default is “img”. The slice number will be added to the end of the name and separated by an underscore.

formatstr, optional

The format of the output image. The default is “tif”.

scale_algrithmstr, optional

The algorithm used to scale the pixel numbers of the image. The default is “linear”. The other option is “spline”.

TODO: The “spline” algorithm is only working for x and y directions yet.

The z direction is to be implemented.

Returns
None

Examples

>>> import pyvista as pv
>>> import polytex as ptx
>>> mesh = pv.read("./v2i.vtu")
>>> mesh_shape = [20, 20, 5]
>>> ptx.io.voxel2img(mesh, mesh_shape, dataset="YarnIndex",
                    save_path="./img/",
                    scale=50, img_name="img", format="tif",
                    scale_algrithm="linear")
polytex.io.voxel2inp(mesh, scale=1, outputDir='./mesh-C3D8R.inp', orientation=True) None[source]

Convert a voxel mesh to an Abaqus input file.

Parameters
meshpyvista.UnstructuredGrid

The voxel mesh.

scalefloat, optional

The scale factor to convert the unit of points. The default is 1.0.

outputDirstr, optional

The output directory and filename. The default is ‘./mesh-C3D8R.inp’. The file extension is automatically added if not provided.

Returns
None.

Notes

voxel2inp is developed by Chao Yang (yangchaogg@whut.edu.cn) & Bin Yang (bin.yang@polymtl.ca) jointly. Please contact us if you have any questions.

polytex.io.write_FoamFile(ver, fmt, cls, location, obj, top_separator)[source]
polytex.io.write_boundary(face_boundary_dict, start_face, output_dir='./constant/polyMesh/', type=None)[source]

Boundary file writing.

Parameters
face_boundary_dictdict

A dict contains boundary category. The key is the boundary name and the value is a numpy array containing all boundary face node indices. The boundary name should be the same as the boundary patch name in the boundary file.

start_faceint

The start face index of the boundary faces. equal to the number of internal faces.

output_dirstr, optional

The output directory. The default is ‘./constant/polyMesh/’.

typedict, optional

The type of each boundary. The default is None. If None, the type of the boundary is set as “patch”. The key is the boundary name and the value is the boundary type. The key should be the same as the face_boundary_dict.

The boundary type can be “patch”, “wall”, “empty”, “symmetryPlane”, “wedge”, “cyclic”, etc. See OpenFOAM user guide for more details.

Returns
None.
polytex.io.write_cell_data(cellDataDict, outputDir='./0/', array_list=None)[source]

Write cell data to OpenFOAM format

Parameters
cellDataDictdict

A dictionary to store all cell data sets in vtu file using the data set name as key.

outputDirstr, optional

The directory to store the converted data. The default is ‘./0/’.

array_listlist, optional

A list containing the names of the cell data to be written. The default is None,

polytex.io.write_cell_zone(cell_zone, output_dir='./constant/polyMesh/')[source]

Write the cells to a file for porous properties setting.

Parameters
cell_zonedict

A dict containing all cell ids corresponding to the cell zones. The key is the cell zone name and the value (a list) is the cell ids in the zone.

output_dirstr, optional

The output directory. The default is ‘./constant/polyMesh/’.

Returns
None.
polytex.io.write_face(face_points)[source]
Parameters
face_pointslist

A list containing all face node indices.

polytex.io.write_faces(internal_faces, face_boundary, output_dir='./constant/polyMesh/')[source]

Write the faces file.

Parameters
internal_faceslist

A list containing all internal face node indices.

face_boundarydict

A dict containing all boundary faces. The key is the boundary patch name, and the value is a numpy array containing all boundary face node indices.

output_dirstr, optional

The output directory. The default is ‘./constant/polyMesh/’.

Returns
None.
polytex.io.write_fiber_orientation_to_file(mesh, Indices, file_header='', output_file='fabrictest.ori')[source]

Writes fiber orientation information to a file.

Parameters
mesh: pyvista.PolyData

The input mesh.

Indices: int

The indices of matrix and fiber.

file_header: str

The header lines for the ori file (default is ‘’).

output_file: str

The output file path for writing fiber orientation information (default is ‘fabrictest.ori’).

Returns
None
polytex.io.write_neighbors(neighbour, output_dir='./constant/polyMesh/')[source]

Write the neighbors file.

Parameters
neighbourlist

A list containing all neighbor cell ids corresponding to the internal faces.

output_dirstr, optional

The output directory. The default is ‘./constant/polyMesh/’.

Returns
None.
polytex.io.write_owner(owner_internal, owner_boundary, output_dir='./constant/polyMesh/')[source]

Write the owner file.

Parameters
owner_internalarray-like

A list containing all owner cell ids corresponding to the internal faces.

owner_boundarydict

A list containing all owner cell ids corresponding to the boundary faces.

output_dirstr, optional

The output directory. The default is ‘./constant/polyMesh/’.

Returns
None.
polytex.io.write_points(points, output_dir='./constant/polyMesh/', scale=1.0)[source]

Write points to OpenFOAM format

Parameters
pointsarray-like

The points to be written. The shape of the array should be (n, 3).

output_dirstr, optional

The directory to store the converted data. The default is ‘./’, which means the current directory.

scalefloat, optional

The scale factor to convert the unit of points. The default is 1.0.

Returns
: int

1 if the writing is successful.

polytex.io.zip_files(directory, file_list, filename, remove='True')[source]

Add multiple files to a zip file.

Parameters
directory: String.

The directory of the files to be added to zip file. Therefore, all the files in the file_list should be in the same directory.

file_listList.

The list of file names to be added to the zip file (without directory).

filename: String.

The name of the zip file. The zip file is saved in the same directory

remove:

Whether to remove original files after adding to zip file. Default is True. If False, the original files will not be removed.

Returns
None.