pressomancy package¶
Subpackages¶
- pressomancy.object_classes package
- Submodules
- pressomancy.object_classes.crowder_class module
- pressomancy.object_classes.filament_class module
- pressomancy.object_classes.object_class module
- pressomancy.object_classes.otp_molecule_class module
- pressomancy.object_classes.quadriplex_class module
- pressomancy.object_classes.raspberry_sphere module
- pressomancy.object_classes.stoner_wohlfarth_part module
- pressomancy.object_classes.egg_model_part module
- pressomancy.object_classes.tel_sequence module
- Module contents
Submodules¶
pressomancy.helper_functions module¶
- class pressomancy.helper_functions.ManagedSimulation(aClass)[source]¶
Bases:
object
A decorator class to manage a singleton instance of a simulation object.
The ManagedSimulation class enforces that only one instance of a decorated simulation class can exist at a time. It provides methods to initialize, reinitialize, and manage the instance, while maintaining a shared espressomd.System object. This class is especially useful for simulations where global state must be consistent across multiple components.
- aClass¶
The class being decorated and managed as a singleton.
- Type:
type
- instance¶
The single instance of the decorated class. Initially set to None.
- Type:
object, optional
- init_args¶
Arguments used during the initialization of the decorated class.
- Type:
tuple
- init_kwargs¶
Keyword arguments used during the initialization of the decorated class.
- Type:
dict
- _espressomd_system¶
The shared ESPResSo system object, initialized during the first instantiation.
- Type:
espressomd.System
- __name__¶
The name of the singleton instance, including the decorated class name.
- Type:
str
- __qualname__¶
The qualified name of the singleton instance, including the decorated class’s qualified name.
- Type:
str
- __call__(*args, \*\*kwargs):
Creates and initializes the singleton instance, or raises an exception if it already exists.
- reinitialize_instance():
Recreates the instance while preserving the shared ESPResSo system object and resets the system state.
- __getattr__(name):
Forwards attribute access to the instance, raising an error if the instance is uninitialized.
- reinitialize_instance()[source]¶
Recreates the singleton instance without affecting the shared ESPResSo system object.
This method resets the decorated class instance while preserving the ESPResSo system object. It clears particles, interactions, and thermostat settings in the system, ensuring a clean state.
- class pressomancy.helper_functions.PartDictSafe(*args, **kwargs)[source]¶
Bases:
dict
A safe dictionary wrapper to enforce consistency and uniqueness of keys and values.
PartDictSafe ensures that: - Keys are unique and cannot be reassigned once set. - Values are unique and cannot be associated with multiple keys. - A default value is provided for missing keys using a customizable default factory.
This is especially useful for managing mappings where both the keys and values must remain consistent, such as particle types and their properties in simulations.
- default_factory¶
A function that returns the default value for missing keys. Defaults to list.
- Type:
callable
- sanity_check(key, value):
Validates that the key and value do not violate uniqueness constraints.
- set_default_factory(factory):
Updates the default factory used to generate default values for missing keys.
- __setitem__(key, value):
Sets a key-value pair in the dictionary after passing a sanity check.
- update(*args, \*\*kwargs):
Updates the dictionary with key-value pairs from another dictionary or iterable, enforcing sanity checks.
- __getitem__(key):
Retrieves the value for a key, initializing it with the default value if the key does not exist.
- sanity_check(key, value)[source]¶
Ensures the key and value do not violate uniqueness constraints.
- Parameters:
key (object) – The key to validate.
value (object) – The value to validate.
- Raises:
RuntimeError – If the key already exists with a different value or the value is already associated with another key.
- set_default_factory(factory)[source]¶
Updates the default factory used to generate default values for missing keys.
- Parameters:
factory (callable) – A function that returns the new default value for missing keys.
- update(*args, **kwargs)[source]¶
Updates the dictionary with key-value pairs from another dictionary or iterable.
- Parameters:
*args (tuple) – Positional arguments passed to the dict.update method.
**kwargs (dict) – Keyword arguments passed to the dict.update method.
- Raises:
RuntimeError – If any key-value pair violates the uniqueness constraints.
- class pressomancy.helper_functions.RoutineWithArgs(func=None, num_monomers=1, monomer_size=1.0, spacing=None)[source]¶
Bases:
object
A wrapper class to manage callable routines with configurable arguments.
The RoutineWithArgs class provides a way to encapsulate a callable function, allowing it to be called with predefined arguments. If no function is provided during initialization, a default routine (generic_routine_per_volume) is used.
- func¶
The function to be called. Defaults to generic_routine_per_volume.
- Type:
callable
- num_monomers¶
The number of monomers or items to process within the routine.
- Type:
int
- generic_routine_per_volume(**kwargs)[source]¶
A default routine to generate points within a spherical volume. Must be implemented by subclasses or overridden.
- static generic_routine_per_volume(**kwargs)[source]¶
A placeholder for a default routine to generate points within a spherical volume.
This method must be implemented by subclasses or overridden by specific instances.
- Parameters:
**kwargs (dict) – The arguments required for the routine.
- Raises:
NotImplementedError – If the method is called without being overridden.
- class pressomancy.helper_functions.SinglePairDict(key, value)[source]¶
Bases:
dict
A dictionary wrapper that enforces unique key-value pairs across all instances.
The SinglePairDict class ensures that each key and value are unique globally across all instances of the class. The dictionary is immutable after initialization, preventing modification or deletion of the stored key-value pair.
- _global_registry¶
A class-level dictionary that tracks all key-value pairs globally across instances.
- Type:
dict
- get_all_pairs():
Returns a copy of the globally registered key-value pairs across all instances.
- Properties()¶
- ----------
- key : object
The single key stored in the dictionary.
- value : object
The single value stored in the dictionary.
Examples
Creating a new SinglePairDict: >>> spd1 = SinglePairDict(‘key1’, ‘value1’) >>> spd1.key ‘key1’ >>> spd1.value ‘value1’
Attempting to reuse an existing key or value: >>> spd2 = SinglePairDict(‘key1’, ‘value2’) ValueError: Key ‘key1’ already exists in another instance.
Retrieving all globally registered pairs: >>> SinglePairDict.get_all_pairs() {‘key1’: ‘value1’}
- classmethod get_all_pairs()[source]¶
Returns all globally registered key-value pairs across instances.
- Returns:
A copy of the globally registered key-value pairs.
- Return type:
dict
- property key¶
Retrieves the single key stored in the dictionary.
- Returns:
The single key stored in the dictionary.
- Return type:
object
- property value¶
Retrieves the single value stored in the dictionary.
- Returns:
The single value stored in the dictionary.
- Return type:
object
- pressomancy.helper_functions.align_vectors(v1, v2)[source]¶
Compute the rotation matrix that aligns vector v1 to vector v2.
- Parameters:
v1 (numpy.ndarray) – The initial vector to align.
v2 (numpy.ndarray) – The target vector to align with.
- Returns:
A 3x3 rotation matrix that aligns v1 with v2.
- Return type:
numpy.ndarray
The function handles special cases where the vectors are already aligned or are opposite. It uses Rodrigues’ rotation formula for general cases.
- pressomancy.helper_functions.build_grid_and_adjacent(lattice_points, volume_side, cell_size)[source]¶
Builds a grid dictionary mapping each cell id (tuple) to a list of particle indices, and an adjacent-cells dictionary mapping each occupied cell id to a list of its adjacent cell ids (including itself), taking periodic boundary conditions into account.
- Parameters:
lattice_points (np.ndarray of shape (N, 3)) – Array of particle positions.
volume_side (float) – The side length of the cubic volume.
cell_size (float) – The grid cell size (typically set equal to the cuttoff distance).
- Returns:
grid (defaultdict(list)) – Dictionary mapping cell id (tuple of ints) to a list of particle indices in that cell.
num_cells (int) – The number of cells per dimension.
adjacent (dict) – Dictionary mapping each occupied cell id to a list of adjacent cell ids (as tuples), with periodic boundaries.
- pressomancy.helper_functions.calculate_pair_distances(points_a, points_b, box_length)[source]¶
Calculate the pair distances between two sets of points, considering periodic boundary conditions if provided.
- Parameters:
points_a (np.array of shape (N, 3)) – An array of points where N is the number of points in the first set.
points_b (np.array of shape (M, 3)) – An array of points where M is the number of points in the second set.
box_length (float, optional) – The length of the cubic box. If provided, periodic boundary conditions are applied.
- Returns:
distances – A 2D array of pair distances between each point in points_a and each point in points_b.
- Return type:
np.array of shape (N, M)
- pressomancy.helper_functions.fcc_lattice(radius, volume_side, scaling_factor=1.0, max_points_per_side=100)[source]¶
Generates a face-centered cubic (FCC) lattice of points within a cubic volume. The function creates an FCC crystal structure where spheres of given radius are arranged such that they touch along the face diagonal of the unit lattice.
- Parameters:
radius (float) – Radius of the spheres in the lattice.
volume_side (float) – Length of the cubic volume’s side.
scaling_factor (float, optional) – Factor to scale the radius of the spheres. Default is 1.0.
max_points_per_side (int, optional) – Maximum number of points allowed per dimension. Default is 100. If exceeded, lattice constant is increased.
- Returns:
Array of shape (N, 3) containing the coordinates of the lattice points, where N is the number of points in the FCC lattice.
- Return type:
np.ndarray
Notes
The lattice constant is calculated as 2*radius_scaled/sqrt(2), where radius_scaled = radius*scaling_factor.
If the number of points per side exceeds max_points_per_side, the lattice constant is gradually increased until the constraint is satisfied.
The function ensures the lattice fits within the given volume by removing the last row of points to avoid periodic boundary condition overlaps.
When the lattice constant is increased, a warning message is logged with the new value.
- pressomancy.helper_functions.generate_positions(self, min_distance)[source]¶
Generates random positions for objects in the simulation box, ensuring minimum distance between positions. Completely naive implementation
- Parameters:
min_distance – float | The minimum allowed distance between objects.
- Returns:
np.ndarray | Array of generated positions.
- pressomancy.helper_functions.generate_positions_directed_triples(no_objects, box_l, min_distance, director_list)[source]¶
- pressomancy.helper_functions.get_cross_lattice_nonintersecting_volumes(current_lattice_centers, current_lattice_grouped_part_pos, current_lattice_diam, other_lattice_centers, other_lattice_grouped_part_pos, other_lattice_diam, box_len, mode='cross_volumes')[source]¶
Calculate non-intersecting volumes between particles in two different lattices. This function determines which volumes from one lattice do not intersect with volumes from another lattice, considering periodic boundary conditions.
- Parameters:
current_lattice_centers (array-like) – Centers of volumes in the first lattice.
current_lattice_grouped_part_pos (array-like) – Particle positions grouped by volume for the first lattice.
current_lattice_diam (float) – Diameter of particles in the first lattice.
other_lattice_centers (array-like) – Centers of volumes in the second lattice.
other_lattice_grouped_part_pos (array-like) – Particle positions grouped by volume for the second lattice.
other_lattice_diam (float) – Diameter of particles in the second lattice.
box_len (float) – Length of the periodic box.
mode (str, optional) – Mode of calculation, either ‘cross_parts’ or ‘cross_volumes’. Default is ‘cross_volumes’.
- Returns:
Dictionary with volume IDs as keys and lists of boolean masks as values. Each mask indicates whether the volume from the first lattice intersects with corresponding volumes from the second lattice.
- Return type:
dict
Notes
The function uses a cutoff distance of (d1 + d2)/2 where d1, d2 are the diameters of particles in respective lattices. Particle pairs are considered non-intersecting if their separation is greater than (d1/n1 + d2/n2)/2, where n1, n2 are the number of particles in respective volumes.
- pressomancy.helper_functions.get_neighbours(lattice_points: ndarray, volume_side: float, cuttoff: float = 1.0) defaultdict [source]¶
Returns grouped_indices, where grouped_indices is a dictionary that maps each particle index to a list of neighbor indices within the cuttoff distance. Uses a grid-based method for efficiency, and reuses the min_img_dist function for distance calculations.
- Parameters:
lattice_points (np.ndarray of shape (N, 3)) – Array of particle positions.
volume_side (float) – The side length of the cubic volume.
cuttoff (float, optional) – The neighbor distance threshold.
- Returns:
grouped_indices – Dictionary mapping each particle index to a list of neighbor indices.
- Return type:
defaultdict[int, list[int]]
- pressomancy.helper_functions.get_neighbours_cross_lattice(lattice1, lattice2, volume_side, cuttoff=1.0)[source]¶
- pressomancy.helper_functions.get_orientation_vec(pos)[source]¶
Calculates the principal gyration axis of a filement as the orientation of a filament. Sometimes the np.linalg.eig() returns a complex number with 0 complex part wich confuses espresso. Therefore the ret values is cast to float explicitly
- Returns:
float | normalised principal gyration axis
- pressomancy.helper_functions.load_coord_file(file_path)[source]¶
load coordinates from a text file. the function allways staples a (0,0,0) as the first row!
- pressomancy.helper_functions.make_centered_rand_orient_point_array(center=array([0, 0, 0]), sphere_radius=1.0, num_monomers=1, spacing=None)[source]¶
Creates an array of points centered at a given position with random orientation.This function generates a linear array of points in 3D space, centered at a specified position with random orientation. It also returns the normalized orientation vector of the array.
- Parameters:
center (numpy.ndarray, default=np.array([0,0,0])) – The center point of the array in 3D space (x,y,z coordinates)
sphere_radius (float, default=1.0) – The radius of the sphere containing the points
num_monomers (int, default=1) – The number of points to generate
spacing (float, optional) – If provided, sets fixed spacing between points. The total chain length will be spacing * (num_monomers - 1), and the points will be centered around center.
- Returns:
A tuple containing: - orientation_vector (numpy.ndarray): Normalized vector indicating array orientation - points (numpy.ndarray): Array of 3D coordinates for each point
- Return type:
tuple
Notes
When spacing is provided, the positions along the line are given by:
positions = spacing * (np.arange(num_monomers) - (num_monomers - 1)/2)
ensuring that the distance between consecutive points is exactly ‘spacing’ and that the center of mass is at 0. The points are then rotated by a random orientation (given by theta and phi) and shifted by ‘center’.
- pressomancy.helper_functions.partition_cubic_volume(box_length, num_spheres, sphere_diameter, routine_per_volume=<pressomancy.helper_functions.RoutineWithArgs object>, flag='rand')[source]¶
Partitions a cubic volume into spherical regions and generates points within them. This function creates a face-centered cubic (FCC) lattice of spheres within a cubic volume and optionally generates points within each sphere according to a specified routine.
- Parameters:
box_length (float) – The length of the cubic volume’s side.
num_spheres (int) – The desired number of spherical regions to create.
sphere_diameter (float) – The diameter of each spherical region.
routine_per_volume (RoutineWithArgs, optional) – A callable object that generates points within each sphere. Default is empty RoutineWithArgs.
flag (str, optional) – Determines the arrangement of sphere centers. ‘rand’ for random shuffling. Default is ‘rand’.
- Returns:
Each tuple contains: - center (array-like): The coordinates of the sphere’s center - points (array-like): The generated points within the sphere (or center if no routine) - orientation (array-like): The orientation vector for the sphere
- Return type:
list of tuples
- pressomancy.helper_functions.partition_cubic_volume_oriented_rectangles(big_box_dim, num_spheres, small_box_dim, num_monomers)[source]¶
Partition a cubic volume into smaller rectangular regions and generate oriented points within each region.
This function divides a larger cubic box into smaller rectangular volumes based on the dimensions of the smaller boxes provided. It then generates a specified number of points within each smaller volume, ensuring they are oriented along a random direction.
- Parameters:
big_box_dim (array-like of shape (3,)) – Dimensions of the larger cubic box (lengths along x, y, and z axes).
num_spheres (int) – Number of smaller rectangular volumes to generate within the larger box.
small_box_dim (array-like of shape (3,)) – Dimensions of the smaller boxes (lengths along x, y, and z axes).
num_monomers (int) – Number of points to generate within each smaller box.
- Returns:
sphere_centers (ndarray of shape (num_spheres, 3)) – Coordinates of the centers of the selected rectangular volumes.
result (ndarray of shape (num_spheres, num_monomers, 3)) – Generated points within each rectangular volume, oriented along a random direction.
- Raises:
AssertionError – If the number of available rectangular volumes is less than num_spheres.
Notes
The function uses the dimensions of small_box_dim to determine the number of partitions along each axis.
When there are fewer partitions along an axis (e.g., one partition), alternate boxes along that axis are adjusted to ensure even distribution.
The generated points within each smaller box are spaced along a single direction determined by a random angle.
Examples
Partition a 10x10x10 box into smaller 2x2x2 volumes and generate 5 points in each volume: >>> big_box_dim = np.array([10.0, 10.0, 10.0]) >>> small_box_dim = np.array([2.0, 2.0, 2.0]) >>> num_spheres = 10 >>> num_monomers = 5 >>> centers, points = partition_cubic_volume_oriented_rectangles(big_box_dim, num_spheres, small_box_dim, num_monomers)
pressomancy.simulation module¶
- pressomancy.simulation.ManagedSimulation(cls)¶
- class pressomancy.simulation.Simulation(box_dim)[source]¶
Bases:
object
A singleton class designed to manage and simulate a suspension of objects within the ESPResSo molecular dynamics framework.
The Simulation class encapsulates the ESPResSo system and provides methods to configure the simulation, manage objects, and apply various interactions and constraints. It maintains a dictionary of simulation objects, tracks their properties, and delegates object-specific operations to the appropriate methods.
Key features include: - Managing particle types and their properties. - Configuring interactions like Lennard-Jones (LJ), Weeks-Chandler-Andersen (WCA), and magnetic interactions. - Supporting lattice Boltzmann (LB) fluid initialization and boundary setup. - Storing, setting, and removing simulation objects. - Providing utilities for avoiding instabilities, generating positions, and managing simulation data.
- no_objects¶
The number of objects currently stored in the simulation.
- Type:
int
- objects¶
A list of objects stored in the simulation.
- Type:
list
- part_types¶
A dictionary-like object tracking particle types and their associated properties.
- Type:
- seed¶
A random seed for reproducibility, generated at initialization.
- Type:
int
- partitioned¶
Indicates whether the simulation box is partitioned.
- Type:
bool
- part_positions¶
A list of particle positions generated for the simulation.
- Type:
list
- volume_size¶
The size of the volume assigned to each object.
- Type:
float
- volume_centers¶
A list of centers of the partitioned volumes.
- Type:
list
- set_sys(timestep, min_global_cut)[source]¶
Configures the ESPResSo system’s basic parameters, such as periodicity, time step, and cell system properties.
- modify_system_attribute(requester, attribute_name, action)[source]¶
Validates and modifies a system attribute if permitted by the object’s permissions.
- store_objects(iterable_list)[source]¶
Stores simulation objects and updates particle types and attributes.
- set_objects(objects)[source]¶
Generates random positions and orientations for managed objects and sets them using object-specific methods.
- unstore_objects(iterable_list)¶
Removes specified objects from the simulation and updates relevant attributes.
- delete_objects()¶
Deletes all parts owned by stored objects by calling their delete method.
- mark_for_collision_detection(object_type, part_type)[source]¶
Marks specific objects for collision detection and prepares them for covalent bond marking.
- init_magnetic_inter(actor_handle)[source]¶
Initializes direct summation magnetic interactions in the simulation.
- set_steric(key, wca_eps, sigma)[source]¶
Configures WCA interactions between specified particle types.
- set_steric_custom(pairs, wca_eps, sigma)[source]¶
Configures custom WCA interactions for specific particle type pairs.
- set_vdW(key, lj_eps, lj_size)[source]¶
Sets Lennard-Jones interactions for specified particle types.
- set_vdW_custom(pairs, lj_eps, lj_size)[source]¶
Configures custom Lennard-Jones interactions for specific particle type pairs.
- init_lb(kT, agrid, dens, visc, gamma, timestep)[source]¶
Initializes a lattice Boltzmann fluid with the specified parameters.
- avoid_explosion(F_TOL, MAX_STEPS, F_incr, I_incr)[source]¶
Caps forces iteratively to avoid simulation instabilities due to initial overlaps.
- magnetize(part_list, dip_magnitude, H_ext)[source]¶
Applies Langevin magnetization to compute dipole moments of particles.
- dump_to_init(path_to_dump, dungeon_witch_list, cnt)[source]¶
Appends simulation data for a specific timestep to an existing pickle dump.
Notes
The class assumes that the ESPResSo system is already instantiated and wraps the system handle during initialization. The initialisation and lifetime is managed by the decorator class.
Many methods rely on specific attributes or methods being implemented in the stored objects. This is why any object that is to be safely used by Simulation should use the SimulationObject metaclass.
This class is designed to be extensible for different types of interactions and constraints.
- avoid_explosion(F_TOL, MAX_STEPS=5, F_incr=100, I_incr=100)[source]¶
Iteratively caps forces to prevent simulation instabilities. :param F_TOL: float | Force change tolerance between iterations to determine convergence. :param MAX_STEPS: int | Maximum number of steps for force iteration. Default is 5. :param F_incr: int | Amount to increase force cap by each iteration. Default is 100. :param I_incr: int | Amount to increase integration steps by each iteration. Default is 100. :return: None
The method gradually increases both the force cap and integration timestep while monitoring the relative force change between iterations. If the relative change falls below F_TOL or MAX_STEPS is reached, the iteration stops.
- collect_instances_recursively(roots)[source]¶
Traverse each root in roots and return a flat preorder list of every object reachable via .associated_objects. Raises RuntimeError on any duplicate.
- create_flow_channel(slip_vel=(0, 0, 0))[source]¶
Sets up LB boundaries for a flow channel.
- Parameters:
slip_vel – tuple | Velocity of the slip boundary in the format (vx, vy, vz). Default is (0, 0, 0).
- Returns:
None
- dump_to_init(path_to_dump, dungeon_witch_list, cnt)[source]¶
Appends simulation data for a given timestep to an existing pickle dump.
This method reads data from a compressed pickle file, adds new data for the specified timestep, and writes the updated data back to the file.
- Parameters:
path_to_dump – str | Path to the pickle dump file.
dungeon_witch_list – list | A list of objects to be serialized and stored for the current timestep.
cnt – int | The current timestep counter to be used as a key in the dump.
- Returns:
None
- get_H_ext()[source]¶
Retrieves the current external magnetic field. Assumes there is only one active applied field!
- Returns:
tuple | The external magnetic field vector.
- init_lb(kT, agrid, dens, visc, gamma, timestep=0.01)[source]¶
Initializes the lattice Boltzmann (LB) fluid for the simulation.
This method configures an LB fluid using either CPU or GPU resources, depending on availability. It disables the thermostat, initializes particle velocities to zero, and sets the LB fluid parameters. If another active LB actor exists, it removes it before adding the new LB fluid.
- Parameters:
kT – float | Thermal energy (temperature) of the LB fluid.
agrid – int | Grid resolution for the LB method.
dens – float | Density of the LB fluid.
visc – float | Viscosity (kinematic) of the LB fluid.
gamma – float | Coupling constant for the thermostat.
timestep – float | Integration time step for the LB simulation. Default is 0.01.
- Returns:
LBFluid | The configured lattice Boltzmann fluid object.
- init_pickle_dump(path_to_dump)[source]¶
Initializes a pickle dump file to store simulation data.
This method creates a new compressed pickle file at the specified path and initializes it with an empty dictionary.
- Parameters:
path_to_dump – str | Path where the pickle dump file should be created.
- Returns:
tuple | A tuple containing the path to the dump file and an initial counter value (0).
- inscribe_part_group_to_h5(group_type=None, h5_data_path=None, mode='NEW')[source]¶
Inscribe one or more groups of simulation objects into an HDF5 file.
This method creates (or opens) an HDF5 file and, for each group_type: - Builds a flat list of particle handles and their coordinating indices - Creates /particles/<GroupName> and corresponding property datasets - Creates /connectivity/<GroupName>/ParticleHandle_to_<OwnerClass> tables - Creates /connectivity/<GroupName>/<Left>_to_<Right> object–object tables
- Parameters:
group_type (list of type) – A list of SimulationObject subclasses. All instances of each class in self.objects will be registered and inscribed.
h5_data_path (str) – Path to the HDF5 file to write (mode=’NEW’) or append (mode=’LOAD’).
mode ({‘NEW’, ‘LOAD’}, optional) –
‘NEW’ : create a fresh file structure (default).
‘LOAD’: open existing file and resume writing.
- Returns:
The starting global counter for writing time steps. Always 0 in ‘NEW’ mode; in ‘LOAD’ mode, the current number of already‑saved steps.
- Return type:
int
- Raises:
ValueError – If mode is not one of ‘NEW’ or ‘LOAD’.
ValueError – If group_type is not a list.
ValueError – In ‘LOAD’ mode, if different groups have mismatched saved step counts.
- load_pickle_dump(path_to_dump)[source]¶
Loads simulation data from a pickle dump file.
Reads a compressed pickle file from the specified path and returns the data along with the next timestep counter.
- Parameters:
path_to_dump – str | Path to the pickle dump file.
- Returns:
tuple | A tuple containing the path to the dump file and the next timestep counter based on the loaded data.
- magnetize(part_list, dip_magnitude, H_ext)[source]¶
Apply the langevin magnetisation law to determine the magnitude of the dipole moment of each particle in part_list, projected along H_tot=H_ext+tot_dip_fld. part_list should be a iterable that contains espresso particleHandle objects.
- Parameters:
part_list – iterable(ParticleHandle) | ParticleSlice could work but prefer to wrap with the list() constructor.
dip_magnitude – float
H_ext – float
- Returns:
None
- mark_for_collision_detection(object_type=<class 'pressomancy.object_classes.quadriplex_class.Quadriplex'>, part_type=666)[source]¶
- modify_system_attribute(requester, attribute_name, action)[source]¶
Validates and modifies a Simulation attribute if allowed by the permissions.
- Parameters:
requester – The object requesting the modification.
attribute_name – str | The name of the attribute to modify.
action – callable | A function that takes the current attribute value as input and modifies it.
- Returns:
None
- object_permissions = ['part_types']¶
- sanity_check(object)[source]¶
Method that checks if the object has the required features to be stored in the simulation. If the object has the required features it is stored in the self.objects list.
- set_H_ext(H=(0, 0, 1.0))[source]¶
Sets an espressomd.constraints.HomogeneousMagneticField in the simulation. Will delete any other HomogeneousMagneticField constraint if present. Safe to use for rotating or AC magnetic fileds.
- Parameters:
H – tuple | The external magnetic field vector. Default is (0, 0, 1).
- Returns:
None
- set_objects(objects)[source]¶
Set objects’ positions and orientations in the simulation box. This method places objects in the simulation box using a partitioning scheme. For the first placement, it generates exactly the required number of positions. For subsequent placements, it searches for non-overlapping positions with existing objects. :Parameters: objects (list) – A list of simulation objects to be placed. All objects must be of the same type.
- Raises:
AssertionError – If not all objects are of the same type.
NotImplementedError – If trying to place objects when more than one previous partition exists.
Notes
The current implementation supports placing objects either in an empty system or in a system with exactly one previous partition. The method uses partition_cubic_volume to generate positions and orientations, and for subsequent placements, ensures no overlaps with existing objects through get_cross_lattice_nonintersecting_volumes. The method automatically adjusts the search space (by increasing the factor) if it cannot find enough non-overlapping positions in subsequent placements.
- set_steric(key=('nonmagn',), wca_eps=1.0, sigma=1.0)[source]¶
Set WCA interactions between particles of types given in the key parameter. :param key: tuple of keys from self.part_types | Default only nonmagn WCA :param wca_epsilon: float | strength of the steric repulsion.
- Returns:
None
Interaction length is allways determined from sigma.
- set_steric_custom(pairs=[(None, None)], wca_eps=[1.0], sigma=[1.0])[source]¶
Configures custom Weeks-Chandler-Andersen (WCA) interactions for specified particle type pairs.
This method explicitly sets the WCA interaction parameters (epsilon and sigma) for each pair of particle types provided. It ensures that each interaction pair has corresponding epsilon and sigma values.
- Parameters:
pairs – list of tuples | List of particle type pairs (keys from self.part_types) for which interactions are defined. Defaults to [(None, None)].
wca_eps – list of float | Strength of the WCA repulsion (epsilon) for each pair. Defaults to [1.0].
sigma – list of float | Interaction range (sigma) for each pair. Defaults to [1.0].
- Returns:
None
- Raises:
AssertionError – If the lengths of pairs, wca_eps, and sigma do not match.
- set_sys(timestep=0.01, min_global_cut=3.0, have_quaternion=False)[source]¶
Set espresso cellsystem params, and import virtual particle scheme. Run automatically on initialisation of the System class.
- set_vdW(key=('nonmagn',), lj_eps=1.0, lj_size=1.0)[source]¶
Configures Lennard-Jones (LJ) interactions for specified particle types.
This method sets the LJ interaction parameters (epsilon and sigma) for particle types listed in the key parameter. The interaction cutoff is automatically set to 2.5 times the LJ size (sigma).
- Parameters:
key – tuple of str | Particle type keys from self.part_types for which interactions are defined. Defaults to (‘nonmagn’,).
lj_eps – float | Strength of the LJ attraction (epsilon). Defaults to 1.0.
lj_size – float | Interaction range (sigma). Defaults to 1.0.
- Returns:
None
- set_vdW_custom(pairs=[(None, None)], lj_eps=[1.0], lj_size=[1.0])[source]¶
Custom setter for Lennard-Jones (LJ) interactions between specified particle type pairs.
This method allows for the explicit definition of LJ interaction parameters (epsilon and sigma) for each pair of particle types in the simulation.
- Parameters:
pairs – list of tuples | Each tuple specifies a pair of keys from self.part_types for which interactions are defined. Defaults to [(None, None)].
lj_eps – list of float | Strength of the LJ interaction for each pair. Defaults to [1.0].
lj_size – list of float | Interaction range (sigma) for each pair. Defaults to [1.0].
- Returns:
None
- Raises:
AssertionError – If the lengths of pairs, lj_eps, and lj_size are not equal.
- store_objects(iterable_list)[source]¶
Method stores objects in the self.objects dict, if the object has a n_part and part_types attributes, and the list of objects passed to the method is commesurate with the system level attribute n_tot_parts. Populates the self.part_types attribute with types found in the objects that are stored. All objects that are stored should have the same types stored, but this is not checked explicitly