MPM Module

This module is for: * generating background mesh and material points. * defining boundary conditions and particle constraints. * generating CB-geo MPM input files that are associated with the current mesh and material points (e.g, entity_sets.json, mpm.json).

MPM configuration module for setting up Material Point Method simulations.

This module provides the MPMConfig class and helper functions for configuring MPM simulations. It handles mesh generation, particle placement, material properties, boundary conditions and more.

class mpm.MPMConfig(domain_origin, domain_length, title='mpm_input_config')[source]

Bases: object

Class for configuring Material Point Method simulations.

This class handles all aspects of MPM simulation setup including: - Mesh generation and configuration - Particle placement and properties - Material definitions - Boundary conditions - Analysis settings - Output configuration

Variables:
  • initial_stresses – Initial stress states for particles

  • materials – List of material definitions

  • cell_size – Size of mesh cells

  • n_cells_per_dim – Number of cells per dimension

  • nnode – Total number of nodes

  • nele – Total number of elements

  • mesh_info – Dictionary containing mesh information

  • mesh_coord_base – Base coordinates for mesh generation

  • entity_sets – Dictionary of entity sets

  • particle_group_id – Current particle group ID

  • particles_count – Total number of particles

  • particle_groups – Dictionary of particle groups

  • direction_mapping – Maps direction names to indices

  • ndims – Number of dimensions

  • domain_origin – Origin coordinates of domain

  • domain_length – Length of domain in each dimension

  • domain_ranges – Ranges of domain in each dimension

  • mpm_json – Dictionary containing MPM configuration

Parameters:
__init__(domain_origin, domain_length, title='mpm_input_config')[source]

Initialize MPM configuration.

Parameters:
  • domain_origin – Origin coordinates of simulation domain

  • domain_length – Length of domain in each dimension

  • title – Title for the configuration

Parameters:
static _generate_particle_grid(domain_origin, domain_length, cell_size, n_particle_per_cell, ndims)[source]

Generate a uniform grid of particle coordinates.

Parameters:
  • domain_origin (List[float]) – Origin coordinates of the domain

  • domain_length (List[float]) – Length of domain in each dimension

  • cell_size (List[float]) – Size of cells in each dimension

  • n_particle_per_cell (int) – Number of particles per cell per dimension

  • ndims (int) – Number of dimensions (2 or 3)

Returns:

Contains:
  • particles (np.ndarray): Array of particle coordinates

  • particle_distance (float): Distance between particles

  • particle_offset_distance (float): Offset distance from domain boundaries

Return type:

tuple

add_cell_entity(nset_id, ranges)[source]

Add a cell entity set based on coordinate ranges.

Parameters:
  • nset_id – Node set ID to assign to this entity set. Must be > 5 since 0-5 are reserved.

  • ranges – List of coordinate ranges [[x_min, x_max], [y_min, y_max], [z_min, z_max]]

Raises:

ValueError – If nset_id <= 5 or if ranges length doesn’t match domain dimensions

Note

The cell entity set is stored in self.entity_sets[“node_sets”] and contains all nodes within the specified coordinate ranges.

Parameters:
add_external_loadings(loadings)[source]

Add external loading conditions.

Parameters:

loadings – Dictionary containing loading conditions, including: - gravity: List of gravity components matching domain dimensions

Raises:

ValueError – If loading dimensions don’t match domain dimensions

Note

The loadings are stored in self.mpm_json[“external_loading_conditions”].

add_friction_constrains(constraints_info)[source]

Add friction constraints to boundary nodes.

Parameters:

constraints_info – List of constraint dictionaries, each containing: - ‘axis’: Direction to constrain (‘x’, ‘y’, or ‘z’) - ‘bound_loc’: Boundary location (‘start’ or ‘end’) - ‘sign_n’: Normal direction sign (-1 or 1) - ‘friction’: Friction coefficient

Note

The constraints are added to self.mpm_json[“mesh”][“boundary_conditions”] under the “friction_constraints” key.

add_initial_stress(option, top_surface, density, k0=None, undeformed_data=None)[source]

Add initial stress state to particles.

