"""
Module providing the Sample class for molecular trajectory sampling.
This module defines the Sample class, which manages the sampling of molecular
trajectories using various samplers. It supports parallel processing using
the multiprocessing module and integrates with the Ovito library for trajectory
handling. The Sample class allows users to add different samplers, configure
sampling parameters, and execute the sampling process either in parallel or
serially.
"""
import itertools
import logging
import multiprocessing as mp
import os
import sys
from typing import Literal
import numpy as np
from numpy.typing import NDArray
from porereax.angle import AngleSampler
from porereax.bond_length import BondLengthSampler
from porereax.charge import ChargeSampler
from porereax.density import BondDensitySampler, DensitySampler, ReactionSampler
from porereax.meta_sampler import Sampler
from porereax.molecule_structure import MoleculeStructureSampler
from porereax.rdf import RdfSampler
from porereax.regions import Region
from porereax.utils import _neighbor_atoms_excluding, read_pore_yml
logger = logging.getLogger(__name__)
def _matches_bond_spec(
neighbor_atoms, atom_types, specs, bond_topology, bond_enum, parent_atom
):
"""
Check whether the bonded neighbours of an atom can be matched, one-to-one,
to a list of required nested bonding-environment specs.
Parameters
----------
neighbor_atoms : np.ndarray
Indices of the atom's bonded neighbours (excluding the edge back to
its own parent, if any).
atom_types : np.ndarray
Particle type of each atom in the current frame.
specs : list
`bonds_spec` list built by `_build_mol_dictionary`: one
`{"type_ids": frozenset, "mol": mol}` entry per required neighbour.
bond_topology : np.ndarray
(num_bonds, 2) array of atom index pairs for the current frame.
bond_enum : ovito.data.BondsEnumerator
Enumerator used to look up the bonds of a given atom.
parent_atom : int
Index of the atom whose neighbours are being matched (becomes the
"exclude_atom" when recursing one hop further).
Returns
-------
bool
True if some assignment of `neighbor_atoms` to `specs` satisfies
every spec's type and (if present) its own nested bonding requirement.
"""
if len(neighbor_atoms) != len(specs):
return False
for permutation in itertools.permutations(neighbor_atoms):
if all(
_matches_single_spec(
neighbor, spec, atom_types, bond_topology, bond_enum, parent_atom
)
for neighbor, spec in zip(permutation, specs, strict=True)
):
return True
return False
def _matches_single_spec(
neighbor, spec, atom_types, bond_topology, bond_enum, parent_atom
):
"""
Check whether one bonded neighbour satisfies one required nested spec.
Parameters
----------
neighbor : int
Index of the candidate neighbour atom.
spec : dict
One `{"type_ids": frozenset, "mol": mol}` entry, see `_matches_bond_spec`.
atom_types : np.ndarray
Particle type of each atom in the current frame.
bond_topology : np.ndarray
(num_bonds, 2) array of atom index pairs for the current frame.
bond_enum : ovito.data.BondsEnumerator
Enumerator used to look up the bonds of a given atom.
parent_atom : int
Index of the atom `neighbor` is bonded to in this match (excluded
when looking up `neighbor`'s own further bonds).
Returns
-------
bool
True if `neighbor` has the required type and, if the spec requires
it, its own further bonding environment also matches.
"""
if atom_types[neighbor] not in spec["type_ids"]:
return False
mol = spec["mol"]
if mol["bonds"] is None:
return True
further_atoms = _neighbor_atoms_excluding(
neighbor, parent_atom, bond_topology, bond_enum
)
if list(atom_types[further_atoms]) not in mol["bonds"]:
return False
if mol["bonds_spec"] is not None:
return _matches_bond_spec(
further_atoms,
atom_types,
mol["bonds_spec"],
bond_topology,
bond_enum,
neighbor,
)
return True
[docs]
class Sample:
"""
Class to manage sampling of molecular trajectories.
A ``Sample`` object loads a LAMMPS trajectory (``.lammpstrj``) and the
matching bond file (``.bonds``), registers one or more samplers with the
``add_*_sampling`` methods and runs them over all frames with
:meth:`sample`. Each sampler writes its result to ``<name_out>.obj``,
which can be loaded with :func:`porereax.get_data` or plotted with
:func:`porereax.plot_data`.
Progress is reported via the ``porereax.sample`` logger; call
``logging.basicConfig(level=logging.INFO)`` to see it.
Example
-------
>>> sampler = Sample(atom_lib, atom_masses, "run_0.lammpstrj", "run_0.bonds")
>>> sampler.add_molecule_structure_sampling("molecule_structure")
>>> sampler.sample()
"""
def __init__(
self,
atom_lib: dict,
masses: dict,
trajectory_file: str,
bond_file: str | None = None,
system: str | None = None,
start_end_nthframe: tuple[int, int, int] = (0, -1, 1),
):
"""
Initialise Sample instance.
To create a Sample instance, ensure that the 'ovito' module is not
already imported in the current Python session, as it may lead to
conflicts during parallel processing.
Parameters
----------
atom_lib : dict
Library mapping atom names to types.
masses : dict
Dictionary mapping atom names to their masses.
trajectory_file : str
Path to the trajectory file.
bond_file : str, optional
Path to the bond file.
system : str, optional
Path to a pore YAML file describing the system geometry. Required
for the 'Pore1D' and 'Pore2D' density dimensions.
start_end_nthframe : tuple, optional
Tuple specifying (start_frame, end_frame, nth_frame) for sampling.
"""
if "forkserver" in mp.get_all_start_methods():
ctx = mp.get_context("forkserver")
elif "spawn" in mp.get_all_start_methods():
ctx = mp.get_context("spawn")
else:
ctx = mp.get_context("fork")
if "ovito" in sys.modules:
raise RuntimeError(
"The 'ovito' module is already imported. Please remove it from the "
"loaded modules to avoid conflicts during parallel processing. "
"This is necessary because the OS does not support the "
"'spawn' start method."
)
with ctx.Pool(1) as pool:
num_particles, num_frames, box = pool.apply_async(
self._get_trajectory_data,
(
trajectory_file,
bond_file,
atom_lib,
),
).get()
logger.info(
f"Trajectory has {num_particles} particles and {num_frames} frames."
)
start_frame, end_frame, nth_frame = start_end_nthframe
self._init_helper(
atom_lib,
masses,
trajectory_file,
bond_file,
system,
start_frame,
end_frame,
nth_frame,
num_particles,
num_frames,
box,
)
def _init_helper(
self,
atom_lib,
masses,
trajectory_file,
bond_file,
system,
start_frame,
end_frame,
nth_frame,
num_particles,
num_frames,
box,
):
"""
Helper function to initialise Sample instance.
Parameters
----------
atom_lib : dict
Library mapping atom names to types.
masses : dict
Dictionary mapping atom names to their masses.
trajectory_file : str
Path to the trajectory file.
bond_file : str, optional
Path to the bond file.
system : str, optional
Path to a pore YAML file describing the system geometry. Required
for the 'Pore1D' and 'Pore2D' density dimensions.
start_frame : int
Starting frame for sampling.
end_frame : int
Ending frame for sampling.
nth_frame : int
Step size for frame sampling.
num_particles : int
Number of particles in the trajectory.
num_frames : int
Total number of frames in the trajectory.
box : np.ndarray
Simulation box dimensions.
"""
self.trajectory_file = os.path.abspath(trajectory_file)
self.bond_file = os.path.abspath(bond_file) if bond_file else None
self.system = system # is only used to pass to the subprocesses
self.sampler_inputs = {
"charge_samplers": [],
"density_samplers": [],
"bond_density_samplers": [],
"angle_samplers": [],
"bond_length_samplers": [],
"molecule_structure_samplers": [],
"rdf_samplers": [],
"reaction_samplers": [],
}
# Registry mapping sampler_inputs key -> (SamplerClass, kind, extra_kwarg_keys)
self._SAMPLER_REGISTRY = {
"charge_samplers": (ChargeSampler, "atom", ["atoms", "range"]),
"density_samplers": (
DensitySampler,
"atom",
["atoms", "num_bins", "direction", "conditions"],
),
"bond_density_samplers": (
BondDensitySampler,
"bond",
["bonds", "num_bins", "direction", "conditions"],
),
"angle_samplers": (AngleSampler, "atom", ["atoms", "num_bins", "angle"]),
"bond_length_samplers": (
BondLengthSampler,
"bond",
["bonds", "num_bins", "range"],
),
"molecule_structure_samplers": (
MoleculeStructureSampler,
"atom",
["steps"],
),
"rdf_samplers": (RdfSampler, "atom", ["pairs", "num_bins", "r_max"]),
"reaction_samplers": (
ReactionSampler,
"atom",
["reactions", "num_bins", "direction", "position"],
),
}
self.samplers: list[Sampler] = []
self.molecules = {}
self.bonds = {}
# Check atom library
if not isinstance(atom_lib, dict):
raise TypeError(
"atom_lib must be a dictionary mapping atom names to types."
)
if len(atom_lib) != len(set(atom_lib.values())) or len(atom_lib) != len(
set(atom_lib.keys())
):
raise ValueError(
"atom_lib must have a one-to-one mapping of atom names to types."
)
self.type_to_name = {v: k for k, v in atom_lib.items()}
self.name_to_type = atom_lib
# Check and set masses
if not isinstance(masses, dict):
raise TypeError("masses must be a dictionary mapping atom names to masses.")
if set(masses.keys()) != set(atom_lib.keys()):
raise ValueError("masses keys must match atom_lib keys.")
self.masses = masses
# Validate start and end frame values
if (
(start_frame < 0)
or (end_frame < -1)
or (start_frame > end_frame and end_frame != -1)
or (start_frame >= num_frames)
or (end_frame >= num_frames)
):
raise ValueError(
f"Invalid start_end frame range. The trajectory has "
f"{num_frames} frames and the provided range is "
f"({start_frame}, {end_frame})."
)
self.start_frame = start_frame
self.end_frame = end_frame if end_frame != -1 else num_frames - 1
self.nth_frame = nth_frame
self.num_particles = num_particles
self.box = box
self.frames = range(self.start_frame, self.end_frame + 1, self.nth_frame)
self.num_frames = len(self.frames)
self.system_properties = read_pore_yml(system) if system else None
@staticmethod
def _get_trajectory_data(trajectory_file, bond_file, atom_lib):
"""
Extract trajectory metadata using Ovito.
Parameters
----------
trajectory_file : str
Path to the trajectory file.
bond_file : str, optional
Path to the bond file.
atom_lib : dict
Library mapping atom names to types.
Returns
-------
num_particles : int
Number of particles in the trajectory.
num_frames : int
Total number of frames in the trajectory.
box : np.ndarray
Simulation box dimensions.
"""
os.environ["OVITO_THREAD_COUNT"] = "1"
from ovito.io import import_file
from ovito.modifiers import LoadTrajectoryModifier
# Load trajectory
if not os.path.isfile(trajectory_file):
raise FileNotFoundError(f"Trajectory file '{trajectory_file}' not found.")
pipeline = import_file(trajectory_file)
if bond_file:
if not os.path.isfile(bond_file):
raise FileNotFoundError(f"Bond file '{bond_file}' not found.")
bond_modifier = LoadTrajectoryModifier()
bond_modifier.source.load(bond_file)
pipeline.modifiers.append(bond_modifier)
# Get and validate trajectory meta data
first_frame = pipeline.compute()
if first_frame.particles.count == 0:
raise ValueError("No particles found in the trajectory file.")
if first_frame.particles.bonds is None:
raise ValueError(
"No bonds found. Ensure bond_file is provided or the "
"trajectory contains bond data."
)
type_set = {int(t) for t in first_frame.particles.particle_types.array}
atom_type_set = set(atom_lib.values())
if type_set > atom_type_set:
raise ValueError(
f"Atom types in trajectory {sorted(type_set)} do not match "
f"those in atom_lib {sorted(atom_type_set)}. Types missing "
f"from atom_lib: {sorted(type_set - atom_type_set)}."
)
num_particles = first_frame.particles.count
if pipeline.source is None:
raise ValueError(
"Pipeline source is None. Make sure the trajectory file is "
"valid and contains frames."
)
num_frames = pipeline.source.num_frames
box = np.diagonal(first_frame.cell.matrix)
return num_particles, num_frames, box
# --------------------------- Add Sampler Methods ---------------------------
[docs]
def add_molecule_structure_sampling(
self, name_out: str, region: Region = "Box", steps: int = 1
):
"""
Add sampling for molecule structures to analyse the bonding of atoms
and identify substructures.
Parameters
----------
name_out : str
Name of the output directory and object file of the sampler data
region : Region, optional
Region of the box to sample. Supported: "Box", "Reservoir", "Pore",
"Wall", or a user-defined function that takes atom positions
(N, 3) as input and returns a boolean mask (N,).
steps : int, optional
Number of bonding "steps" from the central atom to search for. Default
is 1 (only directly bonded neighbours, e.g. "O(Si+Si)"). Step 2 would
include information about the Si neighbours' in that example, e.g.
"O(Si(O+O+O)+Si(O+O+O))", and so on for larger values.
"""
dimension = "MoleculeStructure"
inputs = {
"name_out": name_out,
"dimension": dimension,
"region": region,
"steps": steps,
}
self.sampler_inputs["molecule_structure_samplers"].append(inputs)
[docs]
def add_charge_sampling(
self,
name_out: str,
atoms: list[dict],
region: Region = "Box",
range=(-2.0, 2.0),
):
"""
Add sampling for charge distribution of the central atom in the
specified atom structures.
Parameters
----------
name_out : str
Name of the output directory and object file of the sampler data
atoms : list
List of atom structures to sample. Each atom structure is defined
as a dictionary in the format: {"atom": "a", "bonds": [b, b, c,
...]}, where a is the central atom and b, c, ... are the bonded
atoms. With a, b, c being atom identifiers. The order of atoms in
the "bonds" list does not matter. The "bonds" list can be empty
to indicate that the atom is not bonded to any other atoms. If
the dictionary does not contain the "bonds" key, every atom of
type a will be sampled regardless of its bonding environment.
region : Region, optional
Region of the box to sample. Supported: "Box", "Reservoir", "Pore",
"Wall", or a user-defined function that takes atom positions
(N, 3) as input and returns a boolean mask (N,).
range : tuple, optional
Range (min, max) in e for which to compute the histogram. Default
is (-2.0, 2.0).
"""
dimension = "Histogram"
inputs = {
"name_out": name_out,
"atoms": atoms,
"dimension": dimension,
"region": region,
"range": range,
}
self.sampler_inputs["charge_samplers"].append(inputs)
[docs]
def add_density_sampling(
self,
name_out: str,
atoms: list[dict],
dimension: str,
region: Region = "Box",
num_bins=200,
direction="z",
conditions: dict | None = None,
):
"""
Add sampling for time or position density distribution of the
specified atom structures. For positional sampling the position of
the central atom is used.
Parameters
----------
name_out : str
Name of the output directory and object file of the sampler data
atoms : list
List of atom structures to sample. Each atom structure is defined
as a dictionary in the format: {"atom": "a", "bonds": [b, b, c,
...]}, where a is the central atom and b, c, ... are the bonded
atoms. With a, b, c being atom identifiers. The order of atoms in
the "bonds" list does not matter. The "bonds" list can be empty
to indicate that the atom is not bonded to any other atoms. If
the dictionary does not contain the "bonds" key, every atom of
type a will be sampled regardless of its bonding environment.
dimension : str
Sampling dimension. Supported: "Time", "Cartesian1D", "Cartesian2D",
"Pore1D", "Pore2D".
- "Time": Samples the amount of atom structures over time.
- "Cartesian1D": Samples the amount of atom structures along a
specified direction (x, y, or z) in the simulation box.
- "Cartesian2D": Samples the amount of atom structures in a 2D
plane (xy, xz, or yz) in the simulation box.
- "Pore1D"/"Pore2D": Same as "Cartesian1D"/"Cartesian2D", but in
pore-relative coordinates (r, phi, d). Requires `Sample(...,
system=...)` to be given a cylindrical pore YAML.
region : Region, optional
Region of the box to sample. Supported: "Box", "Reservoir", "Pore",
"Wall", or a user-defined function that takes atom positions
(N, 3) as input and returns a boolean mask (N,).
num_bins : int, optional
Number of bins for position sampling. Not used for time sampling.
direction : str, optional
Direction along which to sample. Options depending on the dimension:
- For "Cartesian1D": use ("x", "y", or "z").
- For "Cartesian2D": use ("xy", "xz", or "yz").
- For "Pore1D": use ("r", "p", or "d") for radial distance,
azimuthal angle, or distance from the nearest pore mouth.
- For "Pore2D": use ("rp", "rz", or "pz").
conditions : dict, optional
Dictionary of conditions to filter atoms during sampling.
Supported conditions:
- "Charge": tuple (min_charge, max_charge) to filter atoms by
charge.
- "Angle": tuple (min_angle, max_angle) to filter atoms by angle
formed with bonded atoms.
"""
inputs = {
"name_out": name_out,
"atoms": atoms,
"dimension": dimension,
"region": region,
"num_bins": num_bins,
"direction": direction,
"conditions": conditions if conditions is not None else {},
}
self.sampler_inputs["density_samplers"].append(inputs)
[docs]
def add_angle_sampling(
self,
name_out: str,
atoms: list[dict],
region: Region = "Box",
num_bins=180,
angle="all",
):
"""
Add sampling for angle distribution of the specified atom structures.
The angle is defined by the central atom and its bonded atoms.
Parameters
----------
name_out : str
Name of the output directory and object file of the sampler data
atoms : list
List of atom structures to sample. Each atom structure is defined
as a dictionary in the format: {"atom": "a", "bonds": [b, b, c,
...]}, where a is the central atom and b, c, ... are the bonded
atoms. With a, b, c being atom identifiers. The order of atoms in
the "bonds" list does not matter. The "bonds" list can be empty
to indicate that the atom is not bonded to any other atoms. If
the dictionary does not contain the "bonds" key, every atom of
type a will be sampled regardless of its bonding environment.
region : Region, optional
Region of the box to sample. Supported: "Box", "Reservoir", "Pore",
"Wall", or a user-defined function that takes atom positions
(N, 3) as input and returns a boolean mask (N,).
num_bins : int, optional
Number of bins for the histogram. Default is 180.
angle : str, optional
Angle of interested atoms. Supported: "all", "a-b-c"
- "all": Samples all angles formed by the central atom and all of
its bonded atoms.
- "a-b-c": Samples only the angle formed by the central atom (b)
and two specific bonded atoms (a and c), regardless of other
bonded atoms d, ... With a, b, c being atom identifiers.
"""
dimension = "Histogram"
inputs = {
"name_out": name_out,
"atoms": atoms,
"dimension": dimension,
"region": region,
"num_bins": num_bins,
"angle": angle,
}
self.sampler_inputs["angle_samplers"].append(inputs)
[docs]
def add_bond_density_sampling(
self,
name_out: str,
bonds: list[dict],
dimension: str,
region: Region = "Box",
num_bins=200,
direction="z",
conditions: dict | None = None,
):
"""
Add sampling for time or position density distribution of the
specified bonds. For positional sampling the position of the bond
center is used.
Parameters
----------
name_out : str
Name of the output directory and object file of the sampler data
bonds : list
List of bonds to sample. Each bond is defined as a dictionary in
the format: {"bond": "a-b", "bonds_A": [c, ...], "bonds_B": [d,
...]}, where a and b are the bonded atoms, and c, d, ... are the
atoms bonded to A and B, respectively. With a, b, c, d being atom
identifiers. Atom b/a does not need to be added to the
"bonds_A"/"bonds_B" list. The order of atoms in the "bonds_A" and
"bonds_B" lists does not matter. The "bonds_A" and "bonds_B"
lists can be empty to indicate that the atoms a and b are not
bonded to any other atoms. If the dictionary does not contain the
"bonds_A" or "bonds_B" keys, every bond of type a-b will be
sampled regardless of its bonding environment.
dimension : str
Sampling dimension. Supported: "Time", "Cartesian1D", "Cartesian2D",
"Pore1D", "Pore2D".
- "Time": Samples the amount of the specified bonds over time.
- "Cartesian1D": Samples the amount of the specified bonds along
a specified direction (x, y, or z) in the simulation box.
- "Cartesian2D": Samples the amount of the specified bonds in a
2D plane (xy, xz, or yz) in the simulation box.
- "Pore1D"/"Pore2D": Same as "Cartesian1D"/"Cartesian2D", but in
pore-relative coordinates (r, phi, d), using the bond midpoint.
Requires `Sample(..., system=...)` to be given a cylindrical
pore YAML.
region : Region, optional
Region of the box to sample. Supported: "Box", "Reservoir", "Pore",
"Wall", or a user-defined function that takes atom positions
(N, 3) as input and returns a boolean mask (N,).
num_bins : int, optional
Number of bins for position sampling. Not used for time sampling.
direction : str, optional
Direction along which to sample. Options depending on the dimension:
- For "Cartesian1D": use ("x", "y", or "z").
- For "Cartesian2D": use ("xy", "xz", or "yz").
- For "Pore1D": use ("r", "p", or "d") for radial distance,
azimuthal angle, or distance from the nearest pore mouth.
- For "Pore2D": use ("rp", "rz", or "pz").
conditions : dict, optional
Dictionary of conditions to filter bonds during sampling.
Supported conditions:
- "Bond Length": tuple (min_len, max_len) to filter bonds by bond length.
"""
inputs = {
"name_out": name_out,
"bonds": bonds,
"dimension": dimension,
"region": region,
"num_bins": num_bins,
"direction": direction,
"conditions": conditions if conditions is not None else {},
}
self.sampler_inputs["bond_density_samplers"].append(inputs)
[docs]
def add_bond_length_sampling(
self,
name_out: str,
bonds: list[dict],
dimension: Literal["Bond Length", "Bond Order"] = "Bond Length",
region: Region = "Box",
num_bins=200,
range=(0.0, 3.0),
):
"""
Add sampling for bond length or bond order distribution of the specified bonds.
Parameters
----------
name_out : str
Name of the output directory and object file of the sampler data
bonds : list
List of bonds to sample. Each bond is defined as a dictionary in
the format: {"bond": "a-b", "bonds_A": [c, ...], "bonds_B": [d,
...]}, where a and b are the bonded atoms, and c, d, ... are the
atoms bonded to A and B, respectively. With a, b, c, d being atom
identifiers. Atom b/a does not need to be added to the
"bonds_A"/"bonds_B" list. The order of atoms in the "bonds_A" and
"bonds_B" lists does not matter. The "bonds_A" and "bonds_B"
lists can be empty to indicate that the atoms a and b are not
bonded to any other atoms. If the dictionary does not contain the
"bonds_A" or "bonds_B" keys, every bond of type a-b will be
sampled regardless of its bonding environment.
dimension : str
Sampling dimension. Supported: "Bond Length" and "Bond Order"
region : Region, optional
Region of the box to sample. Supported: "Box", "Reservoir", "Pore",
"Wall", or a user-defined function that takes atom positions
(N, 3) as input and returns a boolean mask (N,).
num_bins : int, optional
Number of bins for the histogram. Default is 200.
range : tuple, optional
Range (min, max) for which to compute the histogram. Default is
(0.0, 3.0).
- For "Bond Length": range is in Angstroms.
- For "Bond Order": range is in bond order units defined by the
ReaxFF force field.
"""
inputs = {
"name_out": name_out,
"bonds": bonds,
"dimension": dimension,
"region": region,
"num_bins": num_bins,
"range": range,
}
self.sampler_inputs["bond_length_samplers"].append(inputs)
[docs]
def add_rdf_sampling(
self,
name_out: str,
pairs: list[tuple[dict, dict]],
region: Region = "Box",
num_bins=200,
r_max=7.0,
):
"""
Add sampling for radial distribution function (RDF) of the specified atom pairs.
Parameters
----------
name_out : str
Name of the output directory and object file of the sampler data
pairs : list
List of atom pairs to sample. Each pair is defined as a tuple of
two dictionaries in the format: ({"atom": "a", "bonds": [...]},
{"atom": "b", "bonds": [...]}) where a and b are atom
identifiers, and bonds are lists of atom identifiers that atoms a
and b are bonded to, respectively. Each dictionary works the same
way as other samplers, with `atoms` as a parameter.
region : Region, optional
Region of the box to sample. Supported: "Box", "Reservoir", "Pore",
"Wall", or a user-defined function that takes atom positions
(N, 3) as input and returns a boolean mask (N,).
num_bins : int, optional
Number of bins for the histogram. Default is 200.
r_max : float, optional
Maximum distance in Angstroms for which to compute the
histogram. Default is 7.0.
Be aware that the maximum distance significantly affects the
computation time.
"""
dimension = "Histogram"
inputs = {
"name_out": name_out,
"pairs": pairs,
"dimension": dimension,
"region": region,
"num_bins": num_bins,
"r_max": r_max,
}
self.sampler_inputs["rdf_samplers"].append(inputs)
[docs]
def add_reaction_sampling(
self,
name_out: str,
reactions: list[tuple],
dimension: str,
region: Region = "Box",
num_bins=200,
direction="z",
position="center",
):
"""
Add sampling for reaction events of the specified reactions.
Parameters
----------
name_out : str
Name of the output directory and object file of the sampler data
reactions : list
List of reactions to sample. Each reaction is defined as a tuple
of two dictionaries in the format: ({"atom": "a", "bonds": [...]},
{"atom": "b", "bonds": [...]}) where a and b are atom
identifiers, and bonds are lists of atom identifiers that atoms a
and b are bonded to, respectively. Each dictionary works the same
way as other samplers, with `atoms` as a parameter.
dimension : str
Sampling dimension. Supported: "Time", "Cartesian1D", "Cartesian2D",
"Pore1D", "Pore2D".
- "Time": Samples the amount of the specified reactions over time.
- "Cartesian1D": Samples the amount of the specified reactions
along a specified direction (x, y, or z) in the simulation box.
- "Cartesian2D": Samples the amount of the specified reactions in
a 2D plane (xy, xz, or yz) in the simulation box.
- "Pore1D"/"Pore2D": Same as "Cartesian1D"/"Cartesian2D", but in
pore-relative coordinates (r, phi, d). Requires `Sample(...,
system=...)` to be given a cylindrical pore YAML.
region : Region, optional
Region of the box to sample. Supported: "Box", "Reservoir", "Pore",
"Wall", or a user-defined function that takes atom positions
(N, 3) as input and returns a boolean mask (N,).
num_bins : int, optional
Number of bins for position sampling. Default is 200.
direction : str, optional
Direction along which to sample. Options depending on the dimension:
- For "Cartesian1D": use ("x", "y", or "z").
- For "Cartesian2D": use ("xy", "xz", or "yz").
- For "Pore1D": use ("r", "p", or "d") for radial distance,
azimuthal angle, or distance from the nearest pore mouth.
- For "Pore2D": use ("rp", "rz", or "pz").
position : str, optional
Position of the reaction event to sample. Supported: "center",
"reactant", "product"
- "center": Samples the position of the reaction event at the
center between the reactant and product atoms.
- "reactant": Samples the position of the reaction event at the
position of the reactant atoms.
- "product": Samples the position of the reaction event at the
position of the product atoms.
"""
inputs = {
"name_out": name_out,
"reactions": reactions,
"dimension": dimension,
"region": region,
"num_bins": num_bins,
"direction": direction,
"position": position,
}
self.sampler_inputs["reaction_samplers"].append(inputs)
def _add_sampler(self, sampler: Sampler):
"""
Add a sampler to the Sample instance.
Parameters
----------
sampler : Sampler
An instance of a Sampler subclass to be added
"""
if not isinstance(sampler, Sampler):
raise TypeError("sampler must be an instance of Sampler class.")
self.samplers.append(sampler)
def _transform_positions(
self, positions: NDArray[np.float64]
) -> NDArray[np.float64]:
if self.system_properties and self.system_properties["type"] == "cylinder":
# Coordinate transformation to cylindrical coordinates (r, phi, z)
center = self.system_properties["center"]
shifted_positions = positions[:, :2] - center[:2]
r = np.linalg.norm(shifted_positions, axis=1)
phi = np.arctan2(shifted_positions[:, 1], shifted_positions[:, 0])
z = positions[:, 2]
# For reservoir region calculate the distance from the wall
pore_range = self.system_properties["range"]
left_wall = pore_range[0]
right_wall = pore_range[1]
d = (
np.minimum(np.abs(z - left_wall), np.abs(z - right_wall))
* np.sign(z - left_wall)
* np.sign(z - right_wall)
)
return np.column_stack((r, phi, z, d))
else:
return positions
def _init_samplers(self, sampler_inputs, process_id):
"""
Initialise samplers based on provided configurations.
Parameters
----------
sampler_inputs : dict
Dictionary of sampler input configurations.
process_id : int
Process ID for parallel sampling.
"""
common_kwargs = {
"process_id": process_id,
"atom_lib": self.name_to_type,
"masses": self.masses,
"num_frames": self.num_frames,
"box": self.box,
"system_properties": self.system_properties,
}
for sampler_type, sampler_configs in sampler_inputs.items():
if sampler_type not in self._SAMPLER_REGISTRY:
raise ValueError(f"Unknown sampler type: '{sampler_type}'")
SamplerClass, kind, extra_keys = self._SAMPLER_REGISTRY[sampler_type]
for cfg in sampler_configs:
kwargs = dict(
name_out=cfg["name_out"],
dimension=cfg["dimension"],
region=cfg["region"],
**common_kwargs,
**{k: cfg[k] for k in extra_keys},
)
instance = SamplerClass(**kwargs)
# Add sampler instance to the list of samplers
if kind == "bond":
self.bonds.update(instance.get_bonds())
self.molecules.update(instance.get_mols())
self._add_sampler(instance)
[docs]
def sample(self, is_parallel: bool = True, num_cores: int = 0) -> None:
"""
Execute the sampling process.
Parameters
----------
is_parallel : bool, optional
Whether to use parallel processing.
num_cores : int, optional
Number of CPU cores to use for parallel processing.
"""
# Determine number of cores to use
avail_cores = mp.cpu_count()
cluster_tasks = (
os.getenv("SLURM_NTASKS")
or os.getenv("PBS_NP")
or os.getenv("LSB_DJOB_NUMPROC")
or os.getenv("NSLOTS")
)
cluster_tasks = int(cluster_tasks) if cluster_tasks else None
max_cores = (
min(avail_cores, cluster_tasks, self.num_frames)
if cluster_tasks
else min(avail_cores - 1, self.num_frames)
)
num_cores = num_cores if num_cores and num_cores <= max_cores else max_cores
# Run initialisation of samplers in the main process to catch any
# potential issues before spawning subprocesses
self._init_samplers(self.sampler_inputs, process_id=-1)
if is_parallel and num_cores > 1:
frames_per_core = np.array_split(self.frames, num_cores)
start_end_nthframe_list = [
(frames[0], frames[-1], 1) for frames in frames_per_core
]
for i, (start_frame, end_frame, _) in enumerate(start_end_nthframe_list):
logger.info(f"Process {i}: frames {start_frame} to {end_frame}")
logger.info(f"Starting parallel sampling with {num_cores} cores...")
if "forkserver" in mp.get_all_start_methods():
ctx = mp.get_context("forkserver")
elif "spawn" in mp.get_all_start_methods():
ctx = mp.get_context("spawn")
else:
ctx = mp.get_context("fork")
if "ovito" in sys.modules:
raise RuntimeError(
"The 'ovito' module is already imported. Please "
"remove it from the loaded modules to avoid "
"conflicts during parallel processing. This is "
"necessary because the OS does not support the "
"'spawn' start method."
)
with ctx.Pool(num_cores) as pool:
results = [
pool.apply_async(
self._init_subprocess_sampler,
(
self.name_to_type,
self.masses,
self.trajectory_file,
self.bond_file,
self.system,
start_end_nthframe_list[process_id],
self.sampler_inputs,
process_id,
self.num_particles,
np.inf,
self.box,
),
)
for process_id in range(num_cores)
]
pool.close()
# Re-raise any exception from a worker
for result in results:
result.get()
pool.join()
logger.info("Parallel sampling completed.")
else:
logger.info("Starting serial sampling...")
self._sample_helper()
logger.info("Serial sampling completed.")
for sampler in self.samplers:
sampler.join_samplers(num_cores=num_cores if is_parallel else 1)
@staticmethod
def _init_subprocess_sampler(
atom_lib,
masses,
trajectory_file,
bond_file,
system,
start_end_nthframe,
sampler_inputs,
process_id,
num_particles,
num_frames,
box,
):
"""
Initialise and run sampling in a subprocess.
This static method is designed to be called within a subprocess for
parallel sampling.
Parameters
----------
atom_lib : dict
Library mapping atom names to types.
masses : dict
Dictionary mapping atom names to their masses.
trajectory_file : str
Path to the trajectory file.
bond_file : str, optional
Path to the bond file.
system : str, optional
Path to a pore YAML file describing the system geometry. Required
for the 'Pore1D' and 'Pore2D' density dimensions.
start_end_nthframe : tuple
Tuple specifying (start_frame, end_frame, nth_frame) for sampling.
sampler_inputs : dict
Dictionary of sampler input configurations.
process_id : int
Process ID for parallel sampling.
num_particles : int
Number of particles in the trajectory.
box : np.ndarray
Simulation box dimensions.
Returns
-------
str
Completion message for the subprocess.
"""
sample_instance = Sample.__new__(Sample)
start_frame, end_frame, nth_frame = start_end_nthframe
sample_instance._init_helper(
atom_lib,
masses,
trajectory_file,
bond_file,
system,
start_frame,
end_frame,
nth_frame,
num_particles,
num_frames,
box,
)
sample_instance._init_samplers(sampler_inputs, process_id)
sample_instance._sample_helper()
return f"Process {process_id} finished sampling."
def _group_molecules_by_atom_type(self):
"""
Group registered molecule identifiers by their central atom type.
Within each atom type, molecules are sorted so that an unconstrained
registration (no "bonds" constraint) comes first, followed by the
others in increasing order of how many bonded neighbours they require.
This ordering lets `_identify_molecules` short-circuit cheaply for
atom types that don't distinguish molecules by bonding environment.
Returns
-------
molecules_per_atom_type : dict
Mapping atom_type -> list of (identifier, bond_permutations,
bonds_spec) triples, where bond_permutations is None for an
unconstrained molecule or a list of neighbour-type permutations
otherwise, and bonds_spec is None unless the molecule also
requires a bonding environment on one or more of its neighbours
(see `_build_mol_dictionary`). Atom types with no registered
molecule are omitted.
Example (single atom type): [('O', None, None), ('O()', [[]], None),
('O(H+H)', [[1, 1]], None), ('O(H+Si)', [[1, 2], [2, 1]], None)]
"""
molecules_per_atom_type = {}
for atom_type in self.type_to_name:
candidates = [
(identifier, info["bonds"], info["bonds_spec"])
for identifier, info in self.molecules.items()
if info["atom"] == atom_type
]
if not candidates:
continue
candidates.sort(key=lambda c: len(c[1][0]) if c[1] is not None else -1)
molecules_per_atom_type[atom_type] = candidates
return molecules_per_atom_type
def _init_molecule_arrays(self):
"""
Allocate the per-molecule arrays that are reused (and reset every frame)
while identifying molecules.
Returns
-------
molecule_mask : dict
Mask indicating, for each molecule identifier, which atoms belong to it.
Shape: (num_particles, ), dtype: bool.
molecule_bond_atoms : dict
For each molecule identifier, the indices of the atoms it is bonded to.
Shape: (num_particles, num_bonds_per_molecule), dtype: int.
"""
molecule_mask = {}
molecule_bond_atoms = {}
for identifier, info in self.molecules.items():
molecule_mask[identifier] = np.zeros(self.num_particles, dtype=bool)
num_bonds = len(info["bonds"][0]) if info["bonds"] is not None else 0
molecule_bond_atoms[identifier] = np.zeros(
(self.num_particles, num_bonds), dtype=int
)
return molecule_mask, molecule_bond_atoms
def _identify_molecules(
self,
molecule_mask,
molecule_bond_atoms,
atom_types,
bond_topology,
bond_enum,
):
"""
Update molecule_mask and molecule_bond_atoms in place for the current frame.
Parameters
----------
molecule_mask : dict
Per-molecule atom mask to update, as allocated by `_init_molecule_arrays`.
molecule_bond_atoms : dict
Per-molecule bonded-atom indices to update, as allocated by
`_init_molecule_arrays`.
atom_types : np.ndarray
Particle type of each atom in the current frame.
bond_topology : np.ndarray
(num_bonds, 2) array of atom index pairs for the current frame.
bond_enum : ovito.data.BondsEnumerator
Enumerator used to look up the bonds of a given atom.
"""
for identifier in molecule_mask:
molecule_mask[identifier][:] = False
molecule_bond_atoms[identifier][:] = 0
for atom_type, candidates in self._molecules_per_atom_type.items():
atoms = np.where(atom_types == atom_type)[0]
# Sorting guarantees an unconstrained molecule, if registered, comes first.
unconstrained_identifier, bond_permutations, _ = candidates[0]
if bond_permutations is None:
molecule_mask[unconstrained_identifier][atoms] = True
if len(candidates) == 1:
continue
# Remaining candidates require a specific set of bonded neighbour types.
for atom in atoms:
other_atoms = _neighbor_atoms_excluding(
atom, None, bond_topology, bond_enum
)
other_types = list(atom_types[other_atoms])
for identifier, bond_permutations, bonds_spec in candidates:
if (
bond_permutations is None
or other_types not in bond_permutations
):
continue
if bonds_spec is not None and not _matches_bond_spec(
other_atoms,
atom_types,
bonds_spec,
bond_topology,
bond_enum,
atom,
):
continue
molecule_mask[identifier][atom] = True
molecule_bond_atoms[identifier][atom] = other_atoms
def _identify_bonds(
self, bond_mask, bond_count, bond_topology, atom_types, molecule_mask
):
"""
Rebuild bond_mask in place for the current frame.
A bond matches a registered bond identifier if its endpoint types match
(in either order) and its endpoint atoms belong to the corresponding
registered molecules.
Parameters
----------
bond_mask : dict
Mask indicating, for each bond identifier, which bonds in the current
frame belong to it. Populated in place. Shape: (num_bonds, ), dtype: bool.
bond_count : int
Number of bonds in the current frame.
bond_topology : np.ndarray
(num_bonds, 2) array of atom index pairs for the current frame.
atom_types : np.ndarray
Particle type of each atom in the current frame.
molecule_mask : dict
Per-molecule atom mask, as produced by `_identify_molecules`.
"""
for identifier in self.bonds:
bond_mask[identifier] = np.zeros(bond_count, dtype=bool)
for bond_id, (atom_a, atom_b) in enumerate(bond_topology):
type_a = atom_types[atom_a]
type_b = atom_types[atom_b]
for identifier, bond_info in self.bonds.items():
type_A, type_B = bond_info["bond"]
mol_A, mol_B = bond_info["mol_A"], bond_info["mol_B"]
# Check if the bond matches the registered bond type (in either order)
if type_a == type_A and type_b == type_B:
atom_in_A, atom_in_B = atom_a, atom_b
elif type_a == type_B and type_b == type_A:
atom_in_A, atom_in_B = atom_b, atom_a
else:
continue
# Check if the atoms belong to the corresponding registered molecules
if molecule_mask[mol_A][atom_in_A] and molecule_mask[mol_B][atom_in_B]:
bond_mask[identifier][bond_id] = True
def _sample_helper(self):
"""
Helper function to perform the sampling process.
"""
os.environ["OVITO_THREAD_COUNT"] = "1"
from ovito.data import BondsEnumerator
from ovito.io import import_file
from ovito.modifiers import LoadTrajectoryModifier
# Load trajectory
self.pipeline = import_file(self.trajectory_file)
if self.bond_file:
bond_modifier = LoadTrajectoryModifier()
bond_modifier.source.load(self.bond_file)
self.pipeline.modifiers.append(bond_modifier)
# Initialize molecule and bond data structures
self._molecules_per_atom_type = self._group_molecules_by_atom_type()
molecule_mask, molecule_bond_atoms = self._init_molecule_arrays()
bond_mask = {}
# Loop over frames
for frame_idx in self.frames:
logger.debug(f"Processing frame {frame_idx}...")
frame = self.pipeline.compute(frame_idx)
atom_types = frame.particles.particle_types.array
bond_count = frame.particles.bonds.count
bond_topology = frame.particles.bonds.topology.array
bond_enum = BondsEnumerator(frame.particles.bonds)
# Identify molecules and bonds in the current frame
# Build molecule_mask and molecule_bond_atoms in place
self._identify_molecules(
molecule_mask,
molecule_bond_atoms,
atom_types,
bond_topology,
bond_enum,
)
# Build bond_mask in place
self._identify_bonds(
bond_mask, bond_count, bond_topology, atom_types, molecule_mask
)
positions_transformed = self._transform_positions(
frame.particles.positions.array
)
# Sampling
for sampler in self.samplers:
sampler.sample(
frame_id=frame_idx - self.start_frame,
molecule_mask=molecule_mask,
molecule_bond_atoms=molecule_bond_atoms,
bond_mask=bond_mask,
frame=frame,
bond_enum=bond_enum,
positions_transformed=positions_transformed,
)
for sampler in self.samplers:
sampler.save_object()