Classes

Textile objects

class polytex.textile.Textile(name='textile')[source]

Bases: object

Initialize the textile object.

Attributes
bounds

Bounding box of the textile.

items

Return tow names as a list.

n_tows

Number of tows in the textile.

Methods

add_group([name, tow])

Groups of the tows in the textile.

add_tow(tow[, group])

Add a tow to the textile.

case_prepare([path])

Prepare a case for OpenFOAM simulation.

cell_labeling([surface_mesh, intersection, ...])

Label the cells of the background mesh with tow id.

decimate()

Decimate the mesh.

export_as_inp([fp, scale, orientation])

Export the textile mesh as inp file for Abaqus simulation.

export_as_openfoam(fp[, scale, ...])

Export the textile mesh as polyMesh folder for OpenFOAM simulation.

export_as_vtu(fp[, binary])

Export the textile mesh as a vtu file.

from_file(path)

Load a textile object from a file.

meshing(bbox[, voxel_size, show, labeling, ...])

Generate a mesh for the textile.

reconstruct()

Reconstruct the textile object from the saved file.

remove(tow)

Remove a tow from the textile.

save([path, filename, data_size])

Save the textile object to a file.

triangulate()

Hexahedral mesh to tetrahedral mesh.

add_group(name='group1', tow=None)[source]

Groups of the tows in the textile. Each is a group of Tow objects. if tow is None, then the group is empty.

Parameters
namestr

Name of the group.

towTow object

Tow to be added to the group. If tow is None, then the group is empty. If tow is not None, then tow is added to the group. Besides, if tow is not in the self.__tows__ yet, it will be added to self.__tows__.

Returns
None.
add_tow(tow, group=None)[source]

Add a tow to the textile. If tow is already in the textile, then raise a ValueError.

Parameters
towTow object

Tow to be added to the textile. Stored in self.__tows__ as a dictionary. Tow.name is the key, and tow is the value.

groupstr

Group name of the tow. If group is None, then the tow is not added to any group. Stored in self.groups.

Returns
None.
case_prepare(path=None)[source]

Prepare a case for OpenFOAM simulation.

Parameters
pathstr

Path of the case to be prepared. The default is None. If path is None, it is set to the root directory of the OpenFOAM mesh generated by Textile.export_as_openfoam().

Returns
None.
noindex
cell_labeling(surface_mesh=None, intersection=False, check_surface=False, yarn_permeability='Gebart', threshold=1, verbose=False)[source]

Label the cells of the background mesh with tow id.

Parameters
surface_meshpyvista mesh object (PolyData)

Surface mesh of fiber tows. If None, then the surface meshes is selected user interactively. Otherwise, the surface mesh is loaded from the path specified by surface_mesh.

intersectionbool, optional

Whether to detect the intersection of the tows. The default is False.

check_surfacebool, optional

Whether to check if the surface mesh is watertight. The default is False.

yarn_permeabilitystr, optional

The permeability model used to calculate the permeability tensor of the fiber tow. The default is “Gebart”. The available permeability models are “Gebart”, “CaiBerdichevsky”, and “DrummondTahir”.

thresholdfloat, optional

The tolerance for the fiber tow section detection. The default is 1. A wavy fiber tow may have several intersections with the plane of a cross-section. The threshold is used to determine if the cells is correctly labelled.

verbosebool, optional

Whether to print the information. The default is False.

Returns
None.

Notes

Please make sure that the name of the tow (tow.name) is in the format of towType_towNumber.

decimate()[source]

Decimate the mesh.

export_as_inp(fp='./mesh-C3D8R.inp', scale=1, orientation=True)[source]

Export the textile mesh as inp file for Abaqus simulation.

Parameters
fpstr

The file path and filename of the output mesh. The default is “./mesh-C3D8R.inp”.

scalefloat, optional

The scale factor of the mesh. To convert the mesh from mm to m, the scale factor should be 0.001. The default is 1.

orientationbool, optional

Whether to export the orientation of the yarns. The default is True.

Returns
None.
export_as_openfoam(fp, scale=1, boundary_type=None, cell_data=['yarnIndex', 'D'])[source]

Export the textile mesh as polyMesh folder for OpenFOAM simulation.

The structure of the output case folder is:

 fp/ textile.name/
├── 0          
│   ├── D
│   ├── yarnIndex
│   └── ...       
└── constant          
      ├── polyMesh
      │   ├── boundary
      │   ├── faces
      │   ├── neighbour
      │   ├── owner 
      │   ├── points
      │   ├── ... 
      └── ...     
Parameters
fpstr

The file path of the output mesh.

scalefloat, optional

The scale factor of the mesh. To convert the mesh from mm to m, the scale factor should be 0.001. The default is 1.

boundary_typedict, optional

The boundary type of the mesh. The default is None. If None, the boundary type will be set as “wall” for all boundaries.

cell_datalist, optional

The cell data to be written into the mesh. The default is [“yarnIndex”, “D”].

Returns
None.
export_as_vtu(fp, binary=True)[source]

Export the textile mesh as a vtu file.

Parameters
fpstr

The file path of the output mesh.

binarybool, optional

Whether to save the mesh in binary format. The default is True.

Returns
None.
classmethod from_file(path)[source]

Load a textile object from a file.

Parameters
pathstr

Path of the file to be loaded.

Returns
Textile object.
meshing(bbox, voxel_size=None, show=False, labeling=False, yarn_permeability='Gebart', surface_mesh=None, verbose=False)[source]

Generate a mesh for the textile.

Parameters
bboxnumpy.ndarray

bounding box of the background mesh specified through a numpy array contains the minimum and maximum coordinates of the bounding box [xmin, xmax, ymin, ymax, zmin, zmax]

voxel_sizefloat, or numpy.ndarray

voxel size of the background mesh. if None, the voxel size is set to the 1/20 of the diagonal length of the bounding box; if float, the voxel size is set to the float value in x, y, z directions; if list, set, or tuple of size 3, the voxel size is set to the values for the x-, y- and z- directions.

showbool, optional

Whether to show the mesh. The default is False.

labelingbool, optional

Whether to label the background mesh cells with tow id. The default is True.

yarn_permeabilitystr, optional

The permeability model used to calculate the permeability tensor of the fiber tow. The default is “Gebart”. The available permeability models are “Gebart”, “CaiBerdichevsky”, and “DrummondTahir”.

surface_meshstr, optional

Path of the surface meshes of fiber tows. The default is None. If labeling=True, then the surface meshes are loaded from the path specified by surface_mesh. The surface meshes are used to label the background mesh cells with tow id. If surface_mesh is None, then the surface meshes are selected by the user interactively. TODO : Use the surface mesh generated by the tow object.

Returns
None.
reconstruct()[source]

Reconstruct the textile object from the saved file. The saved file must be in the format of “.tex” and loaded by the pk_load function.

Parameters
None.
Returns
None.
noindex
remove(tow)[source]

Remove a tow from the textile.

Parameters
towstr or Tow object

The tow to be removed.

Returns
None.
save(path=None, filename=None, data_size='minimal')[source]

Save the textile object to a file.

Parameters
pathstr, optional

Path of the file to be saved. The default is None. If path is None, then the user is asked to select the directory to save the file.

filenamestr, optional

Filename of the file to be saved. The default is None. If filename is None, then the filename is set to the textile name with extension “.tex”.

data_sizestr, optional

Size of the data to be saved. The default is “minimal”. If data_size is “minimal”, then only the minimal information of the textile that can be used to reconstruct the textile object is saved. If data_size is “full”, then all information of the textile is saved.

Returns
None.

Notes

TODOmore storage can be saved. The Textile and Tow classes should be designed carefully

at next version.

triangulate()[source]

Hexahedral mesh to tetrahedral mesh. Conformal meshing.

property bounds

Bounding box of the textile.

property items

Return tow names as a list. The tow names are reordered by the tow number if the tow name is in the format of “towType_towNumber”. Otherwise, the tow names are ordered according to the order of adding the tows to the textile.

property n_tows

Number of tows in the textile.

class polytex.tow.Tow(surf_points, order, rho_fiber, radius_fiber, length_scale, tex, name='Tow', packing_fiber='Hex', sort=True, resolution=None, **kwargs)[source]

Bases: object

Parameters
surf_pointsstr, ndarray or DataFrame

The surface points of the tow should be an array of shape (n, 3) where n is the number of points. The points are extracted from volumetric images slice by slice. Please always put the column that indicates the slice number as the last column. It serves as the label for differentiate the points from different slices.

If surf_points is a string, it should be the path to the file that stores the surface points. The file should be a .pcd file as defined in the PolyTex library.

If surf_points is a numpy array, it should be an array of shape (n, 3) where n is the number of points.

If surf_points is a pandas DataFrame, it should be a DataFrame with 3 columns and n rows where n is the number of points.

orderstr

It is preferred to set the last column of the surf_points as the coordinate in the direction that is perpendicular to the image slices for geometry analysis, parametrization and kriging resampling. Hence, you may have reordered the columns. Here, you can specify the order of the columns in the reordered points. Default is “xyz”. The other options are “xzy”, “yxz”, “yzx”, “zxy”, “zyx”. This function will recover the original order of the columns when generating the surface mesh.

rho_fiberfloat, optional

The density of the fiber in kg/m^3.

radius_fiberfloat, optional

The radius of the fiber in m.

length_scalestr, optional

The length scale of the coordinates. Default is “mm”. The other options are “m”, “cm”, “um”.

texfloat, optional

The linear density of the tow in tex.

namestr, optional

The name or type of the tow. Default is “Tow”.

packing_fiberstr, optional

The packing pattern of the fiber. Default is “Hex”. The other option is “Square”.

sortbool, optional

Whether to sort the points according to the slice number. Default is True.

resolutionfloat, optional

The resolution of the MicroCT image used to generate the tow dataset. Default is None. This is only stored as an attribute for future use. It is not used in the current version.

kwargsdict

The keyword arguments for the PolyTex Tow class. The user can specify any keyword arguments for the Tow class. The keyword arguments will be stored as attributes of the Tow class. The user can access the attributes by tow.attribute_name.

Attributes
attribute_names

Get the attribute names of the Tow class.

Methods

axial_lines([save_path, plot])

Generate the axial line of the fiber tow surface.

from_file(path)

Initialize the tow from a saved tow file.

kde([bw, save_path])

Generate the kernel density estimation of the radial normalized distance for point cloud decomposition.

normal_cross_section([algorithm, save_path, ...])

Generate the normal cross section of the fiber tow surface.

radial_lines([save_path, plot, type])

Generate the radial line of the fiber tow surface.

resampling([krig_config, skip, ...])

Kriging the cross-sections of the tow to obtain the parametric equations for each cross-section (which is a closed curve).

save(save_path)

Save the fiber tow data.

smooth_window(size, h_res[, extend])

The window size of smoothing operation.

smoothing([name_drift, name_cov, ...])

Smooth the tow using parametric surface kriging.

surf_mesh([plot, save_path, end_closed])

Generate the surface mesh of the tow.

trajectory([krig_config, smooth, plot, ...])

Generate the trajectory of the tow and smooth it using kriging.

unit_vector(vector[, ax])

Returns the unit vector of the input vector along the given axis.

mw_kde

axial_lines(save_path=None, plot=True)[source]

Generate the axial line of the fiber tow surface.

Parameters
save_pathstr, optional

The path to save the axial line data as a vtk mesh file.

plotbool, optional

Whether to plot the axial line. Default is True.

Returns
axial_linevtkPolyData

The axial lines of the fiber tow.

classmethod from_file(path)[source]

Initialize the tow from a saved tow file.

Parameters
pathstr

The path to the saved tow file. The file format is .tow.

Returns
towTow

The Tow object.

kde(bw=None, save_path=None)[source]

Generate the kernel density estimation of the radial normalized distance for point cloud decomposition.

Parameters
bwfloat, optional

The bandwidth of the kernel density estimation. Default is None and the bandwidth will be estimated using the Scott’s rule of thumb (one-fifth of the estimated value).

save_pathstr, optional

The path to save the kernel density estimation. Default is None. If None, the kernel density estimation will not be saved. The file format is .stat and can be loaded by the function polytex.pk_load.

Returns
clustersdict
normal_cross_section(algorithm='kriging', save_path=None, plot=True, i_size=0.7, j_size=1, skip=10, max_dist=2)[source]

Generate the normal cross section of the fiber tow surface.

Parameters
algorithmstr, optional

The algorithm to generate the cross section. Default is “kriging”. The other option is “pyvista” which uses pyvista’s mesh clip function (Polydata.clip_surface()).

save_pathstr, optional

The path to save the normal cross sections as a vtk mesh file.

plotbool, optional

Whether to plot the normal cross sections. Default is True.

i_sizefloat, optional

The size of the i direction of the noraml plane. Default is 0.7.

j_sizefloat, optional

The size of the j direction of the noraml plane. Default is 1.

skipint, optional

The number of cross sections to skip in plot. Default is 10. If skip is 1, all cross sections will be plotted.

Returns
cross_sectionpyvista.PolyData

The normal cross section of the fiber tows stored in a pyvista.PolyData object. Note that only the cross sections that are plotted are stored. If one wants to save all the cross sections, set skip=1.

planespyvista.PolyData

The corresponding planes that the cross sections are generated from. Note that only the planes that are plotted are stored. If one wants to save all the planes, set skip=1.

radial_lines(save_path=None, plot=True, type='resampled')[source]

Generate the radial line of the fiber tow surface.

Parameters
save_pathstr, optional

The path to save the radial line data as a vtk mesh file.

plotbool, optional

Whether to plot the radial line. Default is True.

typestr, optional

The type of radial line. Default is “resampled”. The other option is “original”.

Returns
radial_linevtkPolyData

The radial lines of the fiber tow.

resampling(krig_config=('lin', 'cub'), skip=5, sample_position=[], smooth=0, type='distance')[source]

Kriging the cross-sections of the tow to obtain the parametric equations for each cross-section (which is a closed curve).

Parameters
krig_configtuple, optional

The kriging configuration. The first element is the kriging model for the drift and the second is the name of covariance. Default is (“lin”, “cub”).

skipint, optional

The number of cross-sections to be skipped for resampling to accelerate the operation. Default is 5. Namely, 1 of every 5 cross-sections will be resampled. If skip is 1, all the cross-sections will be kriged.

sample_positionarray_like, optional

The resampling positions of each cross-sections specified by the normalized distance in radial direction of each cross-section. Default is [].

smoothfloat, optional

The smoothing parameter for the kriging resampling. Default is 0. Also known as the nugget effect in geo-statistics and kriging theory.

typestr, optional

The type of the kriging resampling. Default is “distance”. The other option is “angular”. If “distance”, the resampling positions are specified by the normalized distance (between 0 and 1) in radial direction of each cross-section. If “angular”, the resampling positions are specified by angular position (between 0 and 360) of control points in radial direction of each cross-section.

Returns
_Tow__kriged_verticesndarray

The kriged points for each cross-section of the tow. It is an array of shape (n, 3) where n is the number of points. The kriged points is obtained according to the kriging configuration and the resampling positions. If the resampling positions are not specified, the kriged points are obtained by evenly sampling the cross-sections with a sampling interval of 0.05, namely, 20 points per cross- section.

exprdict
The kriging expression for each cross-section. It contains two sub-dictionaries that

use the cross-section number as the key and the kriging expression as the value for the first two components of user input.

save(save_path)[source]

Save the fiber tow data.

Parameters
save_pathstr

The path to save the fiber tow data.

smooth_window(size, h_res, extend=2)[source]

The window size of smoothing operation. The window size is the number of slices in the axial direction of fiber tow that are smoothed per iteration.

A smaller window size will significantly decrease the computation time of smoothing operation.

Parameters
sizeint

The window size.

h_resint

The number of slices in the axial direction of fiber tow.

extendint, optional

The number of slices that are extended to the left and right of the smoothing window to ensure the smoothness of the surface at the boundary of the windows.

Returns
wins_interpndarray

The window size for interpolation (with extensions at the two ends).

wins_resultndarray

The index of effective smoothing results (without extensions).

smoothing(name_drift=['lin', 'lin'], name_cov=['cub', 'cub'], smooth_factor=[0, 0], size=25, save_path=None, plot=False)[source]

Smooth the tow using parametric surface kriging. Anisotropic smoothing is applied to the tow by using different smoothing factors for the two directions.

Parameters
name_driftlist, optional

The drift function for the parametric surface kriging. Default is [‘lin’, ‘lin’].

name_covlist, optional

The covariance function for the parametric surface kriging. Default is [‘cub’, ‘cub’].

smooth_factorlist, optional

The smoothing factor for the parametric surface kriging. Default is [0, 0]. Also known as the nugget effect in geo-statistics and kriging theory. The smoothing factor is applied to the two directions separately. The first element is the smoothing factor for the radial direction and the second element is the smoothing factor for the axial direction.

sizeint, optional

# TODO : improve the description The size of the window for the moving average filter. Default is 25.

save_pathstr, optional

The path to save the smoothed tow. Default is None. If None, the smoothed tow will not be saved. The file format is .ply.

plotbool, optional

Whether to plot the smoothed tow. Default is False.

Returns
verticesndarray

The smoothed tow vertices.

surf_mesh(plot=False, save_path=None, end_closed=False)[source]

Generate the surface mesh of the tow.

Parameters
plotbool, optional

Whether to plot the surface mesh. Default is False.

save_pathstr, optional

The path to save the surface mesh. Default is None and the surface mesh will not be saved. The file format can be .ply or .vtk.

Returns
——-
surf_mesh

The surface mesh of the tow.

trajectory(krig_config=('lin', 'cub'), smooth=0.0, plot=False, save_path=None, orientation=False)[source]

Generate the trajectory of the tow and smooth it using kriging.

Parameters
krig_configtuple, optional

The kriging configuration for the trajectory. It is a tuple of two strings that specify the drift and covariance function. Default is (“lin”, “cub”).

smoothfloat, optional

The smoothing parameter for the parametric curve kriging. Default is 0. Also known as the nugget effect in geo-statistics and kriging theory.

plotbool, optional

Whether to plot the trajectory. Default is False.

save_pathstr, optional

The path to save the trajectory as vtk file. Default is None and the trajectory will not be saved.

orientationbool, optional

Whether to calculate the orientation of the tow. Default is False. The orientation is the tangent vector of the trajectory.

Returns
trajnp.ndarray

The trajectory of the tow in the form of (n, 3) where n is the number of points.

unit_vector(vector, ax=1)[source]

Returns the unit vector of the input vector along the given axis.

Parameters
vectorndarray

The input vector.

axint, optional

The axis along which the unit vector is calculated. Default is 1 (column).

Returns
unit_vectorndarray

The unit vector of the input vector along the given axis.

property attribute_names

Get the attribute names of the Tow class.

Returns
attribute_nameslist

The attribute names of the Tow class.

Primitive geometries

class polytex.geometry.basic.Point(orig_3d=(0, 0, 0))[source]

Bases: ndarray

Default constructor. If no arguments are given, the point is initialized to (0, 0, 0).

Parameters
clsclass

The class of the object.

orig_3dtuple, list, or array_like

Defaults to 3d origin (0, 0, 0).

Returns
objPoint

The origin point of 3d space.

Examples

>>> p1 = Point()
>>> p1
Point([0, 0, 0])
Attributes
T

The transposed array.

base

Base object if memory is from some other object.

bounds

Returns ——- bounds : array_like The bounding box of the point.

ctypes

An object to simplify the interaction of the array with the ctypes module.

data

Python buffer object pointing to the start of the array’s data.

dtype

Data-type of the array’s elements.

flags

Information about the memory layout of the array.

flat

A 1-D iterator over the array.

imag

The imaginary part of the array.

itemsize

Length of one array element in bytes.

nbytes

Total bytes consumed by the elements of the array.

ndim

Number of array dimensions.

real

The real part of the array.

shape

Tuple of array dimensions.

size

Number of elements in the array.

strides

Tuple of bytes to step in each dimension when traversing an array.

x
xyz
y
z

Return —— z : float 3rd dimension element.

Methods

all([axis, out, keepdims, where])

Returns True if all elements evaluate to True.

any([axis, out, keepdims, where])

Returns True if any of the elements of a evaluate to True.

argmax([axis, out, keepdims])

Return indices of the maximum values along the given axis.

argmin([axis, out, keepdims])

Return indices of the minimum values along the given axis.

argpartition(kth[, axis, kind, order])

Returns the indices that would partition this array.

argsort([axis, kind, order])

Returns the indices that would sort this array.

astype(dtype[, order, casting, subok, copy])

Copy of the array, cast to a specified type.

byteswap([inplace])

Swap the bytes of the array elements

choose(choices[, out, mode])

Use an index array to construct a new array from a set of choices.

clip([min, max, out])

Return an array whose values are limited to [min, max].

compress(condition[, axis, out])

Return selected slices of this array along given axis.

conj()

Complex-conjugate all elements.

conjugate()

Return the complex conjugate, element-wise.

copy([order])

Return a copy of the array.

cumprod([axis, dtype, out])

Return the cumulative product of the elements along the given axis.

cumsum([axis, dtype, out])

Return the cumulative sum of the elements along the given axis.

diagonal([offset, axis1, axis2])

Return specified diagonals.

direction_ratio(other)

Gives the direction ratio between 2 points.

dist(other)

Both points must have the same dimensions :return: Euclidean distance

dump(file)

Dump a pickle of the array to the specified file.

dumps()

Returns the pickle of the array as a string.

fill(value)

Fill the array with a scalar value.

flatten([order])

Return a copy of the array collapsed into one dimension.

getfield(dtype[, offset])

Returns a field of the given array as a certain type.

item(*args)

Copy an element of an array to a standard Python scalar and return it.

itemset(*args)

Insert scalar into an array (scalar is cast to array's dtype, if possible)

max([axis, out, keepdims, initial, where])

Return the maximum along a given axis.

mean([axis, dtype, out, keepdims, where])

Returns the average of the array elements along given axis.

min([axis, out, keepdims, initial, where])

Return the minimum along a given axis.

newbyteorder([new_order])

Return the array with the same data viewed with a different byte order.

nonzero()

Return the indices of the elements that are non-zero.

partition(kth[, axis, kind, order])

Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.

prod([axis, dtype, out, keepdims, initial, ...])

Return the product of the array elements over the given axis

ptp([axis, out, keepdims])

Peak to peak (maximum - minimum) value along a given axis.

put(indices, values[, mode])

Set a.flat[n] = values[n] for all n in indices.

ravel([order])

Return a flattened array.

repeat(repeats[, axis])

Repeat elements of an array.

reshape(shape[, order])

Returns an array containing the same data with a new shape.

resize(new_shape[, refcheck])

Change shape and size of array in-place.

round([decimals, out])

Return a with each element rounded to the given number of decimals.

save_as_vtk(filename[, color])

Save the point as a vtk file.

searchsorted(v[, side, sorter])

Find indices where elements of v should be inserted in a to maintain order.

setfield(val, dtype[, offset])

Put a value into a specified place in a field defined by a data-type.

setflags([write, align, uic])

Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.

sort([axis, kind, order])

Sort an array in-place.

squeeze([axis])

Remove axes of length one from a.

std([axis, dtype, out, ddof, keepdims, where])

Returns the standard deviation of the array elements along given axis.

sum([axis, dtype, out, keepdims, initial, where])

Return the sum of the array elements over the given axis.

swapaxes(axis1, axis2)

Return a view of the array with axis1 and axis2 interchanged.

take(indices[, axis, out, mode])

Return an array formed from the elements of a at the given indices.

tobytes([order])

Construct Python bytes containing the raw data bytes in the array.

tofile(fid[, sep, format])

Write array to a file as text or binary (default).

tolist()

Return the array as an a.ndim-levels deep nested list of Python scalars.

tostring([order])

A compatibility alias for tobytes, with exactly the same behavior.

trace([offset, axis1, axis2, dtype, out])

Return the sum along diagonals of the array.

transpose(*axes)

Returns a view of the array with axes transposed.

var([axis, dtype, out, ddof, keepdims, where])

Returns the variance of the array elements, along given axis.

view([dtype][, type])

New view of array with the same data.

dot

set_x

set_y

set_z

direction_ratio(other)[source]

Gives the direction ratio between 2 points.

Parameters
otherPoint object

The other point to which the direction ratio is calculated.

Returns
direction_ratiolist

The direction ratio between the 2 points.

Examples

>>> from polytex.geometry import Point
>>> p1 = Point(1, 2, 3)
>>> p1.direction_ratio(Point(2, 3, 5))
[1, 1, 2]
dist(other)[source]

Both points must have the same dimensions :return: Euclidean distance

save_as_vtk(filename, color=None)[source]

Save the point as a vtk file.

property bounds
Returns
boundsarray_like

The bounding box of the point. The first row is the minimum values and the second row is the maximum values for each dimension.

property size

Number of elements in the array.

Equal to np.prod(a.shape), i.e., the product of the array’s dimensions.

Notes

a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested np.prod(a.shape), which returns an instance of np.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.

Examples

>>> x = np.zeros((3, 5, 2), dtype=np.complex128)
>>> x.size
30
>>> np.prod(x.shape)
30
property z
class polytex.geometry.basic.Vector(orig_3d=(0, 0, 0))[source]

Bases: Point

Default constructor. If no arguments are given, the point is initialized to (0, 0, 0).

Parameters
clsclass

The class of the object.

orig_3dtuple, list, or array_like

Defaults to 3d origin (0, 0, 0).

Returns
objPoint

The origin point of 3d space.

Examples

>>> p1 = Point()
>>> p1
Point([0, 0, 0])
Attributes
T

The transposed array.

add
base

Base object if memory is from some other object.

bounds

Returns ——- bounds : array_like The bounding box of the point.

ctypes

An object to simplify the interaction of the array with the ctypes module.

data

Python buffer object pointing to the start of the array’s data.

dtype

Data-type of the array’s elements.

flags

Information about the memory layout of the array.

flat

A 1-D iterator over the array.

imag

The imaginary part of the array.

itemsize

Length of one array element in bytes.

nbytes

Total bytes consumed by the elements of the array.

ndim

Number of array dimensions.

norm

Return —— norm : float The norm of the vector.

real

The real part of the array.

shape

Tuple of array dimensions.

size

Number of elements in the array.

strides

Tuple of bytes to step in each dimension when traversing an array.

sub
x
xyz
y
z

Return —— z : float 3rd dimension element.

Methods

all([axis, out, keepdims, where])

Returns True if all elements evaluate to True.

angle_between(other[, radian])

Return the angle between 2 vectors.

any([axis, out, keepdims, where])

Returns True if any of the elements of a evaluate to True.

argmax([axis, out, keepdims])

Return indices of the maximum values along the given axis.

argmin([axis, out, keepdims])

Return indices of the minimum values along the given axis.

argpartition(kth[, axis, kind, order])

Returns the indices that would partition this array.

argsort([axis, kind, order])

Returns the indices that would sort this array.

astype(dtype[, order, casting, subok, copy])

Copy of the array, cast to a specified type.

byteswap([inplace])

Swap the bytes of the array elements

choose(choices[, out, mode])

Use an index array to construct a new array from a set of choices.

clip([min, max, out])

Return an array whose values are limited to [min, max].

compress(condition[, axis, out])

Return selected slices of this array along given axis.

conj()

Complex-conjugate all elements.

conjugate()

Return the complex conjugate, element-wise.

copy([order])

Return a copy of the array.

cumprod([axis, dtype, out])

Return the cumulative product of the elements along the given axis.

cumsum([axis, dtype, out])

Return the cumulative sum of the elements along the given axis.

diagonal([offset, axis1, axis2])

Return specified diagonals.

direction_ratio(other)

Gives the direction ratio between 2 points.

dist(other)

Both points must have the same dimensions :return: Euclidean distance

dump(file)

Dump a pickle of the array to the specified file.

dumps()

Returns the pickle of the array as a string.

fill(value)

Fill the array with a scalar value.

flatten([order])

Return a copy of the array collapsed into one dimension.

getfield(dtype[, offset])

Returns a field of the given array as a certain type.

item(*args)

Copy an element of an array to a standard Python scalar and return it.

itemset(*args)

Insert scalar into an array (scalar is cast to array's dtype, if possible)

max([axis, out, keepdims, initial, where])

Return the maximum along a given axis.

mean([axis, dtype, out, keepdims, where])

Returns the average of the array elements along given axis.

min([axis, out, keepdims, initial, where])

Return the minimum along a given axis.

newbyteorder([new_order])

Return the array with the same data viewed with a different byte order.

nonzero()

Return the indices of the elements that are non-zero.

partition(kth[, axis, kind, order])

Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.

prod([axis, dtype, out, keepdims, initial, ...])

Return the product of the array elements over the given axis

ptp([axis, out, keepdims])

Peak to peak (maximum - minimum) value along a given axis.

put(indices, values[, mode])

Set a.flat[n] = values[n] for all n in indices.

ravel([order])

Return a flattened array.

repeat(repeats[, axis])

Repeat elements of an array.

reshape(shape[, order])

Returns an array containing the same data with a new shape.

resize(new_shape[, refcheck])

Change shape and size of array in-place.

round([decimals, out])

Return a with each element rounded to the given number of decimals.

save_as_vtk(filename[, color])

Save the point as a vtk file.

searchsorted(v[, side, sorter])

Find indices where elements of v should be inserted in a to maintain order.

setfield(val, dtype[, offset])

Put a value into a specified place in a field defined by a data-type.

setflags([write, align, uic])

Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.

sort([axis, kind, order])

Sort an array in-place.

squeeze([axis])

Remove axes of length one from a.

std([axis, dtype, out, ddof, keepdims, where])

Returns the standard deviation of the array elements along given axis.

sum([axis, dtype, out, keepdims, initial, where])

Return the sum of the array elements over the given axis.

swapaxes(axis1, axis2)

Return a view of the array with axis1 and axis2 interchanged.

take(indices[, axis, out, mode])

Return an array formed from the elements of a at the given indices.

tobytes([order])

Construct Python bytes containing the raw data bytes in the array.

tofile(fid[, sep, format])

Write array to a file as text or binary (default).

tolist()

Return the array as an a.ndim-levels deep nested list of Python scalars.

tostring([order])

A compatibility alias for tobytes, with exactly the same behavior.

trace([offset, axis1, axis2, dtype, out])

Return the sum along diagonals of the array.

transpose(*axes)

Returns a view of the array with axes transposed.

var([axis, dtype, out, ddof, keepdims, where])

Returns the variance of the array elements, along given axis.

view([dtype][, type])

New view of array with the same data.

cross

dot

set_x

set_y

set_z

angle_between(other, radian=False)[source]

Return the angle between 2 vectors.

\[\theta = \arccos \frac{v_1 \cdot v_2}{\|v_1\| \|v_2\|}\]
Parameters
otherVector object

The other vector to which the angle is calculated.

radianbool, optional

If True, return the angle in radians. The default is False.

Returns
anglefloat

The angle between the 2 vectors. If radian is True, the angle is in radians. Otherwise, the angle is in degrees.

property norm
class polytex.geometry.basic.Line(p1, p2=None, **kwargs)[source]

Bases: Line

Parameters
p1Point object

The first point of the line.

p2Point object

The second point of the line.

Attributes
ambient_dimension

A property method that returns the dimension of LinearEntity object.

args

Returns a tuple of arguments of ‘self’.

assumptions0

Return object type assumptions.

boundary

The boundary or frontier of a set.

bounds

Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure.

canonical_variables

Return a dictionary mapping any variable defined in self.bound_symbols to Symbols that do not clash with any free symbols in the expression.

closure

Property method which returns the closure of a set.

direction

The direction vector of the LinearEntity.

expr_free_symbols
free_symbols

Return from the atoms of self those which are free symbols.

func

The top-level function in an expression.

inf

The infimum of self.

interior

Property method which returns the interior of a set.

is_Complement
is_EmptySet
is_Intersection
is_UniversalSet
is_algebraic
is_antihermitian
is_closed

A property method to check whether a set is closed.

is_commutative
is_comparable

Return True if self can be computed to a real number (or already is a real number) with precision, else False.

is_complex
is_composite
is_empty
is_even
is_extended_negative
is_extended_nonnegative
is_extended_nonpositive
is_extended_nonzero
is_extended_positive
is_extended_real
is_finite
is_finite_set
is_hermitian
is_imaginary
is_infinite
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_odd
is_open

Property method to check whether a set is open.

is_polar
is_positive
is_prime
is_rational
is_real
is_transcendental
is_zero
kind

The kind of a Set

length

The length of the line.

measure

The (Lebesgue) measure of self.

p1

The first defining point of a linear entity.

p2

The second defining point of a linear entity.

points

The two points used to define this linear entity.

sup

The supremum of self.

Methods

angle_between(l2)

Return the non-reflex angle formed by rays emanating from the origin with directions the same as the direction vectors of the linear entities.

arbitrary_point([parameter])

A parameterized point on the Line.

are_concurrent(*lines)

Is a sequence of linear entities concurrent?

as_content_primitive([radical, clear])

A stub to allow Basic args (like Tuple) to be skipped when computing the content and primitive components of an expression.

as_dummy()

Return the expression with any objects having structurally bound symbols replaced with unique, canonical symbols within the object in which they appear and having only the default assumption for commutativity being True.

atoms(*types)

Returns the atoms that form the current object.

bisectors(other)

Returns the perpendicular lines which pass through the intersections of self and other that are in the same plane.

class_key()

Nice order of classes.

compare(other)

Return -1, 0, 1 if the object is less than, equal, or greater than other in a canonical sense.

complement(universe)

The complement of 'self' w.r.t the given universe.

contains(other)

Return True if other is on this Line, or False otherwise.

count(query)

Count the number of matching subexpressions.

count_ops([visual])

Wrapper for count_ops that returns the operation count.

distance(other)

Finds the shortest distance between a line and a point.

doit(**hints)

Evaluate objects that are not evaluated by default like limits, integrals, sums and products.

dummy_eq(other[, symbol])

Compare two expressions and handle dummy symbols.

encloses(o)

Return True if o is inside (not on or outside) the boundaries of self.

equals(other)

Returns True if self and other are the same mathematical entities

evalf([n, subs, maxn, chop, strict, quad, ...])

Evaluate the given formula to an accuracy of n digits.

find(query[, group])

Find all subexpressions matching a query.

fromiter(args, **assumptions)

Create a new object from an iterable.

has(*patterns)

Test whether any subexpression matches any of the patterns.

has_free(*patterns)

Return True if self has object(s) x as a free expression else False.

has_xfree(s)

Return True if self has any of the patterns in s as a free argument, else False.

intersect(other)

Returns the intersection of 'self' and 'other'.

intersection(other)

The intersection with another geometrical entity.

is_disjoint(other)

Returns True if self and other are disjoint.

is_parallel(l2)

Are two linear entities parallel?

is_perpendicular(l2)

Are two linear entities perpendicular?

is_proper_subset(other)

Returns True if self is a proper subset of other.

is_proper_superset(other)

Returns True if self is a proper superset of other.

is_same(b[, approx])

Return True if a and b are structurally the same, else False.

is_similar(other)

Return True if self and other are contained in the same line.

is_subset(other)

Returns True if self is a subset of other.

is_superset(other)

Returns True if self is a superset of other.

isdisjoint(other)

Alias for is_disjoint()

issubset(other)

Alias for is_subset()

issuperset(other)

Alias for is_superset()

match(pattern[, old])

Pattern matching.

matches(expr[, repl_dict, old])

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

n([n, subs, maxn, chop, strict, quad, verbose])

Evaluate the given formula to an accuracy of n digits.

parallel_line(p)

Create a new Line parallel to this linear entity which passes through the point p.

parameter_value(other, t)

Return the parameter corresponding to the given point.

perpendicular_line(p)

Create a new Line perpendicular to this linear entity which passes through the point p.

perpendicular_segment(p)

Create a perpendicular line segment from p to this line.

plot_interval([parameter])

The plot interval for the default geometric plot of line.

powerset()

Find the Power set of self.

projection(other)

Project a point, line, ray, or segment onto this linear entity.

random_point([seed])

A random point on a LinearEntity.

rcall(*args)

Apply on the argument recursively through the expression tree.

refine([assumption])

See the refine function in sympy.assumptions

reflect(line)

Reflects an object across a line.

replace(query, value[, map, simultaneous, exact])

Replace matching subexpressions of self with value.

rewrite(*args[, deep])

Rewrite self using a defined rule.

rotate(angle[, pt])

Rotate angle radians counterclockwise about Point pt.

scale([x, y, pt])

Scale the object by multiplying the x,y-coordinates by x and y.

simplify(**kwargs)

See the simplify function in sympy.simplify

smallest_angle_between(l2)

Return the smallest angle formed at the intersection of the lines containing the linear entities.

sort_key([order])

Return a sort key.

subs(*args, **kwargs)

Substitutes old for new in an expression after sympifying args.

symmetric_difference(other)

Returns symmetric difference of self and other.

translate([x, y])

Shift the object by adding to the x,y-coordinates the values x and y.

union(other)

Returns the union of self and other.

xreplace(rule)

Replace occurrences of objects within the expression.

copy

could_extract_minus_sign

is_hypergeometric

class polytex.geometry.basic.Curve(points)[source]

Bases: object

A partial inheritance of polytex.geometry.Point class.

Parameters
pointslist, tuple or array_like

A list of Point objects.

Attributes
ambient_dimension

Return the dimension of the curve.

bounds

Return the bounds of the curve.

curvature

Return the curvature of the curve.

length

Return the length of the curve.

tangent

Return the tangent vector of the curve at each point.

Methods

plot()

Plot the curve.

save([save_path])

Save the curve to a vtk file.

to_polygon()

Convert the curve to a polygon.

plot()[source]

Plot the curve.

Returns
None
save(save_path=None)[source]

Save the curve to a vtk file.

Parameters
save_pathstr

The path to save the vtk file.

Returns
None
to_polygon()[source]

Convert the curve to a polygon.

Returns
polygonPolygon object
property ambient_dimension

Return the dimension of the curve.

Returns
ambient_dimensionint
property bounds

Return the bounds of the curve.

Returns
boundstuple
property curvature

Return the curvature of the curve.

TODO: curvature of a curve

Returns
curvaturefloat
property length

Return the length of the curve.

Returns
lengthfloat
property tangent

Return the tangent vector of the curve at each point.

Returns
tangentVector object
class polytex.geometry.basic.Polygon(points)[source]

Bases: Curve

A partial inheritance of polytex.geometry.Point class.

Parameters
pointslist, tuple or array_like

A list of Point objects.

Attributes
ambient_dimension

Return the dimension of the curve.

area

Return the area of the polygon.

bounds

Return the bounds of the curve.

centroid

Return the centroid of the polygon.

curvature

Return the curvature of the curve.

length

Return the length of the curve.

perimeter

Return the perimeter of the polygon.

tangent

Return the tangent vector of the curve at each point.

Methods

plot()

Plot the curve.

save([save_path])

Save the curve to a vtk file.

to_curve()

Convert the polygon to a curve.

to_polygon()

Convert the curve to a polygon.

to_curve()[source]

Convert the polygon to a curve.

Returns
curveCurve object
property area

Return the area of the polygon.

Returns
areafloat
property centroid

Return the centroid of the polygon.

Returns
centroidPoint object
property perimeter

Return the perimeter of the polygon.

Returns
perimeterfloat
class polytex.geometry.basic.Plane(p1, a=None, b=None, **kwargs)[source]

Bases: object

Create a plane from 3 points or a point and a normal vector.

Parameters
p1Point object

A point on the plane.

aPoint object, optional

A point on the plane. The default is None.

bPoint object, optional

A point on the plane. The default is None.

**kwargsdict, optional

normal_vector can be passed as a keyword argument when leaving a and b as None. If both a and b are not None, normal_vector will be ignored.

Returns
planePlane object

Methods

distance(point)

Return the signed distance between a point and the plane.

function()

Return the equation of the plane as a function of x, y and z.

intersection(obj, max_dist)

Return the intersection of the plane with a curve or a polygon.

show()

Plot the plane.

distance(point)[source]

Return the signed distance between a point and the plane.

Parameters
pointPoint object

The point to calculate the distance. shape = (n, 3), where n is the number of points.

Returns
distancefloat

The distance between the point and the plane.

Examples

>>> from polytex.geometry import Point, Plane
>>> p1 = Point([5, 0, 0])
>>> normal = Point([1, 0, 0])
>>> plane = Plane(p1, normal_vector=normal)
>>> plane.show()
>>> plane.distance([[0, 0, 0], [1, 0, 0], [2, 0, 0]])
array([-5., -4., -3.])
function()[source]

Return the equation of the plane as a function of x, y and z.

Parameters
normalarray-like

normal vector of the plane.

pointarray-like

point on the plane.

Returns
A lambda function of x, y and z.

function of plane.

Notes

normal = (a, b, c) point = (x0, y0, z0) Equation of a plane: a(x-x0) + b(y-y0) + c(z-z0) = 0

Examples

Create a plane from a point and a normal vector >>> from polytex.geometry import Point, Plane >>> p1 = Point([1, 1, 1]) >>> normal = Point([1, 4, 7]) >>> plane2 = Plane(p1, normal_vector=normal) >>> f = plane2.function() >>> f <function polytex.geometry.basic.Plane.function.<locals>.<lambda>(x, y, z)> >>> f(1, 1, 1) 0

intersection(obj, max_dist)[source]

Return the intersection of the plane with a curve or a polygon.

Parameters
objCurve or Polygon object

The object to intersect with the plane.

max_distfloat

The maximum distance of checked points from the plane.

Returns
intersectionlist or array

The intersection point of the plane with the obj in the shape of (1, 3). If the intersection is not found, none is returned.

show()[source]

Plot the plane.

Returns
None
class polytex.geometry.basic.Ellipse2D(n: int, a: float, b: float, center=[0, 0])[source]

Bases: object

Parameters
nint

The number of points to generate.

afloat

The length of the major axis.

bfloat

The length of the minor axis.

centerlist, tuple or array_like

The center of the ellipse.

Methods

elipse_2d()

Generate points on an ellipse.

elipse_2d() ndarray[source]

Generate points on an ellipse.

Returns
xy: array-like

Points on the ellipse with shape (n, 2).

class polytex.geometry.basic.Tube(theta_res, h_res, vertices=None, **kwargs)[source]

Bases: GeometryEntity

Create a tubular surface.

Parameters
theta_resint

The number of points on each cross-section.

h_resint

The number of cross-sections.

verticesarray_like

The points on the cross-sections. The shape of the array should be (h_res * theta_res, 3). The points should be ordered in the following way: [p1, p2, …, p_theta_res, p1, p2, …, p_theta_res, …, p1, p2, …, p_theta_res] where p1, p2, …, p_theta_res are the points on each cross-section from the top to the bottom. The default value is None. If the value is None, the points will be generated automatically by assigning the height, major and minor radius to the tube.

Returns
tubeTube object

Examples

>>> from polytex.geometry import Tube
>>> tube = Tube(4, 10, major=2, minor=1, h=5)
>>> mesh = tube.mesh(plot=True)
>>> tube.save_as_mesh('tube.vtk')
Attributes
args

Returns a tuple of arguments of ‘self’.

assumptions0

Return object type assumptions.

bounds

Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure.

canonical_variables

Return a dictionary mapping any variable defined in self.bound_symbols to Symbols that do not clash with any free symbols in the expression.

expr_free_symbols
free_symbols

Return from the atoms of self those which are free symbols.

func

The top-level function in an expression.

h_res
is_algebraic
is_antihermitian
is_commutative
is_comparable

Return True if self can be computed to a real number (or already is a real number) with precision, else False.

is_complex
is_composite
is_even
is_extended_negative
is_extended_nonnegative
is_extended_nonpositive
is_extended_nonzero
is_extended_positive
is_extended_real
is_finite
is_hermitian
is_imaginary
is_infinite
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_odd
is_polar
is_positive
is_prime
is_rational
is_real
is_transcendental
is_zero
points
theta_res

Methods

as_content_primitive([radical, clear])

A stub to allow Basic args (like Tuple) to be skipped when computing the content and primitive components of an expression.

as_dummy()

Return the expression with any objects having structurally bound symbols replaced with unique, canonical symbols within the object in which they appear and having only the default assumption for commutativity being True.

atoms(*types)

Returns the atoms that form the current object.

class_key()

Nice order of classes.

compare(other)

Return -1, 0, 1 if the object is less than, equal, or greater than other in a canonical sense.

count(query)

Count the number of matching subexpressions.

count_ops([visual])

Wrapper for count_ops that returns the operation count.

doit(**hints)

Evaluate objects that are not evaluated by default like limits, integrals, sums and products.

dummy_eq(other[, symbol])

Compare two expressions and handle dummy symbols.

encloses(o)

Return True if o is inside (not on or outside) the boundaries of self.

evalf([n, subs, maxn, chop, strict, quad, ...])

Evaluate the given formula to an accuracy of n digits.

find(query[, group])

Find all subexpressions matching a query.

fromiter(args, **assumptions)

Create a new object from an iterable.

has(*patterns)

Test whether any subexpression matches any of the patterns.

has_free(*patterns)

Return True if self has object(s) x as a free expression else False.

has_xfree(s)

Return True if self has any of the patterns in s as a free argument, else False.

intersection(o)

Returns a list of all of the intersections of self with o.

is_same(b[, approx])

Return True if a and b are structurally the same, else False.

match(pattern[, old])

Pattern matching.

matches(expr[, repl_dict, old])

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

mesh([plot, show_edges])

TODO : raise TypeError("Given points must be a sequence or an array.")

n([n, subs, maxn, chop, strict, quad, verbose])

Evaluate the given formula to an accuracy of n digits.

rcall(*args)

Apply on the argument recursively through the expression tree.

refine([assumption])

See the refine function in sympy.assumptions

replace(query, value[, map, simultaneous, exact])

Replace matching subexpressions of self with value.

rewrite(*args[, deep])

Rewrite self using a defined rule.

rotate(angle[, pt])

Rotate angle radians counterclockwise about Point pt.

save_as_mesh(save_path[, end_closed])

Save the tubular mesh to a file.

scale([x, y, pt])

Scale the object by multiplying the x,y-coordinates by x and y.

simplify(**kwargs)

See the simplify function in sympy.simplify

sort_key([order])

Return a sort key.

subs(*args, **kwargs)

Substitutes old for new in an expression after sympifying args.

translate([x, y])

Shift the object by adding to the x,y-coordinates the values x and y.

xreplace(rule)

Replace occurrences of objects within the expression.

copy

could_extract_minus_sign

is_hypergeometric

mesh(plot=False, show_edges=True)[source]

TODO : raise TypeError(“Given points must be a sequence or an array.”)

Notes

theta_res should be 1 less then else where. To be fixed in the future.

save_as_mesh(save_path, end_closed=True)[source]

Save the tubular mesh to a file. The file format is determined by the extension of the filename. The possible file formats are: [“.ply”, “.stl”, “.vtk”, “.vtu”].

TODO : There seems to be a bug in correction option of the to_meshio_data() method of the tubular mesh.

Parameters
save_pathstr

The path and the name of the file to be saved with the extension.

end_closedbool

If True, the ends of the tube will be closed. The default value is True.

Returns
meshpyvista.UnstructuredGrid

The tubular mesh.

Examples

>>> from polytex.geometry import Tube
>>> tube = Tube(5,10,major=2, minor=1,h=5)
>>> tube.save_as_mesh('tube.vtu')
property bounds

Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure.

Parametric geometries

class polytex.geometry.basic.ParamCurve(limits, function=[], dataset=None, krig_config=('lin', 'cub'), smooth=0.0, verbose=False)[source]

Bases: object

Parameters
limits3-tuple

Function parameter and lower and upper bounds.

functionlist

The function list for each coordinate component. The default value is [].

datasetarray_like

The dataset of the curve. The default value is None. The first column is the parameter and the other columns are the value of coordinate components.

One of the function or dataset must be given. Please note that both are given, the dataset will be ignored.

krig_configtuple

The kriging interpolation configuration. The default value is (“lin”, “cub”). The tuple should be in the form of (drift_name, covariance_name).

smoothfloat

The smoothing factor. The default value is 0.0.

verbosebool

If True, print the information of the kriging process. The default value is False.

Returns
curveParamCurve object

Methods

eval(t_value)

Evaluate the curve at a given parameter value.

bounds

eval(t_value)[source]

Evaluate the curve at a given parameter value. The parameter value should be within the limits. Otherwise, an error will be raised.

Parameters
t_valuefloat or array_like

The parameter value for evaluation.

Returns
curveCurve object

The evaluated curve.

class polytex.geometry.basic.ParamSurface(functions, limits, **kwargs)[source]

Bases: GeometryEntity

Parameters
functionslist of functions

Function argument should be (x(s, t), y(s, t), z(s, t)) for a 3D surface.

limits2-tuple

Function parameter and lower and upper bounds of the two parameters. For example, ((s, 0, 1), (t, 0, 1)) is valid. The parameter should be the same for all three functions.

Attributes
args

Returns a tuple of arguments of ‘self’.

assumptions0

Return object type assumptions.

bounds

Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure.

canonical_variables

Return a dictionary mapping any variable defined in self.bound_symbols to Symbols that do not clash with any free symbols in the expression.

expr_free_symbols
free_symbols

Return from the atoms of self those which are free symbols.

func

The top-level function in an expression.

functions

The functions specifying the surface.

is_algebraic
is_antihermitian
is_commutative
is_comparable

Return True if self can be computed to a real number (or already is a real number) with precision, else False.

is_complex
is_composite
is_even
is_extended_negative
is_extended_nonnegative
is_extended_nonpositive
is_extended_nonzero
is_extended_positive
is_extended_real
is_finite
is_hermitian
is_imaginary
is_infinite
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_odd
is_polar
is_positive
is_prime
is_rational
is_real
is_transcendental
is_zero
limits

The limits of the two parameters specifying the surface.

Methods

as_content_primitive([radical, clear])

A stub to allow Basic args (like Tuple) to be skipped when computing the content and primitive components of an expression.

as_dummy()

Return the expression with any objects having structurally bound symbols replaced with unique, canonical symbols within the object in which they appear and having only the default assumption for commutativity being True.

atoms(*types)

Returns the atoms that form the current object.

class_key()

Nice order of classes.

compare(other)

Return -1, 0, 1 if the object is less than, equal, or greater than other in a canonical sense.

count(query)

Count the number of matching subexpressions.

count_ops([visual])

Wrapper for count_ops that returns the operation count.

doit(**hints)

Evaluate objects that are not evaluated by default like limits, integrals, sums and products.

dummy_eq(other[, symbol])

Compare two expressions and handle dummy symbols.

encloses(o)

Return True if o is inside (not on or outside) the boundaries of self.

eval(s_value, t_value)

Evaluate the surface at the given parameter values.

evalf([n, subs, maxn, chop, strict, quad, ...])

Evaluate the given formula to an accuracy of n digits.

find(query[, group])

Find all subexpressions matching a query.

fromiter(args, **assumptions)

Create a new object from an iterable.

has(*patterns)

Test whether any subexpression matches any of the patterns.

has_free(*patterns)

Return True if self has object(s) x as a free expression else False.

has_xfree(s)

Return True if self has any of the patterns in s as a free argument, else False.

intersection(o)

Returns a list of all of the intersections of self with o.

is_same(b[, approx])

Return True if a and b are structurally the same, else False.

match(pattern[, old])

Pattern matching.

matches(expr[, repl_dict, old])

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

n([n, subs, maxn, chop, strict, quad, verbose])

Evaluate the given formula to an accuracy of n digits.

rcall(*args)

Apply on the argument recursively through the expression tree.

refine([assumption])

See the refine function in sympy.assumptions

replace(query, value[, map, simultaneous, exact])

Replace matching subexpressions of self with value.

rewrite(*args[, deep])

Rewrite self using a defined rule.

rotate(angle[, axis])

Rotate angle radians counterclockwise about Point pt.

scale([x, y, z])

Scale the object by multiplying the x,y-coordinates by x and y.

simplify(**kwargs)

See the simplify function in sympy.simplify

sort_key([order])

Return a sort key.

subs(*args, **kwargs)

Substitutes old for new in an expression after sympifying args.

translate([x, y, z])

Shift the object by adding to the x,y-coordinates the values x and y.

xreplace(rule)

Replace occurrences of objects within the expression.

copy

could_extract_minus_sign

is_hypergeometric

eval(s_value, t_value)[source]

Evaluate the surface at the given parameter values.

Parameters
s_valuefloat or array_like

The parameter value for evaluation.

t_valuefloat or array_like

The parameter value for evaluation.

Returns
Surface

The surface evaluated at the given parameter values. the shape of the returned surface is (len(s) * len(t), 3). The first column is s values, the second column is t values, and the following columns are the coordinates of the surface at the given parameter values (x, y, z).

rotate(angle, axis='z')[source]

Rotate angle radians counterclockwise about Point pt.

The default pt is the origin, Point(0, 0)

See also

scale, translate

Examples

>>> from sympy import Point, RegularPolygon, Polygon, pi
>>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
>>> t # vertex on x axis
Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
>>> t.rotate(pi/2) # vertex on y axis now
Triangle(Point2D(0, 1), Point2D(-sqrt(3)/2, -1/2), Point2D(sqrt(3)/2, -1/2))
scale(x=1, y=1, z=1)[source]

Scale the object by multiplying the x,y-coordinates by x and y.

If pt is given, the scaling is done relative to that point; the object is shifted by -pt, scaled, and shifted by pt.

See also

rotate, translate

Examples

>>> from sympy import RegularPolygon, Point, Polygon
>>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
>>> t
Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
>>> t.scale(2)
Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)/2), Point2D(-1, -sqrt(3)/2))
>>> t.scale(2, 2)
Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)), Point2D(-1, -sqrt(3)))
translate(x=0, y=0, z=0)[source]

Shift the object by adding to the x,y-coordinates the values x and y.

See also

rotate, scale

Examples

>>> from sympy import RegularPolygon, Point, Polygon
>>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
>>> t
Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
>>> t.translate(2)
Triangle(Point2D(3, 0), Point2D(3/2, sqrt(3)/2), Point2D(3/2, -sqrt(3)/2))
>>> t.translate(2, 2)
Triangle(Point2D(3, 2), Point2D(3/2, sqrt(3)/2 + 2), Point2D(3/2, 2 - sqrt(3)/2))
property functions

The functions specifying the surface.

Returns
functions

list of parameterized coordinate functions.

Examples

>>> from sympy.abc import t
>>> from polytex.geometry import ParamCurve3D
>>> surface = ParamSurface((t, t, t), ((t, 0, 1), (t, 0, 1)))
>>> surface.functions
(t, t, t)
property limits

The limits of the two parameters specifying the surface.

Returns
list limits of the parameters.

Examples

>>> from sympy.abc import t
>>> from polytex.geometry import ParamCurve3D
>>> surface = ParamSurface((t, t, t), ((t, 0, 1), (t, 0, 1)))
>>> surface.limits
((t, 0, 1), (t, 0, 1))