Parameters:
  • option – Method to calculate initial stress (‘k0’ or ‘stabilized_stress_data’)

  • top_surface – Mesh defining the top surface topography

  • density – Material density

  • k0 – Lateral earth pressure coefficient (required if option=’k0’)

  • undeformed_data – Data for stabilized stress calculation (required if option=’stabilized_stress_data’)

Raises:

Note

The initial stresses are stored in self.initial_stresses and written to ‘particles_stresses.txt’ when the configuration is saved.

Parameters:
  • option (str)

  • top_surface (Trimesh)

add_materials(materials=None, *, option=None, material_type=None)[source]

Add materials to the MPM simulation.

Parameters:
  • materials – List of material dictionaries with properties. Required unless using a special option.

  • option – Special material generation option. One of: {None, “random_field”}

  • material_type – Type of material model. One of: {None, “MohrCoulomb2D”}

Special Options:
random_field: Generates materials with random field values for each cell particle group.

Requires material_type=”MohrCoulomb2D”

Random field generation:

mpm.add_materials(option=”random_field”, material_type=”MohrCoulomb2D”)

Raises:

ValueError – If arguments are invalid or incompatible with model dimensions

Parameters:
add_mesh(n_cells_per_dim, outer_cell_thickness=0)[source]

Make mesh coordinate array & cell group.

Parameters:
  • n_cells_per_dim – Number of cells per dimension [nx, ny, nz]

  • outer_cell_thickness – Thickness of outer mesh layer. If provided, adds outer mesh beyond domain_ranges. If 0, mesh matches domain_ranges exactly.

Raises:

ValueError – If outer_cell_thickness is negative

Parameters:
add_particle_constraints(constraints_info)[source]
Parameters:

constraints_info – List of constraint dictionaries, each containing: - ‘pset_id’: Particle set ID to constrain - ‘axis’: Direction to constrain (‘x’, ‘y’, or ‘z’) - ‘velocity’: Velocity value to apply

Note

The constraints are added to self.mpm_json[“mesh”][“boundary_conditions”] under the “particles_velocity_constraints” key.

Parameters:

constraints_info (List[dict])

add_particles_csv(path, material_id, particle_group_id=None)[source]

Add particles from a CSV file.

Parameters:
  • path – Path to CSV file containing particle coordinates

  • material_id – Material ID to associate with these particles

  • particle_group_id – Optional particle group ID, auto-increments if None

add_particles_cube(cube_origin, cube_length, material_id, n_particle_per_cell, randomness=None, particle_group_id=None)[source]

Add a group of particles within a defined cubic region.

Parameters:
  • cube_origin – Lower edge coordinates of cube [x_min, y_min, (z_min)]

  • cube_length – Lengths of cube along each axis [x_len, y_len, (z_len)]

  • material_id – Material ID to assign to this particle group

  • n_particle_per_cell – Number of particles per dimension in each cell

  • randomness – Factor to randomly perturb particle positions

  • particle_group_id – ID to assign to this particle group

Raises:

ValueError – If domain dimensions are not 2D or 3D

Note

The particles are stored in self.particle_groups with the specified particle_group_id. If particle_group_id is None, it will be auto-incremented.

Parameters:

randomness (Optional[float])

add_particles_from_lines(layer_info, n_particle_per_cell)[source]

Add particles in layers defined by line segments.

Parameters:
  • layer_info – List of dictionaries containing: - line_points: Points defining upper boundary line of layer - material_id: Material ID for this layer - particle_group_id: (Optional) Group ID for these particles - randomness: (Optional) Factor for particle position randomization

  • n_particle_per_cell – Number of particles per cell per dimension

Raises:

ValueError – If used with 3D domain

Note

Line points should span entire x-domain range. First layer assumes y=0 as lower boundary.

Parameters:
  • layer_info (List)

  • n_particle_per_cell (int)

add_particles_from_polygon(polygon_info, n_particle_per_cell, randomness=None)[source]

Add particles within defined polygons.

Parameters:
  • polygon_info – List of dictionaries containing: - polygon_points: List of points defining polygon vertices - material_id: Material ID for particles in this polygon - particle_group_id: (Optional) Group ID for these particles

  • n_particle_per_cell – Number of particles per cell per dimension

  • randomness – Factor for random perturbation of particle positions

Raises:

ValueError – If used with 3D domain

Parameters:
add_particles_from_random_field(polygons_params, n_particle_per_cell, randomness=None, random_field_method='gstools')[source]

Add particles within polygons with random field values.

Parameters:
  • polygons_params – List of dictionaries containing: - polygon_points: List of points defining polygon vertices - random_params: Dict with random field parameters (mean, std, len_scale) - custom_correlation: (Optional) Custom correlation function (gstools.CovModel)

  • n_particle_per_cell – Number of particles per cell per dimension

  • randomness – Factor for random perturbation of particle positions

  • random_field_method – Method to generate random field (“gstools” or “utils”)

Note

Unlike other add_particles methods, this automatically sets particle_group_id based on the particles’ associated cell id, and material_id equals particle_group_id.

Raises:

ValueError – If used with 3D domain or if no particles found in polygon

Parameters:
add_particles_from_topography(lower_topography, upper_topography, n_particle_per_cell, material_id, z_find_method, base_find_method, z_fill_method='simple', randomness=None, overlap_tolerance=None, particle_group_id=None)[source]

Add particles between two topographic surfaces.

This method fills the space between two topographic surfaces with particles. The particles are placed in a regular grid pattern and can optionally be randomly perturbed.

Parameters:
  • lower_topography – Mesh defining the lower surface topography

  • upper_topography – Mesh defining the upper surface topography

  • n_particle_per_cell – Number of particles per cell per dimension

  • material_id – ID of material to assign to this particle set

  • z_find_method – Method to find z-coordinate of mesh (’’ or ‘’)

  • base_find_method – Method to find base area where surfaces overlap ‘alphashape’: Estimates x-y projection area using alphashape ‘simple’: Uses max/min x,y values, restricted to square shape

  • z_fill_method – Method to fill between lower and upper z-coordinates ‘simple’: Uses exact z-coordinate of mesh ‘round’: Uses nearest particle grid points

  • randomness – Factor to randomly perturb particle positions

  • overlap_tolerance – Maximum distance to consider particles as overlapping

  • particle_group_id – ID to assign to this particle group

Raises:

ValueError – If used with 2D domain (only supports 3D)

Note

The particles are stored in self.particle_groups with the specified particle_group_id. If particle_group_id is None, it will be auto-incremented.

Parameters:
  • lower_topography (Trimesh)

  • upper_topography (Trimesh)

  • n_particle_per_cell (int)

  • material_id (int)

  • z_find_method (str)

  • base_find_method (str)

  • z_fill_method (str)

  • randomness (Optional[float])

  • overlap_tolerance (Optional[float])

  • particle_group_id (Optional[int])

add_velocity_constraints(constraints_info)[source]

Add velocity constraints to boundary nodes.

Parameters:

constraints_info – List of constraint dictionaries, each containing: - ‘axis’: Direction to constrain (‘x’, ‘y’, or ‘z’) - ‘bound_loc’: Boundary location (‘start’ or ‘end’) - ‘velocity’: Velocity value to apply

Note

The constraints are added to self.mpm_json[“mesh”][“boundary_conditions”] under the “velocity_constraints” key.

Parameters:

constraints_info (List[Dict])

analysis(config)[source]

Configure analysis settings for the MPM simulation.

Parameters:

config (dict) – Dictionary containing analysis configuration parameters including: - type: Analysis type (e.g. ‘MPMExplicit2D’, ‘MPMExplicit3D’) - Other analysis-specific parameters

Raises:

ValueError – If analysis type dimensionality doesn’t match domain dimensions

Note

The analysis settings are stored in self.mpm_json[“analysis”]. Analysis type must match domain dimensionality (2D/3D).

define_boundary_entity()[source]

Define boundary entity sets for each boundary plane.

Creates node sets for each boundary plane of the domain. The node sets are stored in self.entity_sets[“node_sets”] with IDs 0-5 reserved for boundaries.

Each node set dictionary contains:
  • id: Node set ID (0-5)

  • set: List of node indices

  • axis: Boundary axis (‘x’, ‘y’, ‘z’)

  • bound_loc: Boundary location (‘start’ or ‘end’)

Note

Node set IDs 0-5 are hardcoded for boundaries. Other entity sets should use IDs > 5.

define_particle_entity()[source]

Define particle entity sets for the MPM solver.

This method creates particle entity sets that define different materials for each particle set. The entity sets are used as input to the MPM solver to specify material properties. Each particle set is assigned a unique ID and contains a list of particle indices.

Example

For two particle groups with indices [0,1,2] and [3,4,5], the entity sets would be:

{
    'particle_sets': [
        {'id': 0, 'set': [0,1,2]},
        {'id': 1, 'set': [3,4,5]}
    ]
}

Note

The particle sets are stored in self.entity_sets[‘particle_sets’] as a list of dictionaries. Each dictionary contains:

  • id: Unique identifier for the particle set (int)

  • set: List of particle indices belonging to this set (List[int])

For more details on entity set format, see: https://mpm.cb-geo.com/#/user/preprocess/entity-sets

post_processing(config)[source]

Configure post-processing settings for the MPM simulation.

Parameters:

config (dict) – Dictionary containing post-processing configuration parameters.

Note

The post-processing settings are stored in self.mpm_json[“post_processing”].

remove_overlapping_particles(overlap_tolerance)[source]

Remove overlapping particles between different particle groups.

This method iterates through particle groups in order and removes any particles that overlap with particles from previous groups. A particle is considered overlapping if it is within the overlap_tolerance distance of any existing particle.

The particle IDs are reordered after removing overlaps to maintain consecutive numbering.

Parameters:

overlap_tolerance – Maximum distance between particles to consider them as overlapping. Particles closer than this distance will be considered overlapping and one will be removed.

Raises:

ValueError – If no particle groups exist

Note

This modifies the particle_groups dictionary in place, updating both the particles and their IDs for each group.

Parameters:

overlap_tolerance (float)

visualize_mesh(save_path, node_indices=False)[source]

Visualize the mesh configuration in 3D.

Parameters:
  • save_path (str) – Path to save the visualization HTML file

  • node_indices (bool) – Whether to display node indices in the visualization

Note

Creates an interactive 3D plot using Plotly showing mesh nodes. The plot is saved as an HTML file at the specified path.

visualize_particles(save_path)[source]

Visualize particle groups in 3D.

Parameters:

save_path (str) – Path to save the visualization HTML file

Raises:

ValueError – If attempting to visualize 2D particle configuration

Note

Creates an interactive 3D plot using Plotly showing particles from all groups. Each particle group is plotted in a different color. The plot is saved as an HTML file at the specified path.

write(save_dir, file_name='mpm.json', save_options=None)[source]

Write MPM configuration and data files to disk.

Parameters:
  • save_dir (str) – Directory path to save the MPM input files

  • file_name (str) – Name of the MPM JSON input file with extension

  • save_options (dict, optional) – Dictionary controlling which files to save. Keys are file types, values are booleans. Available options: {

    ‘mesh’: True, # mesh.txt ‘particles’: True, # particles_*.txt ‘entity_sets’: True, # entity_sets.json ‘stresses’: True, # particles_stresses.txt ‘config’: True # mpm.json

    } If None, all files will be saved.

Note

This method writes several files based on save_options: - mesh.txt: Contains mesh node coordinates and cell groups - particles_*.txt: Particle coordinates for each particle group - entity_sets.json: Entity set definitions - particles_stresses.txt: Initial particle stresses if defined - mpm.json: Main configuration file

mpm.find_material_property(id, field, material_list)[source]

Find a specific property of a material by its ID.

Parameters:
  • id (int) – Material ID to search for

  • field (str) – Name of the material property to retrieve

  • material_list (List[dict]) – List of material dictionaries

Returns:

The value of the specified field for the material with matching ID

mpm.get_h5(directory, timestep, mpi)[source]

Read and combine HDF5 particle data files from MPI processes.

Parameters:
  • directory (str) – Directory containing the HDF5 files

  • timestep (int) – Timestep to read

  • mpi (int) – Number of MPI processes

Returns:

Combined particle data from all MPI processes

Return type:

pandas.DataFrame