docs/pyLatticeSim.md¶
API — pyLatticeSim¶
Core modules¶
pyLatticeSim.lattice_sim
¶
Classes:
| Name | Description |
|---|---|
Beam |
Class Beam represents a beam element defined by two endpoints (Point objects), a radius, material index, type, |
Cell |
Class representing a cell in the lattice structure. |
Lattice |
Class to generate lattice structures with various parameters and properties. |
ThinPlateSplineRBF |
Thin-plate-spline (polyharmonic, k=2) RBF interpolator with a linear polynomial tail. |
LatticeSim |
|
Functions:
| Name | Description |
|---|---|
open_lattice_parameters |
Open a JSON file containing lattice parameters. |
load_reduced_basis |
Load a previously saved reduced basis based on the lattice simulation parameters and tolerance. |
get_schur_complement |
Calculate the Schur complement of the stiffness matrix for a given lattice. |
conjugate_gradient_solver |
Solve the system Ax = b using the Conjugate Gradient method. |
solve_FEM_cell |
Solve the finite element method problem for a specific cell in the lattice using FenicsX. |
_import_scipy_sparse |
|
coo_matrix |
|
LinearOperator |
|
splu |
|
spilu |
|
_import_sklearn_neighbors |
|
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
|
NearestNeighbors |
|
timing = Timing()
module-attribute
¶
NearestNeighbors = _import_sklearn_neighbors()
module-attribute
¶
Beam
¶
Bases: object
Class Beam represents a beam element defined by two endpoints (Point objects), a radius, material index, type, and the cells it belongs to.
Methods:
| Name | Description |
|---|---|
__init__ |
Initialize a Beam object representing a beam element. |
destroy |
Delete the beam and clean up references in points and cells. |
get_length |
Calculate the length of the beam. |
get_volume |
Calculate the volume of the beam in case of a circular section. |
is_identical_to |
Check if this beam is identical to another beam. |
add_cell_belonging |
Add a cell to the beam’s belongings if not already present. |
get_angle_between_beams |
Calculates the angle between two beams |
get_point_on_beam_at_distance |
Calculate the coordinates of a point on the beam at a specific distance from an endpoint. |
is_point_on_beam |
Check if a given node lies on the beam. |
set_angle |
Assign angle and radius data to one of the beam’s endpoints. |
get_length_mod |
Calculate the modification length for the penalization method. |
set_beam_mod |
Set the beam as modified. |
unset_beam_mod |
Unset the beam as modified. |
change_beam_radius |
Change the radius of the beam. |
Attributes:
| Name | Type | Description |
|---|---|---|
data |
List[int]
|
Property to retrieve beam data for exporting. |
data
property
¶
Property to retrieve beam data for exporting.
List[int]: [beam_index, point1_index, point2_index, beam_type].
__init__(point1, point2, radius, material, type_beam, cell_belongings)
¶
Parameters:¶
point1 : Point The first endpoint of the beam.
Point
The second endpoint of the beam.
float
The radius of the beam.
int
The material index of the beam.
int
Reference to the geometry type of the beam in case of multiple geometries.
Cell or list of Cell
The cell(s) to which the beam belongs.
destroy()
¶
Delete the beam and clean up references in points and cells. This method removes the beam from its associated cells and points.
get_length()
¶
Calculate the length of the beam.
float: Length of the beam.
get_volume(section_type='circular')
¶
Calculate the volume of the beam in case of a circular section.
Parameters:¶
sectionType : str The type of the beam section. Currently only “circular” is supported.
float: Volume of the beam.
is_identical_to(other, tol=1e-09)
¶
Check if this beam is identical to another beam.
Parameters¶
other : Beam The other beam to compare with. tol : float Tolerance for floating-point comparisons.
add_cell_belonging(cell)
¶
Add a cell to the beam’s belongings if not already present.
Parameters:¶
cell : Cell The cell to add to the beam’s belongings.
get_angle_between_beams(other, periodicity)
¶
get_point_on_beam_at_distance(distance, start_point)
¶
Calculate the coordinates of a point on the beam at a specific distance from an endpoint.
Parameters:¶
distance : float The distance from the specified endpoint along the beam.
int
The index of the starting point (1 or 2) from which the distance is measured
List[float]: Coordinates [x, y, z] of the calculated point.
ValueError: If the point index is not 1 or 2.
is_point_on_beam(node)
¶
Check if a given node lies on the beam.
Parameters:¶
node : Point The node to check.
bool: True if the node lies on the beam, False otherwise.
set_angle(radius, angle, point)
¶
Assign angle and radius data to one of the beam’s endpoints.
Parameters:¶
radius : float Radius at the point.
float
Angle at the point in degrees.
Point
The point (endpoint) of the beam to which the data is assigned.
get_length_mod()
¶
Calculate the modification length for the penalization method.
Tuple[float, float]: Length modifications for point1 and point2.
set_beam_mod()
¶
Set the beam as modified.
unset_beam_mod()
¶
Unset the beam as modified.
Cell
¶
Bases: object
Class representing a cell in the lattice structure.
Methods:
| Name | Description |
|---|---|
__init__ |
Initialize a Cell with its dimensions and position |
dispose |
Dispose of the cell by detaching beams and points, and cleaning up references. |
generate_cell_properties |
Generate cell properties including beams and nodes. |
generate_beams |
Generate beams and nodes using a given lattice type_beam and parameters. |
get_beam_material |
Get the material of the beam based on the material gradient. |
get_radius |
Calculate and return the beam radii |
def_cell_size |
Calculate and return the cell size |
def_cell_center |
Calculate the center point of the cell |
get_point_on_surface |
Get the points on the surface specified in the global reference frame. |
remove_beam |
Removing beam from cell |
remove_point |
Removing point from cell |
add_beam |
Adding beam to cell |
add_point |
Adding point to cell |
add_cell_neighbour |
Add a neighbour cell in a structured dict format. |
get_all_cell_neighbours |
Get all neighbour cells in a flat list. |
refresh_from_global |
Rebuild self.beams_cell and self.points_cell from the current lattice state. |
define_node_order_to_simulate |
Define a deterministic order for boundary nodes to ensure consistent simulation results. |
set_reaction_force_on_nodes |
Set reaction force on each boundary node in the established local order. |
get_displacement_at_nodes |
Return displacement vectors ordered consistently with the provided local list/dict of Points. |
set_displacement_at_boundary_nodes |
Set displacement at nodes. |
build_coupling_operator |
Build the coupling operator B using the deterministic local boundary-node order. |
build_local_preconditioner |
Build the local preconditioner matrix B^T * S * B |
get_number_boundary_nodes |
Get the number of unique boundary nodes in the cell. |
get_internal_energy |
Get cell internal energy from all boundary points |
get_displacement_data |
Build and return displacement data on cell for dataset generation |
get_number_nodes_at_boundary |
Get the number of nodes at the boundary |
change_beam_radius |
WARNING: BEAM MOD IS NOT WORKING |
get_relative_density_kriging |
Get the relative density of the cell using kriging model |
get_relative_density_gradient |
Get the gradient of the relative density |
get_relative_density_gradient_kriging |
Finite difference gradient of the relative density (predictive mean) w.r.t. the radii using the trained |
get_relative_density_gradient_kriging_exact |
Exact gradient of the relative density (predictive mean) w.r.t. the radii using the trained |
get_RGBcolor_depending_of_radius |
Get the RGB color of the cell depending on the radii. |
print_data |
Print the data of the cell for debugging purposes. |
get_translation_rigid_body |
Get the translation of the rigid body |
get_rotation_rigid_body |
Get the rotation matrix of the rigid body using SVD. |
Attributes:
| Name | Type | Description |
|---|---|---|
volume |
Calculate the volume of the cell. |
|
relative_density |
float
|
Calculate the relative density of the cell based on the volume of beams and the cell volume. |
volume_each_geom |
ndarray
|
Get the volume of the cell separated by geometry type_beam. |
boundary_box |
list
|
Get the boundary box of the cell |
boundary_edges |
list[tuple[tuple[float, float, float], tuple[float, float, float]]]
|
Return the 12 edge segments of the cell’s axis-aligned bounding box |
corner_coordinates |
list
|
Get the corner coordinates of the cell. |
volume
property
¶
Calculate the volume of the cell.
relative_density
property
¶
Calculate the relative density of the cell based on the volume of beams and the cell volume.
volume_each_geom
property
¶
Get the volume of the cell separated by geometry type_beam.
boundary_box
property
¶
boundary_edges
property
¶
Return the 12 edge segments of the cell’s axis-aligned bounding box as pairs of 3D points ((x,y,z), (x,y,z)).
corner_coordinates
property
¶
Get the corner coordinates of the cell.
Returns:¶
list of tuples List of (x, y, z) coordinates of the corner points.
__init__(pos, initial_size, coordinate, geom_types, radii, grad_radius, grad_dim, grad_mat, uncertainty_node=0.0, _verbose=0, beams_already_defined=None, nodes_already_defined=None)
¶
Parameters:¶
pos: list Position of the cell in the lattice
list
Initial size of the cell
list
Coordinates of the cell minimum corner in the lattice
list[str]
Type of lattice geometry
float
Base radii of the beam
list
Gradient of the radii
list
Gradient of the dimensions
list
Gradient of the material
float
Standard deviation for adding uncertainty to node coordinates. Defaults to 0.0.
bool
If True, prints additional information during initialization. Defaults to False.
set
Set of beams already defined in the lattice to avoid duplication. Defaults to None.
set
Set of nodes already defined in the lattice to avoid duplication. Defaults to None.
dispose()
¶
Dispose of the cell by detaching beams and points, and cleaning up references.
generate_cell_properties(initial_cell_size, beams_already_defined=None, nodes_already_defined=None)
¶
Generate cell properties including beams and nodes.
Parameters:¶
initialCellSize: list Initial size of the cell without modification
set
Set of beams already defined in the lattice to avoid duplication
set
Set of nodes already defined in the lattice to avoid duplication
generate_beams(latticeType, beamRadius, beamType=0, beams_already_defined=None, nodes_already_defined=None)
¶
Generate beams and nodes using a given lattice type_beam and parameters.
Parameters:¶
latticeType: str Type of lattice structure (e.g., ‘BCC’, ‘Hybrid1’, etc.)
float
Radius of the beam
int
Type index of the beam
set
Set of beams already defined in the lattice to avoid duplication
set
Set of nodes already defined in the lattice to avoid duplication
get_beam_material()
¶
Get the material of the beam based on the material gradient.
get_radius(base_radius)
¶
def_cell_size(initial_cell_size)
¶
def_cell_center()
¶
Calculate the center point of the cell
get_point_on_surface(surfaceName)
¶
Get the points on the surface specified in the global reference frame.
Parameters:¶
surfaceName: str Name of the surface. Choose from ‘Xmin’, ‘Xmax’, ‘Ymin’, ‘Ymax’, ‘Zmin’, ‘Zmax’, ‘Xmid’, ‘Ymid’, ‘Zmid’. If ‘Xmid’, ‘Ymid’, or ‘Zmid’ is specified, it returns the points at the bottom of the cell
Returns:¶
list List of points on the specified surface.
remove_beam(beam_to_delete)
¶
Removing beam from cell
Parameters:¶
beam_to_delete: Beam or Iterable[Beam] Beam or list of beams to remove from the cell
remove_point(point_to_delete)
¶
Removing point from cell
Parameters:¶
point_to_delete: Point or Iterable[Point] Point or list of points to remove from the cell
add_beam(beam_to_add)
¶
Adding beam to cell
Parameters:¶
beam_to_add: Beam or Iterable[Beam] Beam or list of beams to add to the cell
add_point(point_to_add)
¶
Adding point to cell
Parameters:¶
point_to_add: Point or Iterable[Point] Point or list of points to add to the cell
add_cell_neighbour(direction, sign, neighbour_cell)
¶
Add a neighbour cell in a structured dict format.
Parameters¶
direction : str One of “x”, “y”, “z” sign : str Either “positif” or “negatif” neighbour_cell : Cell Neighbour cell to add
get_all_cell_neighbours()
¶
refresh_from_global(all_beams)
¶
Rebuild self.beams_cell and self.points_cell from the current lattice state. Keeps only beams that still declare this cell as a belonging, and derives points from those beams.
define_node_order_to_simulate(face_priority=None, tol=1e-09)
¶
Define a deterministic order for boundary nodes to ensure consistent simulation results.
Parameters:¶
face_priority: Optional[List[str]] List defining the priority order of faces to assign nodes to when they lie on multiple faces. Default is [“Xmin”, “Xmax”, “Ymin”, “Ymax”, “Zmin”, “Zmax”].
float
Tolerance for determining if a point lies on a face. Default is 1e-9.
set_reaction_force_on_nodes(reactionForce)
¶
Set reaction force on each boundary node in the established local order.
Parameters:¶
reactionForce: list List of reaction force vectors corresponding to each boundary node.
get_displacement_at_nodes(nodeList)
¶
set_displacement_at_boundary_nodes(displacementArray)
¶
Set displacement at nodes.
Parameters:¶
displacementArray: list or array-like Flattened array of displacement values.
build_coupling_operator(nb_free_DOF)
¶
Build the coupling operator B using the deterministic local boundary-node order.
Parameters:¶
nb_free_DOF: int Total number of free degrees of freedom in the global system.
build_local_preconditioner(schur_mean=None)
¶
Build the local preconditioner matrix B^T * S * B
Parameters:¶
schur_mean: array-like or None Schur complement matrix to use. If None, uses self.schur_complement.
get_number_boundary_nodes()
¶
Get the number of unique boundary nodes in the cell.
get_internal_energy()
¶
Get cell internal energy from all boundary points
get_displacement_data()
¶
Build and return displacement data on cell for dataset generation
get_number_nodes_at_boundary()
¶
change_beam_radius(new_radius)
¶
WARNING: BEAM MOD IS NOT WORKING Change beam radii in the cell
Parameters:¶
newRadius: list beam radii wanted to assign
get_relative_density_kriging(kriging_model)
¶
Get the relative density of the cell using kriging model
Parameters:¶
krigingModel: Kriging Kriging model to use for prediction
get_relative_density_gradient(relative_density_poly_deriv)
¶
get_relative_density_gradient_kriging(model, geometries_types)
¶
Finite difference gradient of the relative density (predictive mean) w.r.t. the radii using the trained Pipeline(StandardScaler -> GaussianProcessRegressor) with Constant*RBF kernel. Returns an array of size len(geometries_types) where entries for geometries not present in the cell are 0.
get_relative_density_gradient_kriging_exact(model, geometries_types)
¶
Exact gradient of the relative density (predictive mean) w.r.t. the radii using the trained Pipeline(StandardScaler -> GaussianProcessRegressor) with Constant*RBF kernel.
Returns an array of size len(geometries_types) where entries for geometries not present in the cell are 0.
Parameters:¶
model: Pipeline Trained kriging model
list
List of geometry types in the trained kriging model
get_RGBcolor_depending_of_radius()
¶
Get the RGB color of the cell depending on the radii.
print_data()
¶
Print the data of the cell for debugging purposes.
get_translation_rigid_body()
¶
Get the translation of the rigid body
get_rotation_rigid_body()
¶
Get the rotation matrix of the rigid body using SVD.
Lattice
¶
Bases: object
Class to generate lattice structures with various parameters and properties.
Methods:
| Name | Description |
|---|---|
__init__ |
Constructor from a JSON file to create a lattice object. |
open_pickle_lattice |
Load a lattice pickle and (optionally) upcast it to the caller’s class (e.g., LatticeSim). |
__eq__ |
Compare two Lattice objects based on the radii of each cell. |
get_number_cells |
Get number of cells in the lattice |
get_number_beams |
Get number of beams in the lattice |
get_number_nodes |
Get number of nodes in the lattice |
extract_parameters_from_json |
Extract lattice parameters from a JSON file and set the corresponding attributes. |
get_lattice_boundary_box |
Get the boundary box of the lattice |
define_lattice_dimensions |
Computes extremum values of coordinates in the lattice. |
get_relative_density |
Get mean relative density of all cells in lattice |
get_beam_radius_min_max |
Get the maximum and minimum radii of the lattice |
define_gradient |
Define gradient settings for radii, dimensions, and materials based on provided properties. |
generate_lattice |
Generate cells in the lattice structure based on cell size, number of cells, geometry types, and radii. |
cut_beam_with_mesh_trimmer |
Cut beams in the lattice using the mesh trimmer. |
apply_symmetry |
Apply symmetry to the lattice by mirroring cells across a specified plane. |
delete_beams_under_radius_threshold |
Delete beams with radii under a certain threshold |
set_tag_classification |
Define tag list classification. |
define_size_lattice |
Computes the size of the lattice along each direction. |
is_not_in_erased_region |
Check if the cell is not in the erased region or inside the mesh. |
define_beam_node_index |
Define index at each beam and node |
define_cell_index |
Define index at each cell |
define_node_local_tags |
Define inside cell boundary tag for all boundary nodes |
define_cell_neighbours |
Neighbour assignment using integer grid indices + optional periodic wrap. |
define_connected_beams_for_all_nodes |
Populate |
define_angles_between_beams |
Compute, for each beam, the penalization-optimal angle at its two endpoints |
refresh_cells_memberships |
Public helper to refresh all cells’ beams/points from the current global state. |
remove_cell |
Removes a cell from the lattice |
find_minimum_beam_length |
Find minimum beam length |
get_tag_list |
Get the tag for all unique points in the lattice. |
get_tag_list_boundary |
Get the tag for boundary points in the lattice. |
apply_tag_all_point |
Assign a tag to all nodes in the lattice structure. |
get_cell_occupancy_matrix |
Build a 3D matrix storing Cell objects (or None) at each (i, j, k). |
get_cells_at_index |
Get all cells at a specific index along a specified axis. |
get_relative_boundary_box |
Get the relative boundary box of a cell in the lattice. |
get_name_lattice |
Determine the name_lattice of the lattice |
check_hybrid_collision |
Check if beam in hybrid configuration is cut by a point in the geometry |
are_cells_identical |
Check if all cells in the lattice are identical. |
change_beam_radius |
Change beam radius for all beams in the lattice |
change_beam_radius_depending_type |
Change radii of beam for specific type_beam |
find_point_on_lattice_surface |
Find points on the surface of the lattice |
get_cells_on_surfaces |
Return the list of Cell objects matching ordered extrema constraints like [“Xmin”], [“Xmin”,”Zmax”], etc. |
print_statistics_lattice |
Print statistics about the lattice |
delete_orphan_points |
Delete points that are not connected to any beam in the lattice. |
merge_degree2_nodes |
Fusion of nodes with exactly 2 connected beams. |
delete_unconnected_beams |
Delete beams that are “leaf” beams, i.e. connected to at least one node of degree 1 or 0. |
generate_mesh_lattice_Gmsh |
Generate a 2D mesh representation of the lattice structure using GMSH. |
get_volume_mesh |
Compute the exact CAD volume (OCC ‘mass’ with unit density) of the current model |
get_relative_density_mesh |
Compute relative density = V_solid / V_domain using exact CAD volumes. |
generate_mesh_lattice_rough |
Generate a mesh of the lattice structure with Pyrough library. |
__init__(name_file, mesh_trimmer=None, verbose=0)
¶
Parameters:¶
name_file: str Name of the JSON file containing lattice parameters.
MeshTrimmer, optional
MeshTrimmer object to trim the lattice.
int, optional
Verbosity level for logging.
open_pickle_lattice(file_name='LatticeObject', sim_config=None)
classmethod
¶
Load a lattice pickle and (optionally) upcast it to the caller’s class (e.g., LatticeSim).
If the target class defines _post_load_init, it will be invoked after loading.
__eq__(other)
¶
Compare two Lattice objects based on the radii of each cell. Returns True if they have the same number of cells and identical radii values.
get_number_cells()
¶
Get number of cells in the lattice
get_number_beams()
¶
Get number of beams in the lattice
get_number_nodes()
¶
Get number of nodes in the lattice
extract_parameters_from_json(name_file)
¶
Extract lattice parameters from a JSON file and set the corresponding attributes.
Parameters:¶
name_file: str Name of the JSON file containing lattice parameters.
get_lattice_boundary_box()
¶
Get the boundary box of the lattice
define_lattice_dimensions()
¶
Computes extremum values of coordinates in the lattice.
Return:¶
lattice_dimension_dict: dict Dictionary containing min and max values for x, y, z coordinates.
get_relative_density()
¶
Get mean relative density of all cells in lattice Simple average of cell relative densities
Returns:¶
meanRelDens: float Mean relative density of the lattice
get_beam_radius_min_max()
¶
Get the maximum and minimum radii of the lattice
Returns:¶
radMax: float Maximum radii of the lattice
float
Minimum radii of the lattice
define_gradient(grad_radius_property, grad_dim_property, grad_mat_property)
¶
Define gradient settings for radii, dimensions, and materials based on provided properties.
Parameters:¶
grad_radius_property: list Properties defining the gradient for radii.
list
Properties defining the gradient for cell dimensions.
list
Properties defining the gradient for material settings.
generate_lattice()
¶
Generate cells in the lattice structure based on cell size, number of cells, geometry types, and radii. Gradient information and erased regions are also considered during cell generation.
cut_beam_with_mesh_trimmer()
¶
Cut beams in the lattice using the mesh trimmer.
apply_symmetry(symmetry_plane=None, reference_point=None)
¶
Apply symmetry to the lattice by mirroring cells across a specified plane.
Parameters:¶
symmetry_plane: str, optional Plane of symmetry (‘XY’, ‘XZ’, ‘YZ’, ‘X’, ‘Y’, or ‘Z’). If None, uses self.symmetry_lattice[‘sym_plane’].
tuple of float, optional
Reference point for the symmetry operation (x_ref, y_ref, z_ref). If None, uses self.symmetry_lattice[‘sym_point’].
delete_beams_under_radius_threshold(threshold=0.01)
¶
Delete beams with radii under a certain threshold
Parameters:¶
threshold: float Threshold value for beam radii
set_tag_classification()
¶
Define tag list classification.
define_size_lattice()
¶
Computes the size of the lattice along each direction.
is_not_in_erased_region(start_cell_pos)
¶
define_beam_node_index()
¶
Define index at each beam and node
define_cell_index()
¶
Define index at each cell
define_node_local_tags()
¶
Define inside cell boundary tag for all boundary nodes
define_cell_neighbours()
¶
Neighbour assignment using integer grid indices + optional periodic wrap.
define_connected_beams_for_all_nodes(merge_tol=1e-09)
¶
Populate Point.connected_beams for all nodes.
Optionally merges connectivity for coincident/periodic nodes via a spatial hash.
Parameters¶
merge_tol : float Quantization used to bucket nearly-identical coordinates (and periodic wraps).
define_angles_between_beams()
¶
Compute, for each beam, the penalization-optimal angle at its two endpoints
using node-level connectivity (Point.connected_beams). Assumes
define_connected_beams_for_all_nodes() has been called.
refresh_cells_memberships()
¶
Public helper to refresh all cells’ beams/points from the current global state.
remove_cell(index)
¶
find_minimum_beam_length()
¶
get_tag_list()
¶
Get the tag for all unique points in the lattice.
get_tag_list_boundary()
¶
Get the tag for boundary points in the lattice.
apply_tag_all_point()
¶
Assign a tag to all nodes in the lattice structure. Tags are assigned relative to either the global bounding box or a local (cell-relative) bounding box if erased parts are used.
get_cell_occupancy_matrix()
¶
Build a 3D matrix storing Cell objects (or None) at each (i, j, k).
Returns¶
occupancy_matrix : np.ndarray, shape (num_cells_x, num_cells_y, num_cells_z), dtype=object occupancy_matrix[i, j, k] is the Cell at that grid position, or None if empty.
get_cells_at_index(axis, index)
¶
Get all cells at a specific index along a specified axis.
Parameters:¶
axis: str Axis to query (‘x’, ‘y’, or ‘z’).
int
Index along the specified axis.
get_relative_boundary_box(cell)
¶
Get the relative boundary box of a cell in the lattice. It corresponds to the minimum and maximum dimension of the lattice for each axis with cell continuity. Useful for structures with erased parts or periodic boundaries.
Parameters:¶
cell: Cell object The cell for which the boundary box is computed.
get_name_lattice()
¶
check_hybrid_collision()
¶
Check if beam in hybrid configuration is cut by a point in the geometry Change the beam configuration of collisionned beams
are_cells_identical()
¶
Check if all cells in the lattice are identical.
change_beam_radius(radius_list)
¶
Change beam radius for all beams in the lattice radius_list must have the same length as the number of different beam types in cells
Take care if penalization is activated, the radius of penalized beams will be modified with the penalization coefficient but the length of the modified beam will not be changed (Use reset_cell_with_new_radii instead if you want to have clean cells for simulation)
Parameters:¶
radius_list: list of float List of new radii for each beam type
change_beam_radius_depending_type(typeToChange, newRadius)
¶
Change radii of beam for specific type_beam
Parameters:¶
typeToChange: int Type of beam to change newRadius: float New radii of beam
find_point_on_lattice_surface(surfaceNames, surface_cells=None)
¶
Find points on the surface of the lattice
Parameters:¶
surfaceNames: list[str] List of surfaces to find points on (e.g., [“Xmin”, “Xmax”, “Ymin”])
list[str], optional
List of surfaces to find points on cells (e.g., [“Xmin”, “Xmax”, “Ymin”]). If None, use surfaceNames.
Returns:¶
pointSet: set of point objects Set of points found on the specified surfaces
get_cells_on_surfaces(surfaces)
¶
Return the list of Cell objects matching ordered extrema constraints like [“Xmin”], [“Xmin”,”Zmax”], etc. Filtering is iterative: e.g., first keep all cells at X minimum, then among those keep Z maximum.
Parameters¶
surfaces : list[str] Each item is one of {“Xmin”,”Xmax”,”Ymin”,”Ymax”,”Zmin”,”Zmax”} (case-insensitive).
Returns¶
list List of Cell objects (possibly multiple if several share the same extreme index).
print_statistics_lattice()
¶
Print statistics about the lattice
delete_orphan_points()
¶
Delete points that are not connected to any beam in the lattice.
merge_degree2_nodes(colinear_only=True, radius_strategy='inherit', type_strategy='inherit', material_strategy='inherit', iterative=True, max_passes=10)
¶
Fusion of nodes with exactly 2 connected beams. The two beams must be colinear (if colinear_only=True) and the node must be between the two beam endpoints. The two beams are replaced by a single beam connecting the two distant endpoints.
Parameters:¶
colinear_only : bool If True, only merge if the two beams are colinear.
str
Strategy for determining the radius of the new beam: “inherit” (default) - if both beams have the same radius, use it; otherwise use b1’s radius. “max” - use the maximum radius of the two beams. “min” - use the minimum radius of the two beams. “avg” - use the average radius of the two beams.
str
Strategy for determining the type of the new beam: “inherit” (default) - if both beams have the same type, use it; otherwise use b1’s type. “max” - use the maximum type of the two beams. “min” - use the minimum type of the two beams. “avg” - use the average type of the two beams (rounded).
str
Strategy for determining the material of the new beam: “inherit” (default) - if both beams have the same material, use it; otherwise use b1’s material. “max” - use the maximum material of the two beams. “min” - use the minimum material of the two beams. “avg” - use the average material of the two beams (rounded).
bool
If True, repeat the merging process until no more merges are possible or max_passes is reached.
int
Maximum number of passes if iterative is True.
Returns:¶
total_merged : int Total number of nodes merged.
delete_unconnected_beams(protect_fixed=True, protect_loaded=True, also_delete_orphan_nodes=True)
¶
Delete beams that are “leaf” beams, i.e. connected to at least one node of degree 1 or 0.
Parameters:¶
protect_fixed: bool If True, do not delete beams connected to fixed nodes.
bool
If True, do not delete beams connected to loaded nodes.
bool
If True, delete nodes that become orphaned after beam removal.
Returns:¶
tuple[int, int] Number of beams removed and number of nodes removed.
generate_mesh_lattice_Gmsh(cut_mesh_at_boundary=False, mesh_refinement=1, name_mesh='Lattice', save_mesh=False, save_STL=True, volume_computation=False, only_volume=False, only_relative_density=False, cell_index=None)
¶
Generate a 2D mesh representation of the lattice structure using GMSH. Generating 3D mesh for simulation is not currently supported, but will be in the future.
Parameters:¶
cut_mesh_at_boundary: bool If True, the mesh will be cut at the boundary of the lattice.
float
Refinement factor for the mesh (higher values lead to finer meshes).
str
Name of the mesh to be generated.
bool
If True, the mesh will be saved to a file.
bool
If True, the mesh will be saved in STL format.
bool
If True, the volume of the mesh will be computed and printed.
bool
If True, only the volume of the mesh will be computed and returned.
bool
If True, only the relative density of the mesh will be computed and returned.
int | None
If provided, only the specified cell will be meshed.
get_volume_mesh(entities_3d=None, synchronize=True, return_details=False)
¶
Compute the exact CAD volume (OCC ‘mass’ with unit density) of the current model without requiring any meshing.
Parameters¶
entities_3d : list[(int,int)] | None Optional list of 3D OCC entities (pairs (dim=3, tag)). If None, all 3D entities in the current model are used.
bool
If True, call gmsh.model.occ.synchronize() before querying mass properties. Set to False only if you’ve already synchronized after your boolean ops.
bool
If True, return a dict with ‘total’ and ‘per_entity’ (list of (tag, volume)).
Returns¶
float | dict Total volume if return_details is False, else a dict:
get_relative_density_mesh(solids_3d=None, domain_volume=None)
¶
Compute relative density = V_solid / V_domain using exact CAD volumes.
If domain_volume is None, the domain is taken as the axis-aligned box defined by (x_min..x_max) × (y_min..y_max) × (z_min..z_max).
generate_mesh_lattice_rough(name_file_rough_parameters, name_stl_out, print_volume=True, save_mesh=True, cut_mesh_at_boundary=False, refine_mesh=True)
¶
Generate a mesh of the lattice structure with Pyrough library.
Parameters:¶
name_file_rough_parameters: str Name of the file containing roughness parameters for Pyrough. name_stl_out: str Name of the output STL file. print_volume: bool If True, print the volume of the generated mesh. save_mesh: bool If True, save the generated mesh to the specified path. cut_mesh_at_boundary: bool If True, cut the mesh at the boundary of the lattice. refine_mesh: bool If True, refine the generated mesh using Pyrough’s refinement function.
ThinPlateSplineRBF
¶
Thin-plate-spline (polyharmonic, k=2) RBF interpolator with a linear polynomial tail. Supports vector-valued outputs Y in R^{N x m}. Provides evaluation f(X) and analytic gradient ∇f(X).
Methods:
| Name | Description |
|---|---|
__init__ |
Parameters |
evaluate |
Evaluate the interpolant at one or many points. |
gradient |
Evaluate the gradient ∇f at one or many points. |
LatticeSim
¶
Bases: Lattice
Methods:
| Name | Description |
|---|---|
define_simulation_parameters |
Define simulation parameters from the input file. |
set_penalized_beams |
Set penalization on beams at nodes based on L_zone values defined at beam endpoints. |
reset_penalized_beams |
Revert the penalization modifications made by set_penalized_beams. |
apply_constraints_nodes |
Apply boundary conditions to the lattice |
set_boundary_conditions |
Set boundary conditions on the lattice. |
get_global_displacement |
Get global displacement of the lattice |
define_node_index_boundary |
Define boundary tag for all boundary nodes and calculate the total number of boundary nodes |
get_global_reaction_force |
Get local reaction force of the lattice and sum if identical TagIndex |
get_global_reaction_force_without_fixed_DOF |
Get global reaction force of the lattice without fixed DOF |
define_free_DOF |
Get total number of degrees of freedom in the lattice |
set_global_free_DOF_index |
Set global free degree of freedom index for all nodes in boundary |
get_global_displacement_DDM |
Get global displacement of the lattice |
evaluate_alphas_linear_surrogate |
Robust linear surrogate with safe extrapolation: |
define_parameters |
Define parameters for the domain decomposition solver. |
build_coupling_operator_cells |
Build coupling operator for each cell in the lattice |
calculate_schur_complement_cells |
Calculate the Schur complement for each cell in the lattice. |
get_schur_complement_from_reduced_basis_batch |
Vectorized version: compute Schur complements for many queries in one GEMM (faster than many GEMVs). |
get_schur_complement_from_reduced_basis |
Get the Schur complement from the reduced basis with a giver surrogate method |
solve_DDM |
Solve the problem with the domain decomposition method. |
calculate_reaction_force_global |
Calculate the global reaction force of the lattice |
update_reaction_force_each_cell |
Update RF local |
solve_sub_problem |
Solve the subproblem on a cell to get the reaction force |
cg_progress |
Callback function to track and plot progress of the CG method. |
define_preconditioner |
Define the preconditioner for the conjugate gradient solver. |
build_preconditioner |
Build a sparse LU/ILU preconditioner of the global Schur complement. |
reset_cell_with_new_radii |
Reset cell with new radii for each beam type |
get_global_force_displacement_curve |
Aggregate global force (sum of reactions) vs imposed displacement for comparison with experiment. |
define_simulation_parameters(name_file)
¶
Define simulation parameters from the input file.
Parameters¶
name_file : str Name of the input file
set_penalized_beams()
¶
Set penalization on beams at nodes based on L_zone values defined at beam endpoints. This method allows for better simulation of beam junctions by introducing penalized segments.
reset_penalized_beams()
¶
Revert the penalization modifications made by set_penalized_beams. This involves: - Rewiring beams to connect original nodes directly, bypassing penalized segments. - Removing penalized beams and any orphaned nodes. Note: This operation is only valid if the lattice has been previously penalized.
apply_constraints_nodes(surfaces, value, DOF, type_constraint='Displacement', surface_cells=None)
¶
Apply boundary conditions to the lattice
Parameters:¶
surfaces: list[str] List of surfaces to apply constraint (e.g., [“Xmin”, “Xmax”, “Ymin”])
list of float
Values to apply to the constraint
list of int
Degree of freedom to apply constraint (0: x, 1: y, 2: z, 3: Rx, 4: Ry, 5: Rz)
str
Type of constraint (Displacement, Force)
list[str], optional
List of surfaces to find points on cells (e.g., [“Xmin”, “Xmax”, “Ymin”]). If None, uses surfaceNames.
set_boundary_conditions()
¶
Set boundary conditions on the lattice.
get_global_displacement(withFixed=False, OnlyImposed=False)
¶
Get global displacement of the lattice Parameters:
withFixed: bool If True, return displacement including fixed DOF OnlyImposed: bool If True, only return imposed displacement, else return all displacement
Returns:¶
globalDisplacement: dict Dictionary of global displacement with index_boundary as key and displacement vector as value globalDisplacementIndex: list List of boundary index per DOF (optional info)
define_node_index_boundary()
¶
Define boundary tag for all boundary nodes and calculate the total number of boundary nodes
get_global_reaction_force(appliedForceAdded=False)
¶
get_global_reaction_force_without_fixed_DOF(globalReactionForce, rightHandSide=False)
¶
Get global reaction force of the lattice without fixed DOF
Parameters:¶
globalReactionForce: dict Dictionary of global reaction force with index_boundary as key and reaction force vector as value
bool
If True, get applied forces (right-hand side), else get reaction forces
Returns:¶
y: np.ndarray Array of global reaction force without fixed DOF
define_free_DOF()
¶
Get total number of degrees of freedom in the lattice
set_global_free_DOF_index()
¶
Set global free degree of freedom index for all nodes in boundary
get_global_displacement_DDM(OnlyImposed=False)
¶
evaluate_alphas_linear_surrogate(geometric_params)
¶
Robust linear surrogate with safe extrapolation
• 1D: np.interp (fast, stable). • ND: LinearNDInterpolator inside convex hull; fallback to NearestNDInterpolator outside.
define_parameters(enable_precondioner=True, numberIterationMax=1000)
¶
Define parameters for the domain decomposition solver.
enable_preconditioner: bool Enable the preconditioner for the conjugate gradient solver. number_iteration_max: int Maximum number of iterations for the conjugate gradient solver.
build_coupling_operator_cells()
¶
Build coupling operator for each cell in the lattice
calculate_schur_complement_cells()
¶
Calculate the Schur complement for each cell in the lattice. Batch all unique radius cases per geometry and compute them at once.
get_schur_complement_from_reduced_basis_batch(geometric_params_list)
¶
Vectorized version: compute Schur complements for many queries in one GEMM (faster than many GEMVs).
Parameters¶
geometric_params_list : list of list of float Each inner list is a set of geometric parameters for one query.
Returns¶
schur_batch : np.ndarray Array of shape (n_queries, n_schur, n_schur) with Fortran-ordered per-matrix layout.
get_schur_complement_from_reduced_basis(geometric_params)
¶
solve_DDM()
¶
Solve the problem with the domain decomposition method.
calculate_reaction_force_global(globalDisplacement, rightHandSide=False)
¶
Calculate the global reaction force of the lattice
Parameters:¶
globalDisplacement: np.ndarray The global displacement vector. rightHandSide: bool If True, get applied forces (right-hand side), else get reaction forces.
update_reaction_force_each_cell(global_displacement)
¶
solve_sub_problem(cell)
¶
Solve the subproblem on a cell to get the reaction force
cg_progress(xk, b, A_operator)
¶
Callback function to track and plot progress of the CG method.
Parameters:¶
xk: np.array The current solution vector at the k-th iteration.
np.array
The right-hand side vector of the system.
callable or matrix
The operator or matrix for the system Ax = b.
define_preconditioner()
¶
Define the preconditioner for the conjugate gradient solver.
build_preconditioner()
¶
Build a sparse LU/ILU preconditioner of the global Schur complement. Faster assembly by accumulating triplets and avoiding dense ops.
reset_cell_with_new_radii(new_radii, index_cell=0)
¶
Reset cell with new radii for each beam type WARNING: BUG for multiple geometry cells
Parameters:¶
new_radii: list of float List of new radii for each beam type
int
Index of the cell to reset
get_global_force_displacement_curve(dof=2)
¶
Aggregate global force (sum of reactions) vs imposed displacement for comparison with experiment.
Parameters¶
dof : int Degree of freedom to extract (default=2 for Z direction).
Returns¶
disp : np.ndarray Imposed displacement values (at the loading boundary nodes).
np.ndarray
Total reaction force corresponding to that displacement.
open_lattice_parameters(file_name)
¶
Open a JSON file containing lattice parameters.
Parameters:¶
file_name: str Name of the JSON file containing lattice parameters.
load_reduced_basis(lattice_object_sim, tol_greedy)
¶
Load a previously saved reduced basis based on the lattice simulation parameters and tolerance.
Parameters¶
lattice_object_sim : LatticeSim The lattice simulation object containing parameters.
float
Tolerance used in the greedy algorithm.
Returns¶
dict A dictionary containing the loaded reduced basis and related data.
get_schur_complement(lattice, cell_index=None)
¶
Calculate the Schur complement of the stiffness matrix for a given lattice.
Parameters:¶
lattice: Lattice object The lattice structure to be analyzed.
int, optional
The index of the cell to be used for the Schur complement calculation. If None, the first cell is used.
conjugate_gradient_solver(A_operator, b, M=None, maxiter=100, tol=1e-05, mintol=1e-05, restart_every=1000, alpha_max=0.1, callback=None)
¶
Solve the system Ax = b using the Conjugate Gradient method.
Parameters¶
A_operator : callable Function that computes the matrix-vector product Ax.
array_like
Right-hand side vector.
array_like, optional
Preconditioner matrix (if None, no preconditioning is applied).
int, optional
Maximum number of iterations (default is 100).
float, optional
Tolerance for convergence (default is 1e-5).
float, optional
Minimum value of residue (default is 1e-5).
int, optional
Number of iterations after which to restart the search direction (default is 5).
float, optional
Maximum step size for the search direction (default is 1).
callable, optional
Function to call after each iteration with the current solution.
solve_FEM_cell(lattice, cell)
¶
Solve the finite element method problem for a specific cell in the lattice using FenicsX.
Parameters:¶
lattice: Lattice object The lattice structure to be simulated.
object
The specific cell within the lattice to be analyzed.
_import_scipy_sparse()
¶
coo_matrix(*args, **kwargs)
¶
LinearOperator(*args, **kwargs)
¶
splu(A, *args, **kwargs)
¶
spilu(A, *args, **kwargs)
¶
_import_sklearn_neighbors()
¶
pyLatticeSim.simulation_base
¶
Classes:
| Name | Description |
|---|---|
SimulationBase |
Parent class with all utilities to compute simulation in FenicsX |
Functions:
| Name | Description |
|---|---|
_import_dolfinx_fem_common |
|
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
timing = Timing()
module-attribute
¶
SimulationBase
¶
Parent class with all utilities to compute simulation in FenicsX
Methods:
| Name | Description |
|---|---|
prepare_simulation |
Initialize the simulation requisites |
define_test_trial_function |
Define Test and Trial Function from function space |
calculate_stress_strain |
Calculate stress and strain |
calculate_stress_grad |
Calculate stress gradient |
generalized_stress |
Calculate stress from a fem.Function |
generalized_stress_grad |
Calculate stress gradient from a fem.Function |
generalized_strains |
Calculate strain from a fem.Function |
calculate_forces |
Extract force components |
calculate_moments |
Extract moments components |
tgrad |
Calculate tangential gradient |
define_measures |
Define measures with subdomain data |
define_mixed_function_space |
Define Mixed function space with ufl library |
define_K_form |
Define K_form |
define_K_form_grad |
Define K_formGrad |
define_L_form_null |
Define L_form as null |
apply_force_at_node |
Apply a concentrated force at a specific node. |
apply_displacement_at_node |
Applying displacement at a node with a specific tag |
apply_constraint_at_node |
Apply a constraint at a specific node. |
apply_all_boundary_condition_on_lattice |
Apply all boundary conditions on the lattice |
apply_all_boundary_condition_on_cell_without_distinction |
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. |
apply_displacement_at_node_all_DOF |
Applying displacement at a node with a specific tag |
find_boundary_tags |
Find all tag with a node on the boundary of the unit cell |
solve_problem |
Solve the problem with a linear solver |
calculate_reaction_force |
Calculate reaction force on node_tag on macro coordinates basis |
calculate_reaction_force_and_moment_at_position |
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). |
calculate_reaction_force_and_moment |
Calculate reaction force and moment at a node on the macro coordinate basis |
calculate_reaction_force_and_moment_all_boundary_nodes |
Calculate reaction force on all boundary nodes |
calculate_energy_cell |
Calculate the energy in the cell based on the displacement vector. |
calculate_strain_energy |
Compute the strain energy in the lattice cell. |
calculate_strain_energy_grad |
Compute the strain energy gradient in the lattice cell. |
extract_stress_field |
Extract and interpolate the stress field in the structure after solving the problem. |
print_timers |
Print all accumulated timers with wall-clock time. |
prepare_simulation()
¶
Initialize the simulation requisites
define_test_trial_function()
¶
Define Test and Trial Function from function space
calculate_stress_strain()
¶
Calculate stress and strain
calculate_stress_grad()
¶
Calculate stress gradient
generalized_stress_grad(u)
¶
calculate_forces(u)
¶
Extract force components
calculate_moments(u)
¶
Extract moments components
tgrad(u)
¶
Calculate tangential gradient
define_measures()
¶
Define measures with subdomain data
define_mixed_function_space(element_type)
¶
Define Mixed function space with ufl library
Parameters¶
element_type: Tuple[str, str] => (elementType, elementType) Element type for each element of the function space
define_K_form()
¶
Define K_form
define_K_form_grad()
¶
Define K_formGrad
define_L_form_null()
¶
Define L_form as null
apply_force_at_node(node_tag, forceValue, dofIdx)
¶
Apply a concentrated force at a specific node.
Parameters:¶
node_tag: int Tag identifying the node.
float
The value of the force.
int
The degree of freedom where the force is applied
apply_displacement_at_node(node_tag, displacementValue, dofIdx)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
float
Displacement value to apply at the node
int
Between 0 and 5: the degree of freedom where move is apply
apply_constraint_at_node(node_tag, value_constraint, dof_idx, type_constraint)
¶
Apply a constraint at a specific node.
Parameters:¶
node_tag: int Tag identifying the node. value_constraint: float The value of the constraint (displacement or force). dof_idx: int The degree of freedom index (0-5) where the constraint is applied. type_constraint: str Type of constraint: “Displacement” or “Force”.
apply_all_boundary_condition_on_lattice(cell_only=None)
¶
Apply all boundary conditions on the lattice
Parameters:¶
cell_only: Cell, optional If specified, only apply boundary conditions on this cell
apply_all_boundary_condition_on_cell_without_distinction(cellToApply)
¶
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. Here we always impose the current node.displacement_vector on each boundary DOF of the target cell.
Parameters:¶
cellToApply: Cell The cell on which to apply the boundary conditions
apply_displacement_at_node_all_DOF(node_tag, displacementVector)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
list of float
Displacement value to apply at the node
find_boundary_tags()
¶
Find all tag with a node on the boundary of the unit cell
solve_problem()
¶
Solve the problem with a linear solver
Uses PETSc KSP solver with LU preconditioner. This implementation allows to add true nodal point loads collected in self._point_loads before calling this method.
calculate_reaction_force(node_tag, solution=None)
¶
Calculate reaction force on node_tag on macro coordinates basis with strategy 2 : https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : integer The node tag where reaction force is calculated
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
Returns:¶
f : np.ndarray The reaction force vector (3 components).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_at_position(position, solution=None, tol=1e-08)
¶
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). Avoids locate_dofs_geometrical on subspaces by collapsing subspaces to get dof coords, then mapping back to the original subspace indices.
Parameters:¶
position : np.ndarray The (x, y, z) position where the reaction force and moment are calculated.
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
float, optional
Tolerance for matching DOF coordinates to the specified position.
calculate_reaction_force_and_moment(node_tag)
¶
Calculate reaction force and moment at a node on the macro coordinate basis using strategy 2: https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : int The node tag where the reaction force and moment are calculated.
Returns:¶
arrayOfReaction : list[float] The six components of the reaction (3 forces, 3 moments).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_all_boundary_nodes(cell, full_nodes=False)
¶
Calculate reaction force on all boundary nodes
Parameters:¶
cell : Cell The cell containing the nodes. full_nodes : bool, optional If True, include zero reaction forces for non-boundary nodes.
calculate_energy_cell(displacement)
¶
Calculate the energy in the cell based on the displacement vector.
Parameters:¶
displacement : list of float The displacement vector at the boundary nodes.
calculate_strain_energy()
¶
Compute the strain energy in the lattice cell.
Returns:¶
W : float Total strain energy stored in the cell.
calculate_strain_energy_grad()
¶
Compute the strain energy gradient in the lattice cell.
Returns:¶
WGrad : float Total strain energy gradient stored in the cell.
extract_stress_field()
¶
Extract and interpolate the stress field in the structure after solving the problem.
Returns:¶
stress_function: fem.Function The stress field interpolated into the function space for visualization or post-processing.
print_timers()
¶
Print all accumulated timers with wall-clock time.
_import_dolfinx_fem_common()
¶
pyLatticeSim.lattice_generation
¶
Classes:
| Name | Description |
|---|---|
latticeGeneration |
Meshing of lattice structures with GMSH from class Lattice |
Functions:
| Name | Description |
|---|---|
_import_dolfinx_gmshio |
|
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
timing = Timing()
module-attribute
¶
latticeGeneration
¶
Meshing of lattice structures with GMSH from class Lattice
Parameter:¶
Lattice: Lattice class object Object that contains all information of lattice structures
Methods:
| Name | Description |
|---|---|
find_mesh_size |
Determine mesh size |
mesh_lattice_cells |
Meshing lattice structures with node tags and beam tags |
generate_nodes |
Generate nodes in the structures with tags associated |
generate_beams |
Generate beams in the structures with tags associated |
generate_beams_tags |
Generate tags for beam elements |
generate_points_tags |
Generate points tags with normalized procedure |
find_mesh_size(mesh_element_lenght=0.05)
¶
Determine mesh size Function to be updated for better adaptive meshing
Parameters:¶
mesh_element_lenght: float Length of mesh element in unit of lattice cell size
mesh_lattice_cells(cell_index, mesh_element_lenght=0.05, save_mesh=True)
¶
Meshing lattice structures with node tags and beam tags
Parameters:¶
cell_index: int Index of the cell to mesh. If None, all cells are meshed.
float
Length of mesh element in unit of lattice cell size
bool
If True, save the mesh in a .msh file
generate_nodes(cell_index=None)
¶
Generate nodes in the structures with tags associated
Parameters:¶
nodes: list of node object from lattice class
generate_beams(cell_index=None)
¶
generate_beams_tags()
¶
Generate tags for beam elements
generate_points_tags()
¶
Generate points tags with normalized procedure
_import_dolfinx_gmshio()
¶
pyLatticeSim.beam_model
¶
Classes:
| Name | Description |
|---|---|
latticeGeneration |
Meshing of lattice structures with GMSH from class Lattice |
Material |
Encapsulates all material properties for a lattice structure. |
MatProperties |
A class to represent the properties of a material loaded from a file. |
BeamModel |
Class to define a beam model for FenicsX analysis from a lattice geometry. |
Functions:
| Name | Description |
|---|---|
_import_dolfinx |
|
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
timing = Timing()
module-attribute
¶
latticeGeneration
¶
Meshing of lattice structures with GMSH from class Lattice
Parameter:¶
Lattice: Lattice class object Object that contains all information of lattice structures
Methods:
| Name | Description |
|---|---|
find_mesh_size |
Determine mesh size |
mesh_lattice_cells |
Meshing lattice structures with node tags and beam tags |
generate_nodes |
Generate nodes in the structures with tags associated |
generate_beams |
Generate beams in the structures with tags associated |
generate_beams_tags |
Generate tags for beam elements |
generate_points_tags |
Generate points tags with normalized procedure |
find_mesh_size(mesh_element_lenght=0.05)
¶
Determine mesh size Function to be updated for better adaptive meshing
Parameters:¶
mesh_element_lenght: float Length of mesh element in unit of lattice cell size
mesh_lattice_cells(cell_index, mesh_element_lenght=0.05, save_mesh=True)
¶
Meshing lattice structures with node tags and beam tags
Parameters:¶
cell_index: int Index of the cell to mesh. If None, all cells are meshed.
float
Length of mesh element in unit of lattice cell size
bool
If True, save the mesh in a .msh file
generate_nodes(cell_index=None)
¶
Generate nodes in the structures with tags associated
Parameters:¶
nodes: list of node object from lattice class
generate_beams(cell_index=None)
¶
generate_beams_tags()
¶
Generate tags for beam elements
generate_points_tags()
¶
Generate points tags with normalized procedure
Material
¶
Encapsulates all material properties for a lattice structure.
Methods:
| Name | Description |
|---|---|
set_material |
Define material properties for linear behavior based on material_name. |
set_density |
Define material density. |
compute_mechanical_properties |
Compute mechanical properties based on the beam radius. |
compute_gradient |
Compute the gradient of mechanical properties, considering penalization. |
Attributes:
| Name | Type | Description |
|---|---|---|
properties_for_stress |
Return mechanical properties as a vector for stress calculations. |
|
properties_for_stress_gradient |
Return gradient of mechanical properties as a vector. |
properties_for_stress
property
¶
Return mechanical properties as a vector for stress calculations.
properties_for_stress_gradient
property
¶
Return gradient of mechanical properties as a vector.
set_material(lattice_material)
¶
Define material properties for linear behavior based on material_name.
set_density(density)
¶
Define material density.
compute_mechanical_properties(radius)
¶
Compute mechanical properties based on the beam radius.
compute_gradient(radius, tagBeam, lattice)
¶
Compute the gradient of mechanical properties, considering penalization. Vectorized version for performance.
MatProperties
¶
A class to represent the properties of a material loaded from a file.
Methods:
| Name | Description |
|---|---|
__init__ |
Initialize the MatProperties object by loading data from a file. |
load_material |
Loads material properties from a JSON file. |
BeamModel
¶
Class to define a beam model for FenicsX analysis from a lattice geometry.
Parameters¶
COMM : MPI communicator MPI communicator for parallel computing
LatticeObject
Lattice object from pyLatticeDesign
int, optional
Index of the cell to generate the mesh for. If None, the entire lattice mesh is generated.
Methods:
| Name | Description |
|---|---|
define_model |
Initialize the beam model |
open_lattice_geometry |
Open geometry from GMSH mesh file. |
generate_mesh |
Generate the mesh of the lattice or a specific cell |
define_radius |
Define radius values from a dictionary |
define_mechanical_properties |
Compute and set mechanical properties for the beam |
define_beam_geometry_data_circular_gradient |
Define beam geometry data for circular gradient |
define_material_model |
Define all material properties with preset data |
calculate_local_coordinate_system |
Calculate local coordinate system on each beam of the mesh |
Attributes:
| Name | Type | Description |
|---|---|---|
material |
Returns material properties |
material
property
¶
Returns material properties
define_model(lattice, cellIndex=None)
¶
Initialize the beam model
Parameters¶
lattice : Lattice The lattice object containing the mesh generation parameters.
int, optional
Index of the cell to generate the mesh for. If None, the entire lattice mesh is generated.
open_lattice_geometry(name_lattice_geometry)
¶
Open geometry from GMSH mesh file.
Parameters¶
name_lattice_geometry : str Name of the GMSH mesh file (should end with .msh).
generate_mesh(lattice, cell_index=None)
¶
Generate the mesh of the lattice or a specific cell
Parameters¶
lattice : LatticeObject The lattice object containing the mesh generation parameters.
int, optional
Index of the cell to generate the mesh for. If None, the entire lattice mesh is generated.
define_radius(radius_dict=None)
¶
Define radius values from a dictionary
Parameters¶
radius_dict : dict, optional Dictionary containing radius values keyed by beam tags.
define_mechanical_properties()
¶
Compute and set mechanical properties for the beam
define_beam_geometry_data_circular_gradient()
¶
Define beam geometry data for circular gradient
define_material_model(lattice)
¶
Define all material properties with preset data
calculate_local_coordinate_system()
¶
Calculate local coordinate system on each beam of the mesh
_import_dolfinx()
¶
pyLatticeSim.material_definition
¶
Classes:
| Name | Description |
|---|---|
MatProperties |
A class to represent the properties of a material loaded from a file. |
Material |
Encapsulates all material properties for a lattice structure. |
Functions:
| Name | Description |
|---|---|
_import_dolfinx_fem |
|
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
timing = Timing()
module-attribute
¶
MatProperties
¶
A class to represent the properties of a material loaded from a file.
Methods:
| Name | Description |
|---|---|
__init__ |
Initialize the MatProperties object by loading data from a file. |
load_material |
Loads material properties from a JSON file. |
Material
¶
Encapsulates all material properties for a lattice structure.
Methods:
| Name | Description |
|---|---|
set_material |
Define material properties for linear behavior based on material_name. |
set_density |
Define material density. |
compute_mechanical_properties |
Compute mechanical properties based on the beam radius. |
compute_gradient |
Compute the gradient of mechanical properties, considering penalization. |
Attributes:
| Name | Type | Description |
|---|---|---|
properties_for_stress |
Return mechanical properties as a vector for stress calculations. |
|
properties_for_stress_gradient |
Return gradient of mechanical properties as a vector. |
properties_for_stress
property
¶
Return mechanical properties as a vector for stress calculations.
properties_for_stress_gradient
property
¶
Return gradient of mechanical properties as a vector.
set_material(lattice_material)
¶
Define material properties for linear behavior based on material_name.
set_density(density)
¶
Define material density.
compute_mechanical_properties(radius)
¶
Compute mechanical properties based on the beam radius.
compute_gradient(radius, tagBeam, lattice)
¶
Compute the gradient of mechanical properties, considering penalization. Vectorized version for performance.
_import_dolfinx_fem()
¶
pyLatticeSim.schur_complement
¶
Classes:
| Name | Description |
|---|---|
SimulationBase |
Parent class with all utilities to compute simulation in FenicsX |
SchurComplement |
Class to perform Schur Complement calculations on a given BeamModel. |
Functions:
| Name | Description |
|---|---|
_import_dolfinx_fem |
|
_import_petsc4py |
|
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
|
fem |
|
|
PETSc |
|
timing = Timing()
module-attribute
¶
fem = _import_dolfinx_fem()
module-attribute
¶
PETSc = _import_petsc4py()
module-attribute
¶
SimulationBase
¶
Parent class with all utilities to compute simulation in FenicsX
Methods:
| Name | Description |
|---|---|
prepare_simulation |
Initialize the simulation requisites |
define_test_trial_function |
Define Test and Trial Function from function space |
calculate_stress_strain |
Calculate stress and strain |
calculate_stress_grad |
Calculate stress gradient |
generalized_stress |
Calculate stress from a fem.Function |
generalized_stress_grad |
Calculate stress gradient from a fem.Function |
generalized_strains |
Calculate strain from a fem.Function |
calculate_forces |
Extract force components |
calculate_moments |
Extract moments components |
tgrad |
Calculate tangential gradient |
define_measures |
Define measures with subdomain data |
define_mixed_function_space |
Define Mixed function space with ufl library |
define_K_form |
Define K_form |
define_K_form_grad |
Define K_formGrad |
define_L_form_null |
Define L_form as null |
apply_force_at_node |
Apply a concentrated force at a specific node. |
apply_displacement_at_node |
Applying displacement at a node with a specific tag |
apply_constraint_at_node |
Apply a constraint at a specific node. |
apply_all_boundary_condition_on_lattice |
Apply all boundary conditions on the lattice |
apply_all_boundary_condition_on_cell_without_distinction |
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. |
apply_displacement_at_node_all_DOF |
Applying displacement at a node with a specific tag |
find_boundary_tags |
Find all tag with a node on the boundary of the unit cell |
solve_problem |
Solve the problem with a linear solver |
calculate_reaction_force |
Calculate reaction force on node_tag on macro coordinates basis |
calculate_reaction_force_and_moment_at_position |
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). |
calculate_reaction_force_and_moment |
Calculate reaction force and moment at a node on the macro coordinate basis |
calculate_reaction_force_and_moment_all_boundary_nodes |
Calculate reaction force on all boundary nodes |
calculate_energy_cell |
Calculate the energy in the cell based on the displacement vector. |
calculate_strain_energy |
Compute the strain energy in the lattice cell. |
calculate_strain_energy_grad |
Compute the strain energy gradient in the lattice cell. |
extract_stress_field |
Extract and interpolate the stress field in the structure after solving the problem. |
print_timers |
Print all accumulated timers with wall-clock time. |
prepare_simulation()
¶
Initialize the simulation requisites
define_test_trial_function()
¶
Define Test and Trial Function from function space
calculate_stress_strain()
¶
Calculate stress and strain
calculate_stress_grad()
¶
Calculate stress gradient
generalized_stress_grad(u)
¶
calculate_forces(u)
¶
Extract force components
calculate_moments(u)
¶
Extract moments components
tgrad(u)
¶
Calculate tangential gradient
define_measures()
¶
Define measures with subdomain data
define_mixed_function_space(element_type)
¶
Define Mixed function space with ufl library
Parameters¶
element_type: Tuple[str, str] => (elementType, elementType) Element type for each element of the function space
define_K_form()
¶
Define K_form
define_K_form_grad()
¶
Define K_formGrad
define_L_form_null()
¶
Define L_form as null
apply_force_at_node(node_tag, forceValue, dofIdx)
¶
Apply a concentrated force at a specific node.
Parameters:¶
node_tag: int Tag identifying the node.
float
The value of the force.
int
The degree of freedom where the force is applied
apply_displacement_at_node(node_tag, displacementValue, dofIdx)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
float
Displacement value to apply at the node
int
Between 0 and 5: the degree of freedom where move is apply
apply_constraint_at_node(node_tag, value_constraint, dof_idx, type_constraint)
¶
Apply a constraint at a specific node.
Parameters:¶
node_tag: int Tag identifying the node. value_constraint: float The value of the constraint (displacement or force). dof_idx: int The degree of freedom index (0-5) where the constraint is applied. type_constraint: str Type of constraint: “Displacement” or “Force”.
apply_all_boundary_condition_on_lattice(cell_only=None)
¶
Apply all boundary conditions on the lattice
Parameters:¶
cell_only: Cell, optional If specified, only apply boundary conditions on this cell
apply_all_boundary_condition_on_cell_without_distinction(cellToApply)
¶
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. Here we always impose the current node.displacement_vector on each boundary DOF of the target cell.
Parameters:¶
cellToApply: Cell The cell on which to apply the boundary conditions
apply_displacement_at_node_all_DOF(node_tag, displacementVector)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
list of float
Displacement value to apply at the node
find_boundary_tags()
¶
Find all tag with a node on the boundary of the unit cell
solve_problem()
¶
Solve the problem with a linear solver
Uses PETSc KSP solver with LU preconditioner. This implementation allows to add true nodal point loads collected in self._point_loads before calling this method.
calculate_reaction_force(node_tag, solution=None)
¶
Calculate reaction force on node_tag on macro coordinates basis with strategy 2 : https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : integer The node tag where reaction force is calculated
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
Returns:¶
f : np.ndarray The reaction force vector (3 components).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_at_position(position, solution=None, tol=1e-08)
¶
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). Avoids locate_dofs_geometrical on subspaces by collapsing subspaces to get dof coords, then mapping back to the original subspace indices.
Parameters:¶
position : np.ndarray The (x, y, z) position where the reaction force and moment are calculated.
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
float, optional
Tolerance for matching DOF coordinates to the specified position.
calculate_reaction_force_and_moment(node_tag)
¶
Calculate reaction force and moment at a node on the macro coordinate basis using strategy 2: https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : int The node tag where the reaction force and moment are calculated.
Returns:¶
arrayOfReaction : list[float] The six components of the reaction (3 forces, 3 moments).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_all_boundary_nodes(cell, full_nodes=False)
¶
Calculate reaction force on all boundary nodes
Parameters:¶
cell : Cell The cell containing the nodes. full_nodes : bool, optional If True, include zero reaction forces for non-boundary nodes.
calculate_energy_cell(displacement)
¶
Calculate the energy in the cell based on the displacement vector.
Parameters:¶
displacement : list of float The displacement vector at the boundary nodes.
calculate_strain_energy()
¶
Compute the strain energy in the lattice cell.
Returns:¶
W : float Total strain energy stored in the cell.
calculate_strain_energy_grad()
¶
Compute the strain energy gradient in the lattice cell.
Returns:¶
WGrad : float Total strain energy gradient stored in the cell.
extract_stress_field()
¶
Extract and interpolate the stress field in the structure after solving the problem.
Returns:¶
stress_function: fem.Function The stress field interpolated into the function space for visualization or post-processing.
print_timers()
¶
Print all accumulated timers with wall-clock time.
SchurComplement
¶
Bases: SimulationBase
Class to perform Schur Complement calculations on a given BeamModel.
Parameters:¶
BeamModel : BeamModel The beam model to perform the Schur Complement calculation on.
Methods:
| Name | Description |
|---|---|
construct_K |
Construct K matrix from variational form |
calculate_schur_complement |
Calculate the Schur complement of the stiffness matrix. |
_import_dolfinx_fem()
¶
_import_petsc4py()
¶
pyLatticeSim.conjugate_gradient_solver
¶
Functions:
| Name | Description |
|---|---|
conjugate_gradient_solver |
Solve the system Ax = b using the Conjugate Gradient method. |
conjugate_gradient_solver(A_operator, b, M=None, maxiter=100, tol=1e-05, mintol=1e-05, restart_every=1000, alpha_max=0.1, callback=None)
¶
Solve the system Ax = b using the Conjugate Gradient method.
Parameters¶
A_operator : callable Function that computes the matrix-vector product Ax.
array_like
Right-hand side vector.
array_like, optional
Preconditioner matrix (if None, no preconditioning is applied).
int, optional
Maximum number of iterations (default is 100).
float, optional
Tolerance for convergence (default is 1e-5).
float, optional
Minimum value of residue (default is 1e-5).
int, optional
Number of iterations after which to restart the search direction (default is 5).
float, optional
Maximum step size for the search direction (default is 1).
callable, optional
Function to call after each iteration with the current solution.
pyLatticeSim.full_scale_lattice_simulation
¶
Classes:
| Name | Description |
|---|---|
SimulationBase |
Parent class with all utilities to compute simulation in FenicsX |
FullScaleLatticeSimulation |
A class to handle full-scale lattice simulation using FenicsX. |
Functions:
| Name | Description |
|---|---|
_import_dolfinx_fem |
|
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
|
fem |
|
timing = Timing()
module-attribute
¶
fem = _import_dolfinx_fem()
module-attribute
¶
SimulationBase
¶
Parent class with all utilities to compute simulation in FenicsX
Methods:
| Name | Description |
|---|---|
prepare_simulation |
Initialize the simulation requisites |
define_test_trial_function |
Define Test and Trial Function from function space |
calculate_stress_strain |
Calculate stress and strain |
calculate_stress_grad |
Calculate stress gradient |
generalized_stress |
Calculate stress from a fem.Function |
generalized_stress_grad |
Calculate stress gradient from a fem.Function |
generalized_strains |
Calculate strain from a fem.Function |
calculate_forces |
Extract force components |
calculate_moments |
Extract moments components |
tgrad |
Calculate tangential gradient |
define_measures |
Define measures with subdomain data |
define_mixed_function_space |
Define Mixed function space with ufl library |
define_K_form |
Define K_form |
define_K_form_grad |
Define K_formGrad |
define_L_form_null |
Define L_form as null |
apply_force_at_node |
Apply a concentrated force at a specific node. |
apply_displacement_at_node |
Applying displacement at a node with a specific tag |
apply_constraint_at_node |
Apply a constraint at a specific node. |
apply_all_boundary_condition_on_lattice |
Apply all boundary conditions on the lattice |
apply_all_boundary_condition_on_cell_without_distinction |
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. |
apply_displacement_at_node_all_DOF |
Applying displacement at a node with a specific tag |
find_boundary_tags |
Find all tag with a node on the boundary of the unit cell |
solve_problem |
Solve the problem with a linear solver |
calculate_reaction_force |
Calculate reaction force on node_tag on macro coordinates basis |
calculate_reaction_force_and_moment_at_position |
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). |
calculate_reaction_force_and_moment |
Calculate reaction force and moment at a node on the macro coordinate basis |
calculate_reaction_force_and_moment_all_boundary_nodes |
Calculate reaction force on all boundary nodes |
calculate_energy_cell |
Calculate the energy in the cell based on the displacement vector. |
calculate_strain_energy |
Compute the strain energy in the lattice cell. |
calculate_strain_energy_grad |
Compute the strain energy gradient in the lattice cell. |
extract_stress_field |
Extract and interpolate the stress field in the structure after solving the problem. |
print_timers |
Print all accumulated timers with wall-clock time. |
prepare_simulation()
¶
Initialize the simulation requisites
define_test_trial_function()
¶
Define Test and Trial Function from function space
calculate_stress_strain()
¶
Calculate stress and strain
calculate_stress_grad()
¶
Calculate stress gradient
generalized_stress_grad(u)
¶
calculate_forces(u)
¶
Extract force components
calculate_moments(u)
¶
Extract moments components
tgrad(u)
¶
Calculate tangential gradient
define_measures()
¶
Define measures with subdomain data
define_mixed_function_space(element_type)
¶
Define Mixed function space with ufl library
Parameters¶
element_type: Tuple[str, str] => (elementType, elementType) Element type for each element of the function space
define_K_form()
¶
Define K_form
define_K_form_grad()
¶
Define K_formGrad
define_L_form_null()
¶
Define L_form as null
apply_force_at_node(node_tag, forceValue, dofIdx)
¶
Apply a concentrated force at a specific node.
Parameters:¶
node_tag: int Tag identifying the node.
float
The value of the force.
int
The degree of freedom where the force is applied
apply_displacement_at_node(node_tag, displacementValue, dofIdx)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
float
Displacement value to apply at the node
int
Between 0 and 5: the degree of freedom where move is apply
apply_constraint_at_node(node_tag, value_constraint, dof_idx, type_constraint)
¶
Apply a constraint at a specific node.
Parameters:¶
node_tag: int Tag identifying the node. value_constraint: float The value of the constraint (displacement or force). dof_idx: int The degree of freedom index (0-5) where the constraint is applied. type_constraint: str Type of constraint: “Displacement” or “Force”.
apply_all_boundary_condition_on_lattice(cell_only=None)
¶
Apply all boundary conditions on the lattice
Parameters:¶
cell_only: Cell, optional If specified, only apply boundary conditions on this cell
apply_all_boundary_condition_on_cell_without_distinction(cellToApply)
¶
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. Here we always impose the current node.displacement_vector on each boundary DOF of the target cell.
Parameters:¶
cellToApply: Cell The cell on which to apply the boundary conditions
apply_displacement_at_node_all_DOF(node_tag, displacementVector)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
list of float
Displacement value to apply at the node
find_boundary_tags()
¶
Find all tag with a node on the boundary of the unit cell
solve_problem()
¶
Solve the problem with a linear solver
Uses PETSc KSP solver with LU preconditioner. This implementation allows to add true nodal point loads collected in self._point_loads before calling this method.
calculate_reaction_force(node_tag, solution=None)
¶
Calculate reaction force on node_tag on macro coordinates basis with strategy 2 : https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : integer The node tag where reaction force is calculated
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
Returns:¶
f : np.ndarray The reaction force vector (3 components).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_at_position(position, solution=None, tol=1e-08)
¶
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). Avoids locate_dofs_geometrical on subspaces by collapsing subspaces to get dof coords, then mapping back to the original subspace indices.
Parameters:¶
position : np.ndarray The (x, y, z) position where the reaction force and moment are calculated.
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
float, optional
Tolerance for matching DOF coordinates to the specified position.
calculate_reaction_force_and_moment(node_tag)
¶
Calculate reaction force and moment at a node on the macro coordinate basis using strategy 2: https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : int The node tag where the reaction force and moment are calculated.
Returns:¶
arrayOfReaction : list[float] The six components of the reaction (3 forces, 3 moments).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_all_boundary_nodes(cell, full_nodes=False)
¶
Calculate reaction force on all boundary nodes
Parameters:¶
cell : Cell The cell containing the nodes. full_nodes : bool, optional If True, include zero reaction forces for non-boundary nodes.
calculate_energy_cell(displacement)
¶
Calculate the energy in the cell based on the displacement vector.
Parameters:¶
displacement : list of float The displacement vector at the boundary nodes.
calculate_strain_energy()
¶
Compute the strain energy in the lattice cell.
Returns:¶
W : float Total strain energy stored in the cell.
calculate_strain_energy_grad()
¶
Compute the strain energy gradient in the lattice cell.
Returns:¶
WGrad : float Total strain energy gradient stored in the cell.
extract_stress_field()
¶
Extract and interpolate the stress field in the structure after solving the problem.
Returns:¶
stress_function: fem.Function The stress field interpolated into the function space for visualization or post-processing.
print_timers()
¶
Print all accumulated timers with wall-clock time.
FullScaleLatticeSimulation
¶
Bases: SimulationBase
A class to handle full-scale lattice simulation using FenicsX.
Methods:
| Name | Description |
|---|---|
apply_displacement_all_nodes_with_lattice_data |
Applying displacement at all nodes with lattice data. |
set_result_diplacement_on_lattice_object |
Assigns the displacement and rotation values from the simulation to the lattice nodes. |
set_reaction_force_on_lattice_with_FEM_results |
Set reaction force on boundary condition nodes with FEM results. |
apply_force_on_all_nodes_with_lattice_data |
Applying force at all nodes with lattice data. |
print_number_DOFs |
Print the total number of degrees of freedom (DOFs) in the simulation. |
apply_displacement_all_nodes_with_lattice_data()
¶
Applying displacement at all nodes with lattice data.
set_result_diplacement_on_lattice_object()
¶
Assigns the displacement and rotation values from the simulation to the lattice nodes.
set_reaction_force_on_lattice_with_FEM_results()
¶
Set reaction force on boundary condition nodes with FEM results.
apply_force_on_all_nodes_with_lattice_data()
¶
Applying force at all nodes with lattice data.
This function applies forces stored in the lattice structure onto the corresponding nodes in the finite element model.
print_number_DOFs()
¶
Print the total number of degrees of freedom (DOFs) in the simulation.
_import_dolfinx_fem()
¶
pyLatticeSim.homogenization_cell
¶
Classes:
| Name | Description |
|---|---|
SimulationBase |
Parent class with all utilities to compute simulation in FenicsX |
HomogenizedCell |
Lattice homogeneization analysis |
Functions:
| Name | Description |
|---|---|
_import_dolfinx_stack |
|
_import_dolfinx_mpc |
|
_import_petsc4py |
|
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
timing = Timing()
module-attribute
¶
SimulationBase
¶
Parent class with all utilities to compute simulation in FenicsX
Methods:
| Name | Description |
|---|---|
prepare_simulation |
Initialize the simulation requisites |
define_test_trial_function |
Define Test and Trial Function from function space |
calculate_stress_strain |
Calculate stress and strain |
calculate_stress_grad |
Calculate stress gradient |
generalized_stress |
Calculate stress from a fem.Function |
generalized_stress_grad |
Calculate stress gradient from a fem.Function |
generalized_strains |
Calculate strain from a fem.Function |
calculate_forces |
Extract force components |
calculate_moments |
Extract moments components |
tgrad |
Calculate tangential gradient |
define_measures |
Define measures with subdomain data |
define_mixed_function_space |
Define Mixed function space with ufl library |
define_K_form |
Define K_form |
define_K_form_grad |
Define K_formGrad |
define_L_form_null |
Define L_form as null |
apply_force_at_node |
Apply a concentrated force at a specific node. |
apply_displacement_at_node |
Applying displacement at a node with a specific tag |
apply_constraint_at_node |
Apply a constraint at a specific node. |
apply_all_boundary_condition_on_lattice |
Apply all boundary conditions on the lattice |
apply_all_boundary_condition_on_cell_without_distinction |
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. |
apply_displacement_at_node_all_DOF |
Applying displacement at a node with a specific tag |
find_boundary_tags |
Find all tag with a node on the boundary of the unit cell |
solve_problem |
Solve the problem with a linear solver |
calculate_reaction_force |
Calculate reaction force on node_tag on macro coordinates basis |
calculate_reaction_force_and_moment_at_position |
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). |
calculate_reaction_force_and_moment |
Calculate reaction force and moment at a node on the macro coordinate basis |
calculate_reaction_force_and_moment_all_boundary_nodes |
Calculate reaction force on all boundary nodes |
calculate_energy_cell |
Calculate the energy in the cell based on the displacement vector. |
calculate_strain_energy |
Compute the strain energy in the lattice cell. |
calculate_strain_energy_grad |
Compute the strain energy gradient in the lattice cell. |
extract_stress_field |
Extract and interpolate the stress field in the structure after solving the problem. |
print_timers |
Print all accumulated timers with wall-clock time. |
prepare_simulation()
¶
Initialize the simulation requisites
define_test_trial_function()
¶
Define Test and Trial Function from function space
calculate_stress_strain()
¶
Calculate stress and strain
calculate_stress_grad()
¶
Calculate stress gradient
generalized_stress_grad(u)
¶
calculate_forces(u)
¶
Extract force components
calculate_moments(u)
¶
Extract moments components
tgrad(u)
¶
Calculate tangential gradient
define_measures()
¶
Define measures with subdomain data
define_mixed_function_space(element_type)
¶
Define Mixed function space with ufl library
Parameters¶
element_type: Tuple[str, str] => (elementType, elementType) Element type for each element of the function space
define_K_form()
¶
Define K_form
define_K_form_grad()
¶
Define K_formGrad
define_L_form_null()
¶
Define L_form as null
apply_force_at_node(node_tag, forceValue, dofIdx)
¶
Apply a concentrated force at a specific node.
Parameters:¶
node_tag: int Tag identifying the node.
float
The value of the force.
int
The degree of freedom where the force is applied
apply_displacement_at_node(node_tag, displacementValue, dofIdx)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
float
Displacement value to apply at the node
int
Between 0 and 5: the degree of freedom where move is apply
apply_constraint_at_node(node_tag, value_constraint, dof_idx, type_constraint)
¶
Apply a constraint at a specific node.
Parameters:¶
node_tag: int Tag identifying the node. value_constraint: float The value of the constraint (displacement or force). dof_idx: int The degree of freedom index (0-5) where the constraint is applied. type_constraint: str Type of constraint: “Displacement” or “Force”.
apply_all_boundary_condition_on_lattice(cell_only=None)
¶
Apply all boundary conditions on the lattice
Parameters:¶
cell_only: Cell, optional If specified, only apply boundary conditions on this cell
apply_all_boundary_condition_on_cell_without_distinction(cellToApply)
¶
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. Here we always impose the current node.displacement_vector on each boundary DOF of the target cell.
Parameters:¶
cellToApply: Cell The cell on which to apply the boundary conditions
apply_displacement_at_node_all_DOF(node_tag, displacementVector)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
list of float
Displacement value to apply at the node
find_boundary_tags()
¶
Find all tag with a node on the boundary of the unit cell
solve_problem()
¶
Solve the problem with a linear solver
Uses PETSc KSP solver with LU preconditioner. This implementation allows to add true nodal point loads collected in self._point_loads before calling this method.
calculate_reaction_force(node_tag, solution=None)
¶
Calculate reaction force on node_tag on macro coordinates basis with strategy 2 : https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : integer The node tag where reaction force is calculated
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
Returns:¶
f : np.ndarray The reaction force vector (3 components).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_at_position(position, solution=None, tol=1e-08)
¶
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). Avoids locate_dofs_geometrical on subspaces by collapsing subspaces to get dof coords, then mapping back to the original subspace indices.
Parameters:¶
position : np.ndarray The (x, y, z) position where the reaction force and moment are calculated.
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
float, optional
Tolerance for matching DOF coordinates to the specified position.
calculate_reaction_force_and_moment(node_tag)
¶
Calculate reaction force and moment at a node on the macro coordinate basis using strategy 2: https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : int The node tag where the reaction force and moment are calculated.
Returns:¶
arrayOfReaction : list[float] The six components of the reaction (3 forces, 3 moments).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_all_boundary_nodes(cell, full_nodes=False)
¶
Calculate reaction force on all boundary nodes
Parameters:¶
cell : Cell The cell containing the nodes. full_nodes : bool, optional If True, include zero reaction forces for non-boundary nodes.
calculate_energy_cell(displacement)
¶
Calculate the energy in the cell based on the displacement vector.
Parameters:¶
displacement : list of float The displacement vector at the boundary nodes.
calculate_strain_energy()
¶
Compute the strain energy in the lattice cell.
Returns:¶
W : float Total strain energy stored in the cell.
calculate_strain_energy_grad()
¶
Compute the strain energy gradient in the lattice cell.
Returns:¶
WGrad : float Total strain energy gradient stored in the cell.
extract_stress_field()
¶
Extract and interpolate the stress field in the structure after solving the problem.
Returns:¶
stress_function: fem.Function The stress field interpolated into the function space for visualization or post-processing.
print_timers()
¶
Print all accumulated timers with wall-clock time.
HomogenizedCell
¶
Bases: SimulationBase
Lattice homogeneization analysis
Parameter:¶
BeamModel : BeamModel class object An object of class BeamModel with beam properties
Methods:
| Name | Description |
|---|---|
calculate_imposed_stress_strain |
Calculate stress and strain from an imposed study case |
find_imposed_strain |
Find imposed strain on domain |
get_imposed_strains |
Calculate strains from imposed displacement domain on dim-6 vectorspace |
locate_Dofs |
Locate degrees of freedom from selected logic function |
define_K_form_boundary |
Define K_form on element tag by markers |
define_L_form |
Define L_form |
periodic_boundary_condition |
Applying periodic boundary condition on unit cell |
initialize_solver |
Initialize solver for multiple RHS solving |
solve_multiple_linear_problem |
Function to solve multiple linear problem with the same LHS |
calculate_BTerm |
Calculate the right-hand side vector for the linear problem. |
calculate_macro_stress |
Calculate macro stress on define boundary tags |
get_logical_function |
Return a logical function for selecting parts of the domain boundary |
apply_dirichlet_for_homogenization |
Apply Dirichlet boundary condition for homogenization |
calculate_generalized_stress |
Calculate generalized stress on a strain case |
solve_full_homogenization |
Solve the entire homogenization of the unit cell |
print_homogenized_matrix |
Print simulation results of 6 loading case |
convert_to_orthotropic_form |
Convert homogenize matrix to orthotropic form |
get_S_orthotropic |
Return orthotropic matrix |
print_orthotropic_form |
Print orthotropic form of homogenization matrix |
compute_errors |
Calculate errors |
print_errors |
Print multiple types of errors in the matrix of simulation results |
calculate_imposed_stress_strain(case)
¶
Calculate stress and strain from an imposed study case
Parameters:¶
case: int from 1 to 6 Strain case for homogenization 1: X direction strain 2: Y direction strain 3: Z direction strain 4: XY direction strain 5: XZ direction strain 6: YZ direction strain
find_imposed_strain(case)
¶
Find imposed strain on domain
Parameters:¶
case: int from 1 to 6 Strain case for homogenization 1: X direction strain 2: Y direction strain 3: Z direction strain 4: XY direction strain 5: XZ direction strain 6: YZ direction strain
Output:¶
w: ufl.vector on domain Strain on domain depending of the strain case
get_imposed_strains(w)
¶
Calculate strains from imposed displacement domain on dim-6 vectorspace
Parameters:¶
w: ufl.as_vector[] dimension (3) Imposed strain
locate_Dofs(selection_function)
¶
Locate degrees of freedom from selected logic function Modified to be applied only on sub(0) => displacement
Parameters:¶
selectionFunction: logicalFunction Logical function to locate entities
define_K_form_boundary(markers=None)
¶
Define K_form on element tag by markers
Parameters:¶
markers: int Markers for boundary conditions, if None then use all boundaries
define_L_form()
¶
Define L_form
periodic_boundary_condition()
¶
Applying periodic boundary condition on unit cell
initialize_solver()
¶
Initialize solver for multiple RHS solving
solve_multiple_linear_problem()
¶
Function to solve multiple linear problem with the same LHS
calculate_BTerm()
¶
Calculate the right-hand side vector for the linear problem.
calculate_macro_stress(case)
¶
get_logical_function(location)
¶
apply_dirichlet_for_homogenization()
¶
Apply Dirichlet boundary condition for homogenization
calculate_generalized_stress(case)
¶
solve_full_homogenization()
¶
Solve the entire homogenization of the unit cell
Output:¶
self.homogenizeMatrix: homogenization matrix
print_homogenized_matrix()
¶
Print simulation results of 6 loading case
convert_to_orthotropic_form()
¶
Convert homogenize matrix to orthotropic form
get_S_orthotropic()
¶
Return orthotropic matrix
print_orthotropic_form()
¶
Print orthotropic form of homogenization matrix
compute_errors()
¶
Calculate errors
print_errors()
¶
Print multiple types of errors in the matrix of simulation results
_import_dolfinx_stack()
¶
_import_dolfinx_mpc()
¶
_import_petsc4py()
¶
pyLatticeSim.greedy_algorithm
¶
Classes:
| Name | Description |
|---|---|
LatticeSim |
|
Functions:
| Name | Description |
|---|---|
_import_scipy_linalg |
|
reduce_basis_greedy |
Generated a reduced basis with a greedy algorithm from a set of projected fields. |
save_reduced_basis |
Save the reduced basis and related data to a .npz file. |
load_reduced_basis |
Load a previously saved reduced basis based on the lattice simulation parameters and tolerance. |
find_name_file_reduced_basis |
Construct the filename for the reduced basis based on the lattice simulation parameters. |
project_to_reduced_basis |
Project Schur complements into the previously built reduced basis. |
Attributes:
| Name | Type | Description |
|---|---|---|
la |
|
la = _import_scipy_linalg()
module-attribute
¶
LatticeSim
¶
Bases: Lattice
Methods:
| Name | Description |
|---|---|
define_simulation_parameters |
Define simulation parameters from the input file. |
set_penalized_beams |
Set penalization on beams at nodes based on L_zone values defined at beam endpoints. |
reset_penalized_beams |
Revert the penalization modifications made by set_penalized_beams. |
apply_constraints_nodes |
Apply boundary conditions to the lattice |
set_boundary_conditions |
Set boundary conditions on the lattice. |
get_global_displacement |
Get global displacement of the lattice |
define_node_index_boundary |
Define boundary tag for all boundary nodes and calculate the total number of boundary nodes |
get_global_reaction_force |
Get local reaction force of the lattice and sum if identical TagIndex |
get_global_reaction_force_without_fixed_DOF |
Get global reaction force of the lattice without fixed DOF |
define_free_DOF |
Get total number of degrees of freedom in the lattice |
set_global_free_DOF_index |
Set global free degree of freedom index for all nodes in boundary |
get_global_displacement_DDM |
Get global displacement of the lattice |
evaluate_alphas_linear_surrogate |
Robust linear surrogate with safe extrapolation: |
define_parameters |
Define parameters for the domain decomposition solver. |
build_coupling_operator_cells |
Build coupling operator for each cell in the lattice |
calculate_schur_complement_cells |
Calculate the Schur complement for each cell in the lattice. |
get_schur_complement_from_reduced_basis_batch |
Vectorized version: compute Schur complements for many queries in one GEMM (faster than many GEMVs). |
get_schur_complement_from_reduced_basis |
Get the Schur complement from the reduced basis with a giver surrogate method |
solve_DDM |
Solve the problem with the domain decomposition method. |
calculate_reaction_force_global |
Calculate the global reaction force of the lattice |
update_reaction_force_each_cell |
Update RF local |
solve_sub_problem |
Solve the subproblem on a cell to get the reaction force |
cg_progress |
Callback function to track and plot progress of the CG method. |
define_preconditioner |
Define the preconditioner for the conjugate gradient solver. |
build_preconditioner |
Build a sparse LU/ILU preconditioner of the global Schur complement. |
reset_cell_with_new_radii |
Reset cell with new radii for each beam type |
get_global_force_displacement_curve |
Aggregate global force (sum of reactions) vs imposed displacement for comparison with experiment. |
define_simulation_parameters(name_file)
¶
Define simulation parameters from the input file.
Parameters¶
name_file : str Name of the input file
set_penalized_beams()
¶
Set penalization on beams at nodes based on L_zone values defined at beam endpoints. This method allows for better simulation of beam junctions by introducing penalized segments.
reset_penalized_beams()
¶
Revert the penalization modifications made by set_penalized_beams. This involves: - Rewiring beams to connect original nodes directly, bypassing penalized segments. - Removing penalized beams and any orphaned nodes. Note: This operation is only valid if the lattice has been previously penalized.
apply_constraints_nodes(surfaces, value, DOF, type_constraint='Displacement', surface_cells=None)
¶
Apply boundary conditions to the lattice
Parameters:¶
surfaces: list[str] List of surfaces to apply constraint (e.g., [“Xmin”, “Xmax”, “Ymin”])
list of float
Values to apply to the constraint
list of int
Degree of freedom to apply constraint (0: x, 1: y, 2: z, 3: Rx, 4: Ry, 5: Rz)
str
Type of constraint (Displacement, Force)
list[str], optional
List of surfaces to find points on cells (e.g., [“Xmin”, “Xmax”, “Ymin”]). If None, uses surfaceNames.
set_boundary_conditions()
¶
Set boundary conditions on the lattice.
get_global_displacement(withFixed=False, OnlyImposed=False)
¶
Get global displacement of the lattice Parameters:
withFixed: bool If True, return displacement including fixed DOF OnlyImposed: bool If True, only return imposed displacement, else return all displacement
Returns:¶
globalDisplacement: dict Dictionary of global displacement with index_boundary as key and displacement vector as value globalDisplacementIndex: list List of boundary index per DOF (optional info)
define_node_index_boundary()
¶
Define boundary tag for all boundary nodes and calculate the total number of boundary nodes
get_global_reaction_force(appliedForceAdded=False)
¶
get_global_reaction_force_without_fixed_DOF(globalReactionForce, rightHandSide=False)
¶
Get global reaction force of the lattice without fixed DOF
Parameters:¶
globalReactionForce: dict Dictionary of global reaction force with index_boundary as key and reaction force vector as value
bool
If True, get applied forces (right-hand side), else get reaction forces
Returns:¶
y: np.ndarray Array of global reaction force without fixed DOF
define_free_DOF()
¶
Get total number of degrees of freedom in the lattice
set_global_free_DOF_index()
¶
Set global free degree of freedom index for all nodes in boundary
get_global_displacement_DDM(OnlyImposed=False)
¶
evaluate_alphas_linear_surrogate(geometric_params)
¶
Robust linear surrogate with safe extrapolation
• 1D: np.interp (fast, stable). • ND: LinearNDInterpolator inside convex hull; fallback to NearestNDInterpolator outside.
define_parameters(enable_precondioner=True, numberIterationMax=1000)
¶
Define parameters for the domain decomposition solver.
enable_preconditioner: bool Enable the preconditioner for the conjugate gradient solver. number_iteration_max: int Maximum number of iterations for the conjugate gradient solver.
build_coupling_operator_cells()
¶
Build coupling operator for each cell in the lattice
calculate_schur_complement_cells()
¶
Calculate the Schur complement for each cell in the lattice. Batch all unique radius cases per geometry and compute them at once.
get_schur_complement_from_reduced_basis_batch(geometric_params_list)
¶
Vectorized version: compute Schur complements for many queries in one GEMM (faster than many GEMVs).
Parameters¶
geometric_params_list : list of list of float Each inner list is a set of geometric parameters for one query.
Returns¶
schur_batch : np.ndarray Array of shape (n_queries, n_schur, n_schur) with Fortran-ordered per-matrix layout.
get_schur_complement_from_reduced_basis(geometric_params)
¶
solve_DDM()
¶
Solve the problem with the domain decomposition method.
calculate_reaction_force_global(globalDisplacement, rightHandSide=False)
¶
Calculate the global reaction force of the lattice
Parameters:¶
globalDisplacement: np.ndarray The global displacement vector. rightHandSide: bool If True, get applied forces (right-hand side), else get reaction forces.
update_reaction_force_each_cell(global_displacement)
¶
solve_sub_problem(cell)
¶
Solve the subproblem on a cell to get the reaction force
cg_progress(xk, b, A_operator)
¶
Callback function to track and plot progress of the CG method.
Parameters:¶
xk: np.array The current solution vector at the k-th iteration.
np.array
The right-hand side vector of the system.
callable or matrix
The operator or matrix for the system Ax = b.
define_preconditioner()
¶
Define the preconditioner for the conjugate gradient solver.
build_preconditioner()
¶
Build a sparse LU/ILU preconditioner of the global Schur complement. Faster assembly by accumulating triplets and avoiding dense ops.
reset_cell_with_new_radii(new_radii, index_cell=0)
¶
Reset cell with new radii for each beam type WARNING: BUG for multiple geometry cells
Parameters:¶
new_radii: list of float List of new radii for each beam type
int
Index of the cell to reset
get_global_force_displacement_curve(dof=2)
¶
Aggregate global force (sum of reactions) vs imposed displacement for comparison with experiment.
Parameters¶
dof : int Degree of freedom to extract (default=2 for Z direction).
Returns¶
disp : np.ndarray Imposed displacement values (at the loading boundary nodes).
np.ndarray
Total reaction force corresponding to that displacement.
_import_scipy_linalg()
¶
reduce_basis_greedy(schur_complement_dict_to_reduce, tol_greedy, file_name=None, verbose=1)
¶
Generated a reduced basis with a greedy algorithm from a set of projected fields.
Parameters¶
schur_complement_dict_to_reduce : dict A dictionary where keys are identifiers and values are the Schur complements to be projected.
float
Tolerance for the greedy algorithm convergence.
str, optional
If provided, the reduced basis and related data will be saved to a .npz file with this name.
int, optional
Verbosity level for logging information during the process.
Returns¶
mainelem : np.ndarray Indices of the selected main elements.
np.ndarray
Coefficients for the reduced basis.
list
List of projected fields corresponding to the main elements.
np.ndarray
The orthonormal reduced basis.
np.ndarray
Coefficients for projecting original fields onto the reduced basis.
np.ndarray
Upper triangular matrix from the QR decomposition of the reduced coefficients.
np.ndarray
Norms of the projected fields corresponding to the main elements.
Notes¶
The greedy algorithm iteratively selects the most significant projected field and orthogonalizes it against the current basis until convergence. The resulting basis is orthonormal and can be used for efficient projections. The function uses LAPACK and BLAS routines for efficient linear algebra operations. This implementation was provided by Thibaut Hirschler and adapted for pyLatticeSim.
save_reduced_basis(file_name, basis_reduced_ortho, alpha_ortho, list_elements)
¶
Save the reduced basis and related data to a .npz file.
Parameters¶
file_name : str Name of the file to save the data (without extension).
np.ndarray
The orthonormal reduced basis.
np.ndarray
Coefficients for projecting original fields onto the reduced basis.
np.ndarray
List of elements corresponding to the reduced basis.
load_reduced_basis(lattice_object_sim, tol_greedy)
¶
Load a previously saved reduced basis based on the lattice simulation parameters and tolerance.
Parameters¶
lattice_object_sim : LatticeSim The lattice simulation object containing parameters.
float
Tolerance used in the greedy algorithm.
Returns¶
dict A dictionary containing the loaded reduced basis and related data.
find_name_file_reduced_basis(lattice_object_sim, tol_greedy)
¶
project_to_reduced_basis(schur_complement_dict_to_project, basis_matrix_ortho)
¶
Project Schur complements into the previously built reduced basis.
Parameters¶
schur_complement_dict_to_project : dict A dictionary where keys are identifiers and values are the Schur complements to be projected.
np.ndarray
The orthonormal reduced basis obtained from the greedy algorithm.
Utilities¶
pyLatticeSim.utils
¶
Functions:
| Name | Description |
|---|---|
clear_directory |
Clear all files in a directory |
directional_modulus |
Compute the directional stiffness modulus in a spherical coordinate system. |
create_homogenization_figure |
Create a 3D figure representing the directional stiffness modulus |
clear_directory(directoryPath)
¶
directional_modulus(matS, theta, phi)
¶
Compute the directional stiffness modulus in a spherical coordinate system.
Parameters¶
matS : ndarray A 6-by-6 matrix defining the linear stress-to-strain relationship using the voigt notation.
float
Polar angle in degree.
float
Azimuthal angle in degree.
Returns¶
dirE : {float, ndarray} Directional stiffness modulus.
create_homogenization_figure(mat_S_orthotropic, plot=True, save=False, name_file='homogenization_figure')
¶
Create a 3D figure representing the directional stiffness modulus
Parameters¶
mat_S_orthotropic : ndarray A 6-by-6 matrix defining the linear stress-to-strain relationship using the voigt notation.
bool, optional
If True, displays the plot. Default is True.
bool, optional
If True, save the plot to a file. Default is True.
str, optional
Name of the file to save the plot. Default is “homogenization_figure”.
pyLatticeSim.utils_simulation
¶
Classes:
| Name | Description |
|---|---|
Material |
Encapsulates all material properties for a lattice structure. |
MatProperties |
A class to represent the properties of a material loaded from a file. |
BeamModel |
Class to define a beam model for FenicsX analysis from a lattice geometry. |
latticeGeneration |
Meshing of lattice structures with GMSH from class Lattice |
SimulationBase |
Parent class with all utilities to compute simulation in FenicsX |
FullScaleLatticeSimulation |
A class to handle full-scale lattice simulation using FenicsX. |
HomogenizedCell |
Lattice homogeneization analysis |
LatticeSim |
|
Functions:
| Name | Description |
|---|---|
solve_FEM_FenicsX |
Solve the finite element method problem using FenicsX for a given lattice. |
solve_FEM_cell |
Solve the finite element method problem for a specific cell in the lattice using FenicsX. |
get_homogenized_properties |
Perform homogenization analysis on a lattice structure. |
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
|
fem |
|
timing = Timing()
module-attribute
¶
fem = _import_dolfinx_fem()
module-attribute
¶
Material
¶
Encapsulates all material properties for a lattice structure.
Methods:
| Name | Description |
|---|---|
set_material |
Define material properties for linear behavior based on material_name. |
set_density |
Define material density. |
compute_mechanical_properties |
Compute mechanical properties based on the beam radius. |
compute_gradient |
Compute the gradient of mechanical properties, considering penalization. |
Attributes:
| Name | Type | Description |
|---|---|---|
properties_for_stress |
Return mechanical properties as a vector for stress calculations. |
|
properties_for_stress_gradient |
Return gradient of mechanical properties as a vector. |
properties_for_stress
property
¶
Return mechanical properties as a vector for stress calculations.
properties_for_stress_gradient
property
¶
Return gradient of mechanical properties as a vector.
set_material(lattice_material)
¶
Define material properties for linear behavior based on material_name.
set_density(density)
¶
Define material density.
compute_mechanical_properties(radius)
¶
Compute mechanical properties based on the beam radius.
compute_gradient(radius, tagBeam, lattice)
¶
Compute the gradient of mechanical properties, considering penalization. Vectorized version for performance.
MatProperties
¶
A class to represent the properties of a material loaded from a file.
Methods:
| Name | Description |
|---|---|
__init__ |
Initialize the MatProperties object by loading data from a file. |
load_material |
Loads material properties from a JSON file. |
BeamModel
¶
Class to define a beam model for FenicsX analysis from a lattice geometry.
Parameters¶
COMM : MPI communicator MPI communicator for parallel computing
LatticeObject
Lattice object from pyLatticeDesign
int, optional
Index of the cell to generate the mesh for. If None, the entire lattice mesh is generated.
Methods:
| Name | Description |
|---|---|
define_model |
Initialize the beam model |
open_lattice_geometry |
Open geometry from GMSH mesh file. |
generate_mesh |
Generate the mesh of the lattice or a specific cell |
define_radius |
Define radius values from a dictionary |
define_mechanical_properties |
Compute and set mechanical properties for the beam |
define_beam_geometry_data_circular_gradient |
Define beam geometry data for circular gradient |
define_material_model |
Define all material properties with preset data |
calculate_local_coordinate_system |
Calculate local coordinate system on each beam of the mesh |
Attributes:
| Name | Type | Description |
|---|---|---|
material |
Returns material properties |
material
property
¶
Returns material properties
define_model(lattice, cellIndex=None)
¶
Initialize the beam model
Parameters¶
lattice : Lattice The lattice object containing the mesh generation parameters.
int, optional
Index of the cell to generate the mesh for. If None, the entire lattice mesh is generated.
open_lattice_geometry(name_lattice_geometry)
¶
Open geometry from GMSH mesh file.
Parameters¶
name_lattice_geometry : str Name of the GMSH mesh file (should end with .msh).
generate_mesh(lattice, cell_index=None)
¶
Generate the mesh of the lattice or a specific cell
Parameters¶
lattice : LatticeObject The lattice object containing the mesh generation parameters.
int, optional
Index of the cell to generate the mesh for. If None, the entire lattice mesh is generated.
define_radius(radius_dict=None)
¶
Define radius values from a dictionary
Parameters¶
radius_dict : dict, optional Dictionary containing radius values keyed by beam tags.
define_mechanical_properties()
¶
Compute and set mechanical properties for the beam
define_beam_geometry_data_circular_gradient()
¶
Define beam geometry data for circular gradient
define_material_model(lattice)
¶
Define all material properties with preset data
calculate_local_coordinate_system()
¶
Calculate local coordinate system on each beam of the mesh
latticeGeneration
¶
Meshing of lattice structures with GMSH from class Lattice
Parameter:¶
Lattice: Lattice class object Object that contains all information of lattice structures
Methods:
| Name | Description |
|---|---|
find_mesh_size |
Determine mesh size |
mesh_lattice_cells |
Meshing lattice structures with node tags and beam tags |
generate_nodes |
Generate nodes in the structures with tags associated |
generate_beams |
Generate beams in the structures with tags associated |
generate_beams_tags |
Generate tags for beam elements |
generate_points_tags |
Generate points tags with normalized procedure |
find_mesh_size(mesh_element_lenght=0.05)
¶
Determine mesh size Function to be updated for better adaptive meshing
Parameters:¶
mesh_element_lenght: float Length of mesh element in unit of lattice cell size
mesh_lattice_cells(cell_index, mesh_element_lenght=0.05, save_mesh=True)
¶
Meshing lattice structures with node tags and beam tags
Parameters:¶
cell_index: int Index of the cell to mesh. If None, all cells are meshed.
float
Length of mesh element in unit of lattice cell size
bool
If True, save the mesh in a .msh file
generate_nodes(cell_index=None)
¶
Generate nodes in the structures with tags associated
Parameters:¶
nodes: list of node object from lattice class
generate_beams(cell_index=None)
¶
generate_beams_tags()
¶
Generate tags for beam elements
generate_points_tags()
¶
Generate points tags with normalized procedure
SimulationBase
¶
Parent class with all utilities to compute simulation in FenicsX
Methods:
| Name | Description |
|---|---|
prepare_simulation |
Initialize the simulation requisites |
define_test_trial_function |
Define Test and Trial Function from function space |
calculate_stress_strain |
Calculate stress and strain |
calculate_stress_grad |
Calculate stress gradient |
generalized_stress |
Calculate stress from a fem.Function |
generalized_stress_grad |
Calculate stress gradient from a fem.Function |
generalized_strains |
Calculate strain from a fem.Function |
calculate_forces |
Extract force components |
calculate_moments |
Extract moments components |
tgrad |
Calculate tangential gradient |
define_measures |
Define measures with subdomain data |
define_mixed_function_space |
Define Mixed function space with ufl library |
define_K_form |
Define K_form |
define_K_form_grad |
Define K_formGrad |
define_L_form_null |
Define L_form as null |
apply_force_at_node |
Apply a concentrated force at a specific node. |
apply_displacement_at_node |
Applying displacement at a node with a specific tag |
apply_constraint_at_node |
Apply a constraint at a specific node. |
apply_all_boundary_condition_on_lattice |
Apply all boundary conditions on the lattice |
apply_all_boundary_condition_on_cell_without_distinction |
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. |
apply_displacement_at_node_all_DOF |
Applying displacement at a node with a specific tag |
find_boundary_tags |
Find all tag with a node on the boundary of the unit cell |
solve_problem |
Solve the problem with a linear solver |
calculate_reaction_force |
Calculate reaction force on node_tag on macro coordinates basis |
calculate_reaction_force_and_moment_at_position |
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). |
calculate_reaction_force_and_moment |
Calculate reaction force and moment at a node on the macro coordinate basis |
calculate_reaction_force_and_moment_all_boundary_nodes |
Calculate reaction force on all boundary nodes |
calculate_energy_cell |
Calculate the energy in the cell based on the displacement vector. |
calculate_strain_energy |
Compute the strain energy in the lattice cell. |
calculate_strain_energy_grad |
Compute the strain energy gradient in the lattice cell. |
extract_stress_field |
Extract and interpolate the stress field in the structure after solving the problem. |
print_timers |
Print all accumulated timers with wall-clock time. |
prepare_simulation()
¶
Initialize the simulation requisites
define_test_trial_function()
¶
Define Test and Trial Function from function space
calculate_stress_strain()
¶
Calculate stress and strain
calculate_stress_grad()
¶
Calculate stress gradient
generalized_stress_grad(u)
¶
calculate_forces(u)
¶
Extract force components
calculate_moments(u)
¶
Extract moments components
tgrad(u)
¶
Calculate tangential gradient
define_measures()
¶
Define measures with subdomain data
define_mixed_function_space(element_type)
¶
Define Mixed function space with ufl library
Parameters¶
element_type: Tuple[str, str] => (elementType, elementType) Element type for each element of the function space
define_K_form()
¶
Define K_form
define_K_form_grad()
¶
Define K_formGrad
define_L_form_null()
¶
Define L_form as null
apply_force_at_node(node_tag, forceValue, dofIdx)
¶
Apply a concentrated force at a specific node.
Parameters:¶
node_tag: int Tag identifying the node.
float
The value of the force.
int
The degree of freedom where the force is applied
apply_displacement_at_node(node_tag, displacementValue, dofIdx)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
float
Displacement value to apply at the node
int
Between 0 and 5: the degree of freedom where move is apply
apply_constraint_at_node(node_tag, value_constraint, dof_idx, type_constraint)
¶
Apply a constraint at a specific node.
Parameters:¶
node_tag: int Tag identifying the node. value_constraint: float The value of the constraint (displacement or force). dof_idx: int The degree of freedom index (0-5) where the constraint is applied. type_constraint: str Type of constraint: “Displacement” or “Force”.
apply_all_boundary_condition_on_lattice(cell_only=None)
¶
Apply all boundary conditions on the lattice
Parameters:¶
cell_only: Cell, optional If specified, only apply boundary conditions on this cell
apply_all_boundary_condition_on_cell_without_distinction(cellToApply)
¶
Apply all boundary conditions on a specific cell without distinction between fixed DOF and applied force. Here we always impose the current node.displacement_vector on each boundary DOF of the target cell.
Parameters:¶
cellToApply: Cell The cell on which to apply the boundary conditions
apply_displacement_at_node_all_DOF(node_tag, displacementVector)
¶
Applying displacement at a node with a specific tag
Parameters:¶
node_tag: int Tag identifying the node
list of float
Displacement value to apply at the node
find_boundary_tags()
¶
Find all tag with a node on the boundary of the unit cell
solve_problem()
¶
Solve the problem with a linear solver
Uses PETSc KSP solver with LU preconditioner. This implementation allows to add true nodal point loads collected in self._point_loads before calling this method.
calculate_reaction_force(node_tag, solution=None)
¶
Calculate reaction force on node_tag on macro coordinates basis with strategy 2 : https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : integer The node tag where reaction force is calculated
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
Returns:¶
f : np.ndarray The reaction force vector (3 components).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_at_position(position, solution=None, tol=1e-08)
¶
Same as calculate_reaction_force_and_moment but selects the node by spatial position (x,y,z). Avoids locate_dofs_geometrical on subspaces by collapsing subspaces to get dof coords, then mapping back to the original subspace indices.
Parameters:¶
position : np.ndarray The (x, y, z) position where the reaction force and moment are calculated.
fem.Function, optional
The solution function to use for the calculation. If None, uses self.u.
float, optional
Tolerance for matching DOF coordinates to the specified position.
calculate_reaction_force_and_moment(node_tag)
¶
Calculate reaction force and moment at a node on the macro coordinate basis using strategy 2: https://bleyerj.github.io/comet-fenicsx/tips/computing_reactions/computing_reactions.html
Parameters:¶
node_tag : int The node tag where the reaction force and moment are calculated.
Returns:¶
arrayOfReaction : list[float] The six components of the reaction (3 forces, 3 moments).
np.ndarray
The position vector of the node.
calculate_reaction_force_and_moment_all_boundary_nodes(cell, full_nodes=False)
¶
Calculate reaction force on all boundary nodes
Parameters:¶
cell : Cell The cell containing the nodes. full_nodes : bool, optional If True, include zero reaction forces for non-boundary nodes.
calculate_energy_cell(displacement)
¶
Calculate the energy in the cell based on the displacement vector.
Parameters:¶
displacement : list of float The displacement vector at the boundary nodes.
calculate_strain_energy()
¶
Compute the strain energy in the lattice cell.
Returns:¶
W : float Total strain energy stored in the cell.
calculate_strain_energy_grad()
¶
Compute the strain energy gradient in the lattice cell.
Returns:¶
WGrad : float Total strain energy gradient stored in the cell.
extract_stress_field()
¶
Extract and interpolate the stress field in the structure after solving the problem.
Returns:¶
stress_function: fem.Function The stress field interpolated into the function space for visualization or post-processing.
print_timers()
¶
Print all accumulated timers with wall-clock time.
FullScaleLatticeSimulation
¶
Bases: SimulationBase
A class to handle full-scale lattice simulation using FenicsX.
Methods:
| Name | Description |
|---|---|
apply_displacement_all_nodes_with_lattice_data |
Applying displacement at all nodes with lattice data. |
set_result_diplacement_on_lattice_object |
Assigns the displacement and rotation values from the simulation to the lattice nodes. |
set_reaction_force_on_lattice_with_FEM_results |
Set reaction force on boundary condition nodes with FEM results. |
apply_force_on_all_nodes_with_lattice_data |
Applying force at all nodes with lattice data. |
print_number_DOFs |
Print the total number of degrees of freedom (DOFs) in the simulation. |
apply_displacement_all_nodes_with_lattice_data()
¶
Applying displacement at all nodes with lattice data.
set_result_diplacement_on_lattice_object()
¶
Assigns the displacement and rotation values from the simulation to the lattice nodes.
set_reaction_force_on_lattice_with_FEM_results()
¶
Set reaction force on boundary condition nodes with FEM results.
apply_force_on_all_nodes_with_lattice_data()
¶
Applying force at all nodes with lattice data.
This function applies forces stored in the lattice structure onto the corresponding nodes in the finite element model.
print_number_DOFs()
¶
Print the total number of degrees of freedom (DOFs) in the simulation.
HomogenizedCell
¶
Bases: SimulationBase
Lattice homogeneization analysis
Parameter:¶
BeamModel : BeamModel class object An object of class BeamModel with beam properties
Methods:
| Name | Description |
|---|---|
calculate_imposed_stress_strain |
Calculate stress and strain from an imposed study case |
find_imposed_strain |
Find imposed strain on domain |
get_imposed_strains |
Calculate strains from imposed displacement domain on dim-6 vectorspace |
locate_Dofs |
Locate degrees of freedom from selected logic function |
define_K_form_boundary |
Define K_form on element tag by markers |
define_L_form |
Define L_form |
periodic_boundary_condition |
Applying periodic boundary condition on unit cell |
initialize_solver |
Initialize solver for multiple RHS solving |
solve_multiple_linear_problem |
Function to solve multiple linear problem with the same LHS |
calculate_BTerm |
Calculate the right-hand side vector for the linear problem. |
calculate_macro_stress |
Calculate macro stress on define boundary tags |
get_logical_function |
Return a logical function for selecting parts of the domain boundary |
apply_dirichlet_for_homogenization |
Apply Dirichlet boundary condition for homogenization |
calculate_generalized_stress |
Calculate generalized stress on a strain case |
solve_full_homogenization |
Solve the entire homogenization of the unit cell |
print_homogenized_matrix |
Print simulation results of 6 loading case |
convert_to_orthotropic_form |
Convert homogenize matrix to orthotropic form |
get_S_orthotropic |
Return orthotropic matrix |
print_orthotropic_form |
Print orthotropic form of homogenization matrix |
compute_errors |
Calculate errors |
print_errors |
Print multiple types of errors in the matrix of simulation results |
calculate_imposed_stress_strain(case)
¶
Calculate stress and strain from an imposed study case
Parameters:¶
case: int from 1 to 6 Strain case for homogenization 1: X direction strain 2: Y direction strain 3: Z direction strain 4: XY direction strain 5: XZ direction strain 6: YZ direction strain
find_imposed_strain(case)
¶
Find imposed strain on domain
Parameters:¶
case: int from 1 to 6 Strain case for homogenization 1: X direction strain 2: Y direction strain 3: Z direction strain 4: XY direction strain 5: XZ direction strain 6: YZ direction strain
Output:¶
w: ufl.vector on domain Strain on domain depending of the strain case
get_imposed_strains(w)
¶
Calculate strains from imposed displacement domain on dim-6 vectorspace
Parameters:¶
w: ufl.as_vector[] dimension (3) Imposed strain
locate_Dofs(selection_function)
¶
Locate degrees of freedom from selected logic function Modified to be applied only on sub(0) => displacement
Parameters:¶
selectionFunction: logicalFunction Logical function to locate entities
define_K_form_boundary(markers=None)
¶
Define K_form on element tag by markers
Parameters:¶
markers: int Markers for boundary conditions, if None then use all boundaries
define_L_form()
¶
Define L_form
periodic_boundary_condition()
¶
Applying periodic boundary condition on unit cell
initialize_solver()
¶
Initialize solver for multiple RHS solving
solve_multiple_linear_problem()
¶
Function to solve multiple linear problem with the same LHS
calculate_BTerm()
¶
Calculate the right-hand side vector for the linear problem.
calculate_macro_stress(case)
¶
get_logical_function(location)
¶
apply_dirichlet_for_homogenization()
¶
Apply Dirichlet boundary condition for homogenization
calculate_generalized_stress(case)
¶
solve_full_homogenization()
¶
Solve the entire homogenization of the unit cell
Output:¶
self.homogenizeMatrix: homogenization matrix
print_homogenized_matrix()
¶
Print simulation results of 6 loading case
convert_to_orthotropic_form()
¶
Convert homogenize matrix to orthotropic form
get_S_orthotropic()
¶
Return orthotropic matrix
print_orthotropic_form()
¶
Print orthotropic form of homogenization matrix
compute_errors()
¶
Calculate errors
print_errors()
¶
Print multiple types of errors in the matrix of simulation results
LatticeSim
¶
Bases: Lattice
Methods:
| Name | Description |
|---|---|
define_simulation_parameters |
Define simulation parameters from the input file. |
set_penalized_beams |
Set penalization on beams at nodes based on L_zone values defined at beam endpoints. |
reset_penalized_beams |
Revert the penalization modifications made by set_penalized_beams. |
apply_constraints_nodes |
Apply boundary conditions to the lattice |
set_boundary_conditions |
Set boundary conditions on the lattice. |
get_global_displacement |
Get global displacement of the lattice |
define_node_index_boundary |
Define boundary tag for all boundary nodes and calculate the total number of boundary nodes |
get_global_reaction_force |
Get local reaction force of the lattice and sum if identical TagIndex |
get_global_reaction_force_without_fixed_DOF |
Get global reaction force of the lattice without fixed DOF |
define_free_DOF |
Get total number of degrees of freedom in the lattice |
set_global_free_DOF_index |
Set global free degree of freedom index for all nodes in boundary |
get_global_displacement_DDM |
Get global displacement of the lattice |
evaluate_alphas_linear_surrogate |
Robust linear surrogate with safe extrapolation: |
define_parameters |
Define parameters for the domain decomposition solver. |
build_coupling_operator_cells |
Build coupling operator for each cell in the lattice |
calculate_schur_complement_cells |
Calculate the Schur complement for each cell in the lattice. |
get_schur_complement_from_reduced_basis_batch |
Vectorized version: compute Schur complements for many queries in one GEMM (faster than many GEMVs). |
get_schur_complement_from_reduced_basis |
Get the Schur complement from the reduced basis with a giver surrogate method |
solve_DDM |
Solve the problem with the domain decomposition method. |
calculate_reaction_force_global |
Calculate the global reaction force of the lattice |
update_reaction_force_each_cell |
Update RF local |
solve_sub_problem |
Solve the subproblem on a cell to get the reaction force |
cg_progress |
Callback function to track and plot progress of the CG method. |
define_preconditioner |
Define the preconditioner for the conjugate gradient solver. |
build_preconditioner |
Build a sparse LU/ILU preconditioner of the global Schur complement. |
reset_cell_with_new_radii |
Reset cell with new radii for each beam type |
get_global_force_displacement_curve |
Aggregate global force (sum of reactions) vs imposed displacement for comparison with experiment. |
define_simulation_parameters(name_file)
¶
Define simulation parameters from the input file.
Parameters¶
name_file : str Name of the input file
set_penalized_beams()
¶
Set penalization on beams at nodes based on L_zone values defined at beam endpoints. This method allows for better simulation of beam junctions by introducing penalized segments.
reset_penalized_beams()
¶
Revert the penalization modifications made by set_penalized_beams. This involves: - Rewiring beams to connect original nodes directly, bypassing penalized segments. - Removing penalized beams and any orphaned nodes. Note: This operation is only valid if the lattice has been previously penalized.
apply_constraints_nodes(surfaces, value, DOF, type_constraint='Displacement', surface_cells=None)
¶
Apply boundary conditions to the lattice
Parameters:¶
surfaces: list[str] List of surfaces to apply constraint (e.g., [“Xmin”, “Xmax”, “Ymin”])
list of float
Values to apply to the constraint
list of int
Degree of freedom to apply constraint (0: x, 1: y, 2: z, 3: Rx, 4: Ry, 5: Rz)
str
Type of constraint (Displacement, Force)
list[str], optional
List of surfaces to find points on cells (e.g., [“Xmin”, “Xmax”, “Ymin”]). If None, uses surfaceNames.
set_boundary_conditions()
¶
Set boundary conditions on the lattice.
get_global_displacement(withFixed=False, OnlyImposed=False)
¶
Get global displacement of the lattice Parameters:
withFixed: bool If True, return displacement including fixed DOF OnlyImposed: bool If True, only return imposed displacement, else return all displacement
Returns:¶
globalDisplacement: dict Dictionary of global displacement with index_boundary as key and displacement vector as value globalDisplacementIndex: list List of boundary index per DOF (optional info)
define_node_index_boundary()
¶
Define boundary tag for all boundary nodes and calculate the total number of boundary nodes
get_global_reaction_force(appliedForceAdded=False)
¶
get_global_reaction_force_without_fixed_DOF(globalReactionForce, rightHandSide=False)
¶
Get global reaction force of the lattice without fixed DOF
Parameters:¶
globalReactionForce: dict Dictionary of global reaction force with index_boundary as key and reaction force vector as value
bool
If True, get applied forces (right-hand side), else get reaction forces
Returns:¶
y: np.ndarray Array of global reaction force without fixed DOF
define_free_DOF()
¶
Get total number of degrees of freedom in the lattice
set_global_free_DOF_index()
¶
Set global free degree of freedom index for all nodes in boundary
get_global_displacement_DDM(OnlyImposed=False)
¶
evaluate_alphas_linear_surrogate(geometric_params)
¶
Robust linear surrogate with safe extrapolation
• 1D: np.interp (fast, stable). • ND: LinearNDInterpolator inside convex hull; fallback to NearestNDInterpolator outside.
define_parameters(enable_precondioner=True, numberIterationMax=1000)
¶
Define parameters for the domain decomposition solver.
enable_preconditioner: bool Enable the preconditioner for the conjugate gradient solver. number_iteration_max: int Maximum number of iterations for the conjugate gradient solver.
build_coupling_operator_cells()
¶
Build coupling operator for each cell in the lattice
calculate_schur_complement_cells()
¶
Calculate the Schur complement for each cell in the lattice. Batch all unique radius cases per geometry and compute them at once.
get_schur_complement_from_reduced_basis_batch(geometric_params_list)
¶
Vectorized version: compute Schur complements for many queries in one GEMM (faster than many GEMVs).
Parameters¶
geometric_params_list : list of list of float Each inner list is a set of geometric parameters for one query.
Returns¶
schur_batch : np.ndarray Array of shape (n_queries, n_schur, n_schur) with Fortran-ordered per-matrix layout.
get_schur_complement_from_reduced_basis(geometric_params)
¶
solve_DDM()
¶
Solve the problem with the domain decomposition method.
calculate_reaction_force_global(globalDisplacement, rightHandSide=False)
¶
Calculate the global reaction force of the lattice
Parameters:¶
globalDisplacement: np.ndarray The global displacement vector. rightHandSide: bool If True, get applied forces (right-hand side), else get reaction forces.
update_reaction_force_each_cell(global_displacement)
¶
solve_sub_problem(cell)
¶
Solve the subproblem on a cell to get the reaction force
cg_progress(xk, b, A_operator)
¶
Callback function to track and plot progress of the CG method.
Parameters:¶
xk: np.array The current solution vector at the k-th iteration.
np.array
The right-hand side vector of the system.
callable or matrix
The operator or matrix for the system Ax = b.
define_preconditioner()
¶
Define the preconditioner for the conjugate gradient solver.
build_preconditioner()
¶
Build a sparse LU/ILU preconditioner of the global Schur complement. Faster assembly by accumulating triplets and avoiding dense ops.
reset_cell_with_new_radii(new_radii, index_cell=0)
¶
Reset cell with new radii for each beam type WARNING: BUG for multiple geometry cells
Parameters:¶
new_radii: list of float List of new radii for each beam type
int
Index of the cell to reset
get_global_force_displacement_curve(dof=2)
¶
Aggregate global force (sum of reactions) vs imposed displacement for comparison with experiment.
Parameters¶
dof : int Degree of freedom to extract (default=2 for Z direction).
Returns¶
disp : np.ndarray Imposed displacement values (at the loading boundary nodes).
np.ndarray
Total reaction force corresponding to that displacement.
solve_FEM_FenicsX(lattice)
¶
Solve the finite element method problem using FenicsX for a given lattice.
Parameters:¶
lattice: Lattice object The lattice structure to be simulated.
Returns:¶
xsol: numpy.ndarray The solution vector containing displacements.
FullScaleLatticeSimulation
The simulation model containing the results of the simulation.
solve_FEM_cell(lattice, cell)
¶
Solve the finite element method problem for a specific cell in the lattice using FenicsX.
Parameters:¶
lattice: Lattice object The lattice structure to be simulated.
object
The specific cell within the lattice to be analyzed.
get_homogenized_properties(lattice)
¶
Perform homogenization analysis on a lattice structure.
Parameters:¶
lattice: Lattice object The lattice structure to be homogenized.
Returns:¶
mat_Sorthotropic: numpy.ndarray The homogenized orthotropic stiffness matrix.
HomogenizedCell
The homogenization analysis object containing results and methods.
pyLatticeSim.utils_schur
¶
Classes:
| Name | Description |
|---|---|
Material |
Encapsulates all material properties for a lattice structure. |
MatProperties |
A class to represent the properties of a material loaded from a file. |
BeamModel |
Class to define a beam model for FenicsX analysis from a lattice geometry. |
latticeGeneration |
Meshing of lattice structures with GMSH from class Lattice |
SchurComplement |
Class to perform Schur Complement calculations on a given BeamModel. |
LatticeSim |
|
Cell |
Class representing a cell in the lattice structure. |
Functions:
| Name | Description |
|---|---|
get_schur_complement |
Calculate the Schur complement of the stiffness matrix for a given lattice. |
save_schur_complement_npz |
Save the Schur complement matrices and corresponding radius values to a .npz file. |
define_path_schur_complement |
Define the file path for the Schur complement dataset based on the lattice geometry. |
load_schur_complement_dataset |
Load the Schur complement matrices from a file and normalize them if needed. |
normalize_schur_matrix |
Normalize each Schur complement matrix in the dictionary. |
Attributes:
| Name | Type | Description |
|---|---|---|
timing |
|
timing = Timing()
module-attribute
¶
Material
¶
Encapsulates all material properties for a lattice structure.
Methods:
| Name | Description |
|---|---|
set_material |
Define material properties for linear behavior based on material_name. |
set_density |
Define material density. |
compute_mechanical_properties |
Compute mechanical properties based on the beam radius. |
compute_gradient |
Compute the gradient of mechanical properties, considering penalization. |
Attributes:
| Name | Type | Description |
|---|---|---|
properties_for_stress |
Return mechanical properties as a vector for stress calculations. |
|
properties_for_stress_gradient |
Return gradient of mechanical properties as a vector. |
properties_for_stress
property
¶
Return mechanical properties as a vector for stress calculations.
properties_for_stress_gradient
property
¶
Return gradient of mechanical properties as a vector.
set_material(lattice_material)
¶
Define material properties for linear behavior based on material_name.
set_density(density)
¶
Define material density.
compute_mechanical_properties(radius)
¶
Compute mechanical properties based on the beam radius.
compute_gradient(radius, tagBeam, lattice)
¶
Compute the gradient of mechanical properties, considering penalization. Vectorized version for performance.
MatProperties
¶
A class to represent the properties of a material loaded from a file.
Methods:
| Name | Description |
|---|---|
__init__ |
Initialize the MatProperties object by loading data from a file. |
load_material |
Loads material properties from a JSON file. |
BeamModel
¶
Class to define a beam model for FenicsX analysis from a lattice geometry.
Parameters¶
COMM : MPI communicator MPI communicator for parallel computing
LatticeObject
Lattice object from pyLatticeDesign
int, optional
Index of the cell to generate the mesh for. If None, the entire lattice mesh is generated.
Methods:
| Name | Description |
|---|---|
define_model |
Initialize the beam model |
open_lattice_geometry |
Open geometry from GMSH mesh file. |
generate_mesh |
Generate the mesh of the lattice or a specific cell |
define_radius |
Define radius values from a dictionary |
define_mechanical_properties |
Compute and set mechanical properties for the beam |
define_beam_geometry_data_circular_gradient |
Define beam geometry data for circular gradient |
define_material_model |
Define all material properties with preset data |
calculate_local_coordinate_system |
Calculate local coordinate system on each beam of the mesh |
Attributes:
| Name | Type | Description |
|---|---|---|
material |
Returns material properties |
material
property
¶
Returns material properties
define_model(lattice, cellIndex=None)
¶
Initialize the beam model
Parameters¶
lattice : Lattice The lattice object containing the mesh generation parameters.
int, optional
Index of the cell to generate the mesh for. If None, the entire lattice mesh is generated.
open_lattice_geometry(name_lattice_geometry)
¶
Open geometry from GMSH mesh file.
Parameters¶
name_lattice_geometry : str Name of the GMSH mesh file (should end with .msh).
generate_mesh(lattice, cell_index=None)
¶
Generate the mesh of the lattice or a specific cell
Parameters¶
lattice : LatticeObject The lattice object containing the mesh generation parameters.
int, optional
Index of the cell to generate the mesh for. If None, the entire lattice mesh is generated.
define_radius(radius_dict=None)
¶
Define radius values from a dictionary
Parameters¶
radius_dict : dict, optional Dictionary containing radius values keyed by beam tags.
define_mechanical_properties()
¶
Compute and set mechanical properties for the beam
define_beam_geometry_data_circular_gradient()
¶
Define beam geometry data for circular gradient
define_material_model(lattice)
¶
Define all material properties with preset data
calculate_local_coordinate_system()
¶
Calculate local coordinate system on each beam of the mesh
latticeGeneration
¶
Meshing of lattice structures with GMSH from class Lattice
Parameter:¶
Lattice: Lattice class object Object that contains all information of lattice structures
Methods:
| Name | Description |
|---|---|
find_mesh_size |
Determine mesh size |
mesh_lattice_cells |
Meshing lattice structures with node tags and beam tags |
generate_nodes |
Generate nodes in the structures with tags associated |
generate_beams |
Generate beams in the structures with tags associated |
generate_beams_tags |
Generate tags for beam elements |
generate_points_tags |
Generate points tags with normalized procedure |
find_mesh_size(mesh_element_lenght=0.05)
¶
Determine mesh size Function to be updated for better adaptive meshing
Parameters:¶
mesh_element_lenght: float Length of mesh element in unit of lattice cell size
mesh_lattice_cells(cell_index, mesh_element_lenght=0.05, save_mesh=True)
¶
Meshing lattice structures with node tags and beam tags
Parameters:¶
cell_index: int Index of the cell to mesh. If None, all cells are meshed.
float
Length of mesh element in unit of lattice cell size
bool
If True, save the mesh in a .msh file
generate_nodes(cell_index=None)
¶
Generate nodes in the structures with tags associated
Parameters:¶
nodes: list of node object from lattice class
generate_beams(cell_index=None)
¶
generate_beams_tags()
¶
Generate tags for beam elements
generate_points_tags()
¶
Generate points tags with normalized procedure
SchurComplement
¶
Bases: SimulationBase
Class to perform Schur Complement calculations on a given BeamModel.
Parameters:¶
BeamModel : BeamModel The beam model to perform the Schur Complement calculation on.
Methods:
| Name | Description |
|---|---|
construct_K |
Construct K matrix from variational form |
calculate_schur_complement |
Calculate the Schur complement of the stiffness matrix. |
LatticeSim
¶
Bases: Lattice
Methods:
| Name | Description |
|---|---|
define_simulation_parameters |
Define simulation parameters from the input file. |
set_penalized_beams |
Set penalization on beams at nodes based on L_zone values defined at beam endpoints. |
reset_penalized_beams |
Revert the penalization modifications made by set_penalized_beams. |
apply_constraints_nodes |
Apply boundary conditions to the lattice |
set_boundary_conditions |
Set boundary conditions on the lattice. |
get_global_displacement |
Get global displacement of the lattice |
define_node_index_boundary |
Define boundary tag for all boundary nodes and calculate the total number of boundary nodes |
get_global_reaction_force |
Get local reaction force of the lattice and sum if identical TagIndex |
get_global_reaction_force_without_fixed_DOF |
Get global reaction force of the lattice without fixed DOF |
define_free_DOF |
Get total number of degrees of freedom in the lattice |
set_global_free_DOF_index |
Set global free degree of freedom index for all nodes in boundary |
get_global_displacement_DDM |
Get global displacement of the lattice |
evaluate_alphas_linear_surrogate |
Robust linear surrogate with safe extrapolation: |
define_parameters |
Define parameters for the domain decomposition solver. |
build_coupling_operator_cells |
Build coupling operator for each cell in the lattice |
calculate_schur_complement_cells |
Calculate the Schur complement for each cell in the lattice. |
get_schur_complement_from_reduced_basis_batch |
Vectorized version: compute Schur complements for many queries in one GEMM (faster than many GEMVs). |
get_schur_complement_from_reduced_basis |
Get the Schur complement from the reduced basis with a giver surrogate method |
solve_DDM |
Solve the problem with the domain decomposition method. |
calculate_reaction_force_global |
Calculate the global reaction force of the lattice |
update_reaction_force_each_cell |
Update RF local |
solve_sub_problem |
Solve the subproblem on a cell to get the reaction force |
cg_progress |
Callback function to track and plot progress of the CG method. |
define_preconditioner |
Define the preconditioner for the conjugate gradient solver. |
build_preconditioner |
Build a sparse LU/ILU preconditioner of the global Schur complement. |
reset_cell_with_new_radii |
Reset cell with new radii for each beam type |
get_global_force_displacement_curve |
Aggregate global force (sum of reactions) vs imposed displacement for comparison with experiment. |
define_simulation_parameters(name_file)
¶
Define simulation parameters from the input file.
Parameters¶
name_file : str Name of the input file
set_penalized_beams()
¶
Set penalization on beams at nodes based on L_zone values defined at beam endpoints. This method allows for better simulation of beam junctions by introducing penalized segments.
reset_penalized_beams()
¶
Revert the penalization modifications made by set_penalized_beams. This involves: - Rewiring beams to connect original nodes directly, bypassing penalized segments. - Removing penalized beams and any orphaned nodes. Note: This operation is only valid if the lattice has been previously penalized.
apply_constraints_nodes(surfaces, value, DOF, type_constraint='Displacement', surface_cells=None)
¶
Apply boundary conditions to the lattice
Parameters:¶
surfaces: list[str] List of surfaces to apply constraint (e.g., [“Xmin”, “Xmax”, “Ymin”])
list of float
Values to apply to the constraint
list of int
Degree of freedom to apply constraint (0: x, 1: y, 2: z, 3: Rx, 4: Ry, 5: Rz)
str
Type of constraint (Displacement, Force)
list[str], optional
List of surfaces to find points on cells (e.g., [“Xmin”, “Xmax”, “Ymin”]). If None, uses surfaceNames.
set_boundary_conditions()
¶
Set boundary conditions on the lattice.
get_global_displacement(withFixed=False, OnlyImposed=False)
¶
Get global displacement of the lattice Parameters:
withFixed: bool If True, return displacement including fixed DOF OnlyImposed: bool If True, only return imposed displacement, else return all displacement
Returns:¶
globalDisplacement: dict Dictionary of global displacement with index_boundary as key and displacement vector as value globalDisplacementIndex: list List of boundary index per DOF (optional info)
define_node_index_boundary()
¶
Define boundary tag for all boundary nodes and calculate the total number of boundary nodes
get_global_reaction_force(appliedForceAdded=False)
¶
get_global_reaction_force_without_fixed_DOF(globalReactionForce, rightHandSide=False)
¶
Get global reaction force of the lattice without fixed DOF
Parameters:¶
globalReactionForce: dict Dictionary of global reaction force with index_boundary as key and reaction force vector as value
bool
If True, get applied forces (right-hand side), else get reaction forces
Returns:¶
y: np.ndarray Array of global reaction force without fixed DOF
define_free_DOF()
¶
Get total number of degrees of freedom in the lattice
set_global_free_DOF_index()
¶
Set global free degree of freedom index for all nodes in boundary
get_global_displacement_DDM(OnlyImposed=False)
¶
evaluate_alphas_linear_surrogate(geometric_params)
¶
Robust linear surrogate with safe extrapolation
• 1D: np.interp (fast, stable). • ND: LinearNDInterpolator inside convex hull; fallback to NearestNDInterpolator outside.
define_parameters(enable_precondioner=True, numberIterationMax=1000)
¶
Define parameters for the domain decomposition solver.
enable_preconditioner: bool Enable the preconditioner for the conjugate gradient solver. number_iteration_max: int Maximum number of iterations for the conjugate gradient solver.
build_coupling_operator_cells()
¶
Build coupling operator for each cell in the lattice
calculate_schur_complement_cells()
¶
Calculate the Schur complement for each cell in the lattice. Batch all unique radius cases per geometry and compute them at once.
get_schur_complement_from_reduced_basis_batch(geometric_params_list)
¶
Vectorized version: compute Schur complements for many queries in one GEMM (faster than many GEMVs).
Parameters¶
geometric_params_list : list of list of float Each inner list is a set of geometric parameters for one query.
Returns¶
schur_batch : np.ndarray Array of shape (n_queries, n_schur, n_schur) with Fortran-ordered per-matrix layout.
get_schur_complement_from_reduced_basis(geometric_params)
¶
solve_DDM()
¶
Solve the problem with the domain decomposition method.
calculate_reaction_force_global(globalDisplacement, rightHandSide=False)
¶
Calculate the global reaction force of the lattice
Parameters:¶
globalDisplacement: np.ndarray The global displacement vector. rightHandSide: bool If True, get applied forces (right-hand side), else get reaction forces.
update_reaction_force_each_cell(global_displacement)
¶
solve_sub_problem(cell)
¶
Solve the subproblem on a cell to get the reaction force
cg_progress(xk, b, A_operator)
¶
Callback function to track and plot progress of the CG method.
Parameters:¶
xk: np.array The current solution vector at the k-th iteration.
np.array
The right-hand side vector of the system.
callable or matrix
The operator or matrix for the system Ax = b.
define_preconditioner()
¶
Define the preconditioner for the conjugate gradient solver.
build_preconditioner()
¶
Build a sparse LU/ILU preconditioner of the global Schur complement. Faster assembly by accumulating triplets and avoiding dense ops.
reset_cell_with_new_radii(new_radii, index_cell=0)
¶
Reset cell with new radii for each beam type WARNING: BUG for multiple geometry cells
Parameters:¶
new_radii: list of float List of new radii for each beam type
int
Index of the cell to reset
get_global_force_displacement_curve(dof=2)
¶
Aggregate global force (sum of reactions) vs imposed displacement for comparison with experiment.
Parameters¶
dof : int Degree of freedom to extract (default=2 for Z direction).
Returns¶
disp : np.ndarray Imposed displacement values (at the loading boundary nodes).
np.ndarray
Total reaction force corresponding to that displacement.
Cell
¶
Bases: object
Class representing a cell in the lattice structure.
Methods:
| Name | Description |
|---|---|
__init__ |
Initialize a Cell with its dimensions and position |
dispose |
Dispose of the cell by detaching beams and points, and cleaning up references. |
generate_cell_properties |
Generate cell properties including beams and nodes. |
generate_beams |
Generate beams and nodes using a given lattice type_beam and parameters. |
get_beam_material |
Get the material of the beam based on the material gradient. |
get_radius |
Calculate and return the beam radii |
def_cell_size |
Calculate and return the cell size |
def_cell_center |
Calculate the center point of the cell |
get_point_on_surface |
Get the points on the surface specified in the global reference frame. |
remove_beam |
Removing beam from cell |
remove_point |
Removing point from cell |
add_beam |
Adding beam to cell |
add_point |
Adding point to cell |
add_cell_neighbour |
Add a neighbour cell in a structured dict format. |
get_all_cell_neighbours |
Get all neighbour cells in a flat list. |
refresh_from_global |
Rebuild self.beams_cell and self.points_cell from the current lattice state. |
define_node_order_to_simulate |
Define a deterministic order for boundary nodes to ensure consistent simulation results. |
set_reaction_force_on_nodes |
Set reaction force on each boundary node in the established local order. |
get_displacement_at_nodes |
Return displacement vectors ordered consistently with the provided local list/dict of Points. |
set_displacement_at_boundary_nodes |
Set displacement at nodes. |
build_coupling_operator |
Build the coupling operator B using the deterministic local boundary-node order. |
build_local_preconditioner |
Build the local preconditioner matrix B^T * S * B |
get_number_boundary_nodes |
Get the number of unique boundary nodes in the cell. |
get_internal_energy |
Get cell internal energy from all boundary points |
get_displacement_data |
Build and return displacement data on cell for dataset generation |
get_number_nodes_at_boundary |
Get the number of nodes at the boundary |
change_beam_radius |
WARNING: BEAM MOD IS NOT WORKING |
get_relative_density_kriging |
Get the relative density of the cell using kriging model |
get_relative_density_gradient |
Get the gradient of the relative density |
get_relative_density_gradient_kriging |
Finite difference gradient of the relative density (predictive mean) w.r.t. the radii using the trained |
get_relative_density_gradient_kriging_exact |
Exact gradient of the relative density (predictive mean) w.r.t. the radii using the trained |
get_RGBcolor_depending_of_radius |
Get the RGB color of the cell depending on the radii. |
print_data |
Print the data of the cell for debugging purposes. |
get_translation_rigid_body |
Get the translation of the rigid body |
get_rotation_rigid_body |
Get the rotation matrix of the rigid body using SVD. |
Attributes:
| Name | Type | Description |
|---|---|---|
volume |
Calculate the volume of the cell. |
|
relative_density |
float
|
Calculate the relative density of the cell based on the volume of beams and the cell volume. |
volume_each_geom |
ndarray
|
Get the volume of the cell separated by geometry type_beam. |
boundary_box |
list
|
Get the boundary box of the cell |
boundary_edges |
list[tuple[tuple[float, float, float], tuple[float, float, float]]]
|
Return the 12 edge segments of the cell’s axis-aligned bounding box |
corner_coordinates |
list
|
Get the corner coordinates of the cell. |
volume
property
¶
Calculate the volume of the cell.
relative_density
property
¶
Calculate the relative density of the cell based on the volume of beams and the cell volume.
volume_each_geom
property
¶
Get the volume of the cell separated by geometry type_beam.
boundary_box
property
¶
boundary_edges
property
¶
Return the 12 edge segments of the cell’s axis-aligned bounding box as pairs of 3D points ((x,y,z), (x,y,z)).
corner_coordinates
property
¶
Get the corner coordinates of the cell.
Returns:¶
list of tuples List of (x, y, z) coordinates of the corner points.
__init__(pos, initial_size, coordinate, geom_types, radii, grad_radius, grad_dim, grad_mat, uncertainty_node=0.0, _verbose=0, beams_already_defined=None, nodes_already_defined=None)
¶
Parameters:¶
pos: list Position of the cell in the lattice
list
Initial size of the cell
list
Coordinates of the cell minimum corner in the lattice
list[str]
Type of lattice geometry
float
Base radii of the beam
list
Gradient of the radii
list
Gradient of the dimensions
list
Gradient of the material
float
Standard deviation for adding uncertainty to node coordinates. Defaults to 0.0.
bool
If True, prints additional information during initialization. Defaults to False.
set
Set of beams already defined in the lattice to avoid duplication. Defaults to None.
set
Set of nodes already defined in the lattice to avoid duplication. Defaults to None.
dispose()
¶
Dispose of the cell by detaching beams and points, and cleaning up references.
generate_cell_properties(initial_cell_size, beams_already_defined=None, nodes_already_defined=None)
¶
Generate cell properties including beams and nodes.
Parameters:¶
initialCellSize: list Initial size of the cell without modification
set
Set of beams already defined in the lattice to avoid duplication
set
Set of nodes already defined in the lattice to avoid duplication
generate_beams(latticeType, beamRadius, beamType=0, beams_already_defined=None, nodes_already_defined=None)
¶
Generate beams and nodes using a given lattice type_beam and parameters.
Parameters:¶
latticeType: str Type of lattice structure (e.g., ‘BCC’, ‘Hybrid1’, etc.)
float
Radius of the beam
int
Type index of the beam
set
Set of beams already defined in the lattice to avoid duplication
set
Set of nodes already defined in the lattice to avoid duplication
get_beam_material()
¶
Get the material of the beam based on the material gradient.
get_radius(base_radius)
¶
def_cell_size(initial_cell_size)
¶
def_cell_center()
¶
Calculate the center point of the cell
get_point_on_surface(surfaceName)
¶
Get the points on the surface specified in the global reference frame.
Parameters:¶
surfaceName: str Name of the surface. Choose from ‘Xmin’, ‘Xmax’, ‘Ymin’, ‘Ymax’, ‘Zmin’, ‘Zmax’, ‘Xmid’, ‘Ymid’, ‘Zmid’. If ‘Xmid’, ‘Ymid’, or ‘Zmid’ is specified, it returns the points at the bottom of the cell
Returns:¶
list List of points on the specified surface.
remove_beam(beam_to_delete)
¶
Removing beam from cell
Parameters:¶
beam_to_delete: Beam or Iterable[Beam] Beam or list of beams to remove from the cell
remove_point(point_to_delete)
¶
Removing point from cell
Parameters:¶
point_to_delete: Point or Iterable[Point] Point or list of points to remove from the cell
add_beam(beam_to_add)
¶
Adding beam to cell
Parameters:¶
beam_to_add: Beam or Iterable[Beam] Beam or list of beams to add to the cell
add_point(point_to_add)
¶
Adding point to cell
Parameters:¶
point_to_add: Point or Iterable[Point] Point or list of points to add to the cell
add_cell_neighbour(direction, sign, neighbour_cell)
¶
Add a neighbour cell in a structured dict format.
Parameters¶
direction : str One of “x”, “y”, “z” sign : str Either “positif” or “negatif” neighbour_cell : Cell Neighbour cell to add
get_all_cell_neighbours()
¶
refresh_from_global(all_beams)
¶
Rebuild self.beams_cell and self.points_cell from the current lattice state. Keeps only beams that still declare this cell as a belonging, and derives points from those beams.
define_node_order_to_simulate(face_priority=None, tol=1e-09)
¶
Define a deterministic order for boundary nodes to ensure consistent simulation results.
Parameters:¶
face_priority: Optional[List[str]] List defining the priority order of faces to assign nodes to when they lie on multiple faces. Default is [“Xmin”, “Xmax”, “Ymin”, “Ymax”, “Zmin”, “Zmax”].
float
Tolerance for determining if a point lies on a face. Default is 1e-9.
set_reaction_force_on_nodes(reactionForce)
¶
Set reaction force on each boundary node in the established local order.
Parameters:¶
reactionForce: list List of reaction force vectors corresponding to each boundary node.
get_displacement_at_nodes(nodeList)
¶
set_displacement_at_boundary_nodes(displacementArray)
¶
Set displacement at nodes.
Parameters:¶
displacementArray: list or array-like Flattened array of displacement values.
build_coupling_operator(nb_free_DOF)
¶
Build the coupling operator B using the deterministic local boundary-node order.
Parameters:¶
nb_free_DOF: int Total number of free degrees of freedom in the global system.
build_local_preconditioner(schur_mean=None)
¶
Build the local preconditioner matrix B^T * S * B
Parameters:¶
schur_mean: array-like or None Schur complement matrix to use. If None, uses self.schur_complement.
get_number_boundary_nodes()
¶
Get the number of unique boundary nodes in the cell.
get_internal_energy()
¶
Get cell internal energy from all boundary points
get_displacement_data()
¶
Build and return displacement data on cell for dataset generation
get_number_nodes_at_boundary()
¶
change_beam_radius(new_radius)
¶
WARNING: BEAM MOD IS NOT WORKING Change beam radii in the cell
Parameters:¶
newRadius: list beam radii wanted to assign
get_relative_density_kriging(kriging_model)
¶
Get the relative density of the cell using kriging model
Parameters:¶
krigingModel: Kriging Kriging model to use for prediction
get_relative_density_gradient(relative_density_poly_deriv)
¶
get_relative_density_gradient_kriging(model, geometries_types)
¶
Finite difference gradient of the relative density (predictive mean) w.r.t. the radii using the trained Pipeline(StandardScaler -> GaussianProcessRegressor) with Constant*RBF kernel. Returns an array of size len(geometries_types) where entries for geometries not present in the cell are 0.
get_relative_density_gradient_kriging_exact(model, geometries_types)
¶
Exact gradient of the relative density (predictive mean) w.r.t. the radii using the trained Pipeline(StandardScaler -> GaussianProcessRegressor) with Constant*RBF kernel.
Returns an array of size len(geometries_types) where entries for geometries not present in the cell are 0.
Parameters:¶
model: Pipeline Trained kriging model
list
List of geometry types in the trained kriging model
get_RGBcolor_depending_of_radius()
¶
Get the RGB color of the cell depending on the radii.
print_data()
¶
Print the data of the cell for debugging purposes.
get_translation_rigid_body()
¶
Get the translation of the rigid body
get_rotation_rigid_body()
¶
Get the rotation matrix of the rigid body using SVD.
get_schur_complement(lattice, cell_index=None)
¶
Calculate the Schur complement of the stiffness matrix for a given lattice.
Parameters:¶
lattice: Lattice object The lattice structure to be analyzed.
int, optional
The index of the cell to be used for the Schur complement calculation. If None, the first cell is used.
save_schur_complement_npz(lattice_object, radius_values, schur_matrices)
¶
Save the Schur complement matrices and corresponding radius values to a .npz file.
Parameters:¶
lattice_object: LatticeSim The lattice object containing geometry and material information.
list
A list of radius values corresponding to each Schur complement matrix.
list
A list of Schur complement matrices to be saved.
define_path_schur_complement(lattice_object)
¶
load_schur_complement_dataset(lattice_object, enable_normalization=False)
¶
Load the Schur complement matrices from a file and normalize them if needed.
Parameters:¶
lattice_object: LatticeSim The lattice object containing geometry and material information.
bool
If True, normalize each Schur complement matrix.
Returns:¶
Schur_complement: dict A dictionary with radius tuples as keys and corresponding Schur complement matrices as values.
normalize_schur_matrix(schur_dict)
¶
pyLatticeSim.utils_rbf
¶
Classes:
| Name | Description |
|---|---|
ThinPlateSplineRBF |
Thin-plate-spline (polyharmonic, k=2) RBF interpolator with a linear polynomial tail. |
ThinPlateSplineRBF
¶
Thin-plate-spline (polyharmonic, k=2) RBF interpolator with a linear polynomial tail. Supports vector-valued outputs Y in R^{N x m}. Provides evaluation f(X) and analytic gradient ∇f(X).
Methods:
| Name | Description |
|---|---|
__init__ |
Parameters |
evaluate |
Evaluate the interpolant at one or many points. |
gradient |
Evaluate the gradient ∇f at one or many points. |
pyLatticeSim.export_simulation_results
¶
Classes:
| Name | Description |
|---|---|
exportSimulationResults |
Beam data exportation to Paraview |
Functions:
| Name | Description |
|---|---|
clear_directory |
Clear all files in a directory |
directional_modulus |
Compute the directional stiffness modulus in a spherical coordinate system. |
_import_dolfinx |
|
exportSimulationResults
¶
Beam data exportation to Paraview
Parameters:¶
simulation_model: object Your simulation model, exposing .domain, .u, .BeamModel, etc.
str
Folder name (will be created under
Methods:
| Name | Description |
|---|---|
define_function_space |
Define the function space for forces and moments. |
export_displacement_rotation |
Export displacement and rotation fields from self.simulation_model.u |
export_moments |
Export moments based on FE_result (typically self.simulation_model.u) |
export_macro_strain |
Export macro strain for a given loading case. |
export_local_coordinates_system |
Export local coordinate axes (a1, a2, t) on the domain. |
export_internal_force |
Export internal forces. |
export_finalize |
Write and close (single-shot). |
write_function |
Append current fields at time t to the PVD series. |
close_file |
Close the PVD writer. |
full_export |
Export all data for a given case |
export_data_homogenization |
Export all data from 6 loading cases in homogenization. |
export_homogenization_surface_paraview |
Export the 3D homogenization polar surface (directional stiffness) using Gmsh. |
export_vizualisation_3D |
Export beam data on 3D cylinders. All files are written inside |
save_VTK_data |
Save a single beam element domain to VTU file for Paraview visualization. |
convert_mesh_for_paraview |
Convert a given mesh to Paraview VTU format for visualization. |
create_PVD_file |
Generate a PVD file to open all beam results in one step inside the given directory. |
change_radius |
Change the radius of the beam element mesh. |
move_element |
Move the beam element mesh to the correct position. |
resize_element |
Resize the beam element mesh to the correct length. |
rotate_element |
Rotate the beam element mesh to the correct direction. |
find_beam_element_mesh_name |
Find the mesh name for given parameters and check if it exists. |
generate_beam_element |
Generate the beam element mesh using Gmsh if it does not exist. |
export_reaction_force |
Export reaction force as a CG(1) vector field. |
define_function_space()
¶
Define the function space for forces and moments.
export_displacement_rotation(case=0)
¶
Export displacement and rotation fields from self.simulation_model.u
export_moments(FE_result, case=0)
¶
Export moments based on FE_result (typically self.simulation_model.u)
export_macro_strain(case)
¶
Export macro strain for a given loading case.
export_local_coordinates_system()
¶
Export local coordinate axes (a1, a2, t) on the domain.
export_internal_force(u, case=0)
¶
Export internal forces.
export_finalize(time=0.0)
¶
Write and close (single-shot).
write_function(time=0.0)
¶
Append current fields at time t to the PVD series.
close_file()
¶
Close the PVD writer.
export_data_homogenization(homogenization_surface=True)
¶
Export all data from 6 loading cases in homogenization. Each item in saveDataToExport is a solution field.
Parameters¶
homogenization_surface: bool Whether to export the homogenization surface as well.
export_homogenization_surface_paraview(mat_S_orthotropic, filename='homogenization_surface', n_theta=90, n_phi=180)
¶
Export the 3D homogenization polar surface (directional stiffness) using Gmsh.
Writes
Parameters¶
mat_S_orthotropic: np.ndarray 6x6 stiffness matrix in Voigt notation (assumed orthotropic)
str
Base name for output files (without extension)
int
Number of angular samples in theta (0..pi)
int
Number of angular samples in phi (0..2pi)
export_vizualisation_3D(save_directory, number_point_ext=8, mesh_radius_int=3)
¶
Export beam data on 3D cylinders. All files are written inside
Parameters¶
save_directory: str | Path Subdirectory inside self.out_dir where to save the VTU files.
int
Number of points along the external circle of the beam cross-section mesh.
int
Number of points along the radius of the beam cross-section mesh.
save_VTK_data(save_path, domainElement)
¶
Save a single beam element domain to VTU file for Paraview visualization.
Parameters¶
save_path: str | Path Full path where to save the VTU file. domainElement: dolfinx.mesh.Mesh The mesh of the beam element to save.
convert_mesh_for_paraview(nameMesh)
¶
Convert a given mesh to Paraview VTU format for visualization.
Parameters¶
nameMesh: str | Path Full path to the input mesh file in MSH format.
create_PVD_file(vtk_directory, output_filename='#0_AllElements.pvd')
staticmethod
¶
Generate a PVD file to open all beam results in one step inside the given directory.
Parameters¶
vtk_directory: str | Path Directory where VTU files are located. output_filename: str Name of the output PVD file.
change_radius(domainElement, radius)
¶
Change the radius of the beam element mesh.
move_element(domainElement, nodePosition)
¶
Move the beam element mesh to the correct position.
resize_element(domainElement, dofmap, nodePos)
¶
Resize the beam element mesh to the correct length.
rotate_element(newDirection)
¶
Rotate the beam element mesh to the correct direction.
find_beam_element_mesh_name(number_point_ext, mesh_radius_int)
¶
Find the mesh name for given parameters and check if it exists.
generate_beam_element(number_point_ext, mesh_radius_int)
¶
Generate the beam element mesh using Gmsh if it does not exist.
clear_directory(directoryPath)
¶
directional_modulus(matS, theta, phi)
¶
Compute the directional stiffness modulus in a spherical coordinate system.
Parameters¶
matS : ndarray A 6-by-6 matrix defining the linear stress-to-strain relationship using the voigt notation.
float
Polar angle in degree.
float
Azimuthal angle in degree.
Returns¶
dirE : {float, ndarray} Directional stiffness modulus.