Core¶
Foundational data structures for molecular systems. All available via import molpy as mp.
Quick reference¶
| Symbol | Summary | Preferred for | Avoid when |
|---|---|---|---|
Atomistic |
Editable molecular graph (atoms + bonds) | Building, editing, reacting on chemistry | Array-backed analysis or export |
Block |
Columnar table: column names → NumPy arrays | Tabular data, vectorized computation | Graph-level chemical editing |
Frame |
Named collection of Blocks + metadata | System snapshots, file I/O | Editing individual atoms |
Box |
Periodic simulation cell (3×3 matrix + PBC) | Wrapping, minimum-image distances | Non-periodic systems |
Trajectory |
Ordered sequence of Frames (eager or lazy) | Time-series analysis, streaming I/O | Single-snapshot work |
Topology |
igraph-based bond graph → derived angles/dihedrals | Graph algorithms, connectivity queries | Storing atom properties |
CoarseGrain |
CG molecular graph (beads + CG bonds) | Coarse-grained modelling, CG/AA conversion | All-atom work (use Atomistic) |
Config |
Thread-safe global configuration singleton | Logging level, thread count settings | Per-run overrides (use Config.temporary) |
AtomisticForcefield |
Force field container (styles → types → potentials) | Defining parameters before execution | Direct numerical computation |
Canonical examples¶
import molpy as mp
# Atomistic: editable molecular graph
mol = mp.Atomistic(name="water")
o = mol.def_atom(element="O", x=0.0, y=0.0, z=0.0)
h = mol.def_atom(element="H", x=0.957, y=0.0, z=0.0)
mol.def_bond(o, h)
# Block + Frame: tabular snapshot
frame = mp.Frame(blocks={
"atoms": {"element": ["O", "H"], "x": [0.0, 0.957]},
}, timestep=0)
# Box: periodic cell
box = mp.Box.cubic(20.0)
wrapped = box.wrap(coords)
d = box.dist(r1, r2) # minimum-image distance
# ForceField: parameter data
ff = mp.AtomisticForcefield(name="demo", units="real")
style = ff.def_atomstyle("full")
ct = style.def_type("CT", mass=12.011)
Related¶
Full API¶
Atomistic¶
atomistic ¶
Angle ¶
Bases: Link
Valence angle formed by three atoms (i--j--k).
The central atom jtom is the vertex of the angle. Angle values are
measured in radians by convention throughout MolPy.
Create an angle between three atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom (one arm of the angle). |
required |
b
|
Atom
|
Central/vertex atom. |
required |
c
|
Atom
|
Third atom (other arm of the angle). |
required |
**attrs
|
Any
|
Arbitrary angle attributes (e.g., |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any argument is not an Atom instance. |
Atom ¶
Bases: Entity
Atom entity (common keys include {"element": "C", "xyz": [...]})
Atomistic ¶
Bases: Struct, MembershipMixin, SpatialMixin, ConnectivityMixin
All-atom molecular structure with full topological information.
Atomistic is the primary container for molecular systems in MolPy. It manages collections of atoms, bonds, angles, and dihedrals through typed buckets, and provides factory methods for creating and adding topology elements.
Supports spatial operations (move, rotate, scale, align), system
composition via + / +=, and conversion to tabular Frame format
for I/O.
Initialize an empty atomistic structure.
Registers buckets for Atom, Bond, Angle, and Dihedral types.
If the concrete subclass defines a __post_init__ method, it is
called automatically with the same keyword arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**props
|
Any
|
Arbitrary properties stored on the structure (e.g.,
|
{}
|
angles
property
¶
All angles in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Angle]
|
Entities[Angle]: Column-accessible list of Angle objects. |
atoms
property
¶
All atoms in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Atom]
|
Entities[Atom]: Column-accessible list of Atom objects. |
bonds
property
¶
All bonds in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Bond]
|
Entities[Bond]: Column-accessible list of Bond objects. |
dihedrals
property
¶
All dihedrals in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Dihedral]
|
Entities[Dihedral]: Column-accessible list of Dihedral objects. |
impropers
property
¶
All impropers in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Improper]
|
Entities[Improper]: Column-accessible list of Improper objects. |
symbols
property
¶
Element symbols for every atom in insertion order.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of element strings (e.g., |
xyz
property
¶
Get atomic positions as numpy array.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Nx3 array of atomic coordinates, or list of lists if numpy not available. |
add_angle ¶
add_angles ¶
add_atom ¶
Add an existing Atom object to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom
|
Atom
|
Atom instance to register. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Atom |
Atom
|
The same atom passed in (for chaining convenience). |
Preferred for
Re-using an Atom created elsewhere. Use def_atom to create
and add in one step.
add_atoms ¶
add_bond ¶
add_bonds ¶
add_dihedral ¶
add_dihedrals ¶
add_improper ¶
align ¶
Align this structure so that atom a coincides with atom b.
When direction vectors a_dir and b_dir are given, the
structure is first rotated to align the two directions, then
translated so that a lands on b.
This is an in-place operation that returns self for method
chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Entity
|
Source reference atom (in this structure). |
required |
b
|
Entity
|
Target reference atom (position to align to) with coordinates in angstroms. |
required |
a_dir
|
list[float] | None
|
Direction vector at |
None
|
b_dir
|
list[float] | None
|
Direction vector at |
None
|
flip
|
bool
|
If True, reverse |
False
|
entity_type
|
type[Entity]
|
Entity type to transform (default: Atom). |
Atom
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
|
def_angle ¶
Create a new Angle between three atoms and add it to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom (one arm of the angle). |
required |
b
|
Atom
|
Central/vertex atom. |
required |
c
|
Atom
|
Third atom (other arm of the angle). |
required |
**attrs
|
Any
|
Angle attributes (e.g., |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Angle |
Angle
|
The newly created and registered angle. |
def_angles ¶
Create multiple Angles from a list of atom-triple tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
angles_data
|
list[tuple[Atom, Atom, Atom] | tuple[Atom, Atom, Atom, dict[str, Any]]]
|
Each element is |
required |
Returns:
| Type | Description |
|---|---|
list[Angle]
|
list[Angle]: Newly created angles in the same order as input. |
def_atom ¶
Create a new Atom and add it to the structure.
If an xyz key is provided, it is expanded into separate x,
y, z float fields on the created atom.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**attrs
|
Any
|
Atom attributes. Common keys include |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Atom |
Atom
|
The newly created and registered atom. |
Preferred for
Building structures atom-by-atom. Use add_atom instead when
the Atom object already exists.
def_atoms ¶
Create multiple Atoms from a list of attribute dictionaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms_data
|
list[dict[str, Any]]
|
Each dict is passed as |
required |
Returns:
| Type | Description |
|---|---|
list[Atom]
|
list[Atom]: Newly created atoms in the same order as input. |
def_bond ¶
Create a new Bond between two atoms and add it to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom endpoint. |
required |
b
|
Atom
|
Second atom endpoint. |
required |
**attrs
|
Any
|
Bond attributes (e.g., |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Bond |
Bond
|
The newly created and registered bond. |
def_bonds ¶
Create multiple Bonds from a list of atom-pair tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bonds_data
|
list[tuple[Atom, Atom] | tuple[Atom, Atom, dict[str, Any]]]
|
Each element is |
required |
Returns:
| Type | Description |
|---|---|
list[Bond]
|
list[Bond]: Newly created bonds in the same order as input. |
def_dihedral ¶
Create a new Dihedral between four atoms and add it to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom. |
required |
b
|
Atom
|
Second atom (part of the central bond). |
required |
c
|
Atom
|
Third atom (part of the central bond). |
required |
d
|
Atom
|
Fourth atom. |
required |
**attrs
|
Any
|
Dihedral attributes (e.g., |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Dihedral |
Dihedral
|
The newly created and registered dihedral. |
def_dihedrals ¶
Create multiple Dihedrals from a list of atom-quadruple tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dihedrals_data
|
list[tuple[Atom, Atom, Atom, Atom] | tuple[Atom, Atom, Atom, Atom, dict[str, Any]]]
|
Each element is |
required |
Returns:
| Type | Description |
|---|---|
list[Dihedral]
|
list[Dihedral]: Newly created dihedrals in the same order as input. |
def_improper ¶
Create a new Improper torsion and add it to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
Central atom. |
required |
b
|
Atom
|
First substituent atom. |
required |
c
|
Atom
|
Second substituent atom. |
required |
d
|
Atom
|
Third substituent atom. |
required |
**attrs
|
Any
|
Improper attributes (e.g., |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Improper |
Improper
|
The newly created and registered improper. |
del_angle ¶
Remove angles from the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*angles
|
Angle
|
Angle instances to remove. |
()
|
del_atom ¶
Remove atoms and all their incident bonds, angles, and dihedrals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*atoms
|
Atom
|
Atom instances to remove. |
()
|
del_bond ¶
Remove bonds (and any dependent angles / dihedrals that reference them).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*bonds
|
Bond
|
Bond instances to remove. |
()
|
del_dihedral ¶
Remove dihedrals from the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*dihedrals
|
Dihedral
|
Dihedral instances to remove. |
()
|
del_improper ¶
Remove impropers from the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*impropers
|
Improper
|
Improper instances to remove. |
()
|
extract_subgraph ¶
Extract subgraph preserving all topology (bonds, angles, dihedrals).
Overrides ConnectivityMixin.extract_subgraph to ensure all topology types (bonds, angles, dihedrals) are preserved in the extracted subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
center_entities
|
Iterable[Atom]
|
Center atoms for extraction |
required |
radius
|
int
|
Topological radius |
required |
entity_type
|
type[Atom]
|
Entity type (should be Atom) |
Atom
|
link_type
|
type[Link]
|
Link type for topology calculation (should be Bond) |
Bond
|
Returns:
| Type | Description |
|---|---|
tuple['Atomistic', list[Atom]]
|
Tuple of (subgraph Atomistic, edge atoms) |
get_topo ¶
Generate topology (angles and dihedrals) from bonds.
When gen_angle or gen_dihe is True, returns a new Atomistic
with the generated interactions added — the original is not mutated.
When both are False, falls through to the base-class method and returns
a :class:Topology graph (used internally for traversal).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_type
|
type[Entity]
|
Entity type to include in topology (default: Atom) |
Atom
|
link_type
|
type[Link]
|
Link type to use for connections (default: Bond) |
Bond
|
gen_angle
|
bool
|
Whether to generate angles |
False
|
gen_dihe
|
bool
|
Whether to generate dihedrals |
False
|
clear_existing
|
bool
|
If True, clear existing angles/dihedrals before generating new ones. |
False
|
Returns:
| Type | Description |
|---|---|
'Atomistic | Topology'
|
New Atomistic with angles/dihedrals added when gen_angle or |
'Atomistic | Topology'
|
gen_dihe is True; Topology graph otherwise. |
move ¶
Translate all atoms by a displacement vector.
This is an in-place operation that returns self for method
chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta
|
list[float]
|
Translation vector |
required |
entity_type
|
type[Entity]
|
Entity type to translate (default: Atom). |
Atom
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
|
rename_type ¶
Rename all entities/links of kind whose type attribute equals old.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old
|
str
|
Existing type name. |
required |
new
|
str
|
Replacement type name. |
required |
kind
|
type
|
Entity or Link class to target (default: |
Atom
|
Returns:
| Type | Description |
|---|---|
int
|
Number of entities/links whose type was renamed. |
replicate ¶
Create n copies and merge them into a new system.
Each copy is independently deep-copied from self, optionally
transformed, then merged into a single new Atomistic structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of copies to create. |
required |
transform
|
Callable | None
|
Optional callable |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
A new structure containing all replicas merged together. |
Example
waters = Water().replicate(10, lambda mol, i: mol.move([i5, 0, 0])) grid = Methane().replicate(9, lambda mol, i: mol.move([i%35, i//3*5, 0]))
rotate ¶
Rotate all atoms around an axis using the Rodrigues formula.
This is an in-place operation that returns self for method
chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
list[float]
|
Rotation axis |
required |
angle
|
float
|
Rotation angle in radians. |
required |
about
|
list[float] | None
|
Point |
None
|
entity_type
|
type[Entity]
|
Entity type to rotate (default: Atom). |
Atom
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
|
scale ¶
Scale all atom positions by a uniform factor.
This is an in-place operation that returns self for method
chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor
|
float
|
Multiplicative scale factor (dimensionless). |
required |
about
|
list[float] | None
|
Center of scaling |
None
|
entity_type
|
type[Entity]
|
Entity type to scale (default: Atom). |
Atom
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
|
select ¶
Return a new Atomistic containing atoms matching predicate.
All bonds/angles/dihedrals whose endpoints are fully contained in the selection are carried over (deep-copied).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicate
|
Callable |
required |
Returns:
| Type | Description |
|---|---|
'Atomistic'
|
New Atomistic with the selected atoms and their induced topology. |
set_property ¶
Set a property on every atom (or link) matching selector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selector
|
Callable |
required | |
key
|
str
|
Property key to assign. |
required |
value
|
Any
|
Value to store. |
required |
kind
|
type
|
Entity or Link class to iterate (default: |
Atom
|
Returns:
| Type | Description |
|---|---|
int
|
Number of items updated. |
to_frame ¶
Convert to LAMMPS data Frame format.
Converts this Atomistic structure into a Frame suitable for writing as a LAMMPS data file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom_fields
|
list[str] | None
|
List of atom fields to extract. If None, extracts all fields. |
None
|
Returns:
| Type | Description |
|---|---|
'Frame'
|
Frame with atoms, bonds, angles, and dihedrals |
Example
butane = CH3() + CH2() + CH3()
Extract all fields¶
frame = butane.to_frame()
Extract specific fields only¶
frame = butane.to_frame( ... atom_fields=['xyz', 'charge', 'element', 'type'], ... bond_fields=['itom', 'jtom', 'type'], ... ) writer = LammpsDataWriter("system.data") writer.write(frame)
Bond ¶
Bases: Link
Covalent bond connecting two atoms.
A Bond holds ordered references to exactly two Atom endpoints and optional key-value attributes (e.g., bond order, force-field type).
Create a bond between two atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom endpoint. |
required |
b
|
Atom
|
Second atom endpoint. |
required |
**attrs
|
Any
|
Arbitrary bond attributes (e.g., |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If either argument is not an Atom instance. |
Dihedral ¶
Bases: Link
Dihedral (torsion) angle between four atoms
Create a dihedral angle between four atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom. |
required |
b
|
Atom
|
Second atom (part of the central bond). |
required |
c
|
Atom
|
Third atom (part of the central bond). |
required |
d
|
Atom
|
Fourth atom. |
required |
**attrs
|
Any
|
Arbitrary dihedral attributes (e.g., |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any argument is not an Atom instance. |
Improper ¶
Bases: Link
Improper torsion between four atoms (i is the central atom).
Impropers constrain out-of-plane geometry around a central atom i
bonded to three substituents j/k/l. They are topologically
distinct from proper :class:Dihedral terms — force fields assign
separate coefficients and LAMMPS/OpenMM/GROMACS all treat the two as
separate lists.
Create an improper torsion between four atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
Central atom. |
required |
b
|
Atom
|
First substituent atom. |
required |
c
|
Atom
|
Second substituent atom. |
required |
d
|
Atom
|
Third substituent atom. |
required |
**attrs
|
Any
|
Arbitrary improper attributes (e.g., |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any argument is not an Atom instance. |
Box¶
box ¶
Box ¶
Bases: PeriodicBoundary
Simulation box representing a periodic domain in 3D space.
The box is defined by a 3x3 upper-triangular matrix whose columns are the lattice vectors, an origin point, and per-axis periodic boundary flags. Three styles are supported:
- FREE -- no boundaries (zero matrix).
- ORTHOGONAL -- axis-aligned cuboid (diagonal matrix).
- TRICLINIC -- general parallelepiped (upper-triangular matrix with at least one nonzero off-diagonal element).
All length quantities are in Angstroms. Angles are in degrees unless stated otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ArrayLike | None
|
A 3x3 upper-triangular box matrix with lattice vectors
as columns, shape |
None
|
pbc
|
ArrayLike
|
Boolean periodic-boundary flags per axis, shape |
ones(3, dtype=bool)
|
origin
|
ArrayLike
|
Cartesian origin of the box in Angstroms, shape |
zeros(3)
|
Initialize a Box object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | None
|
A 3x3 matrix representing the box dimensions. If None or all elements are zero, a zero matrix is used. If a 1D array of shape (3,) is provided, it is converted to a diagonal matrix. Defaults to None. |
None
|
pbc
|
ndarray
|
A 1D boolean array of shape (3,) indicating periodic boundary conditions along each axis. Defaults to an array of ones (True for all axes). |
ones(3, dtype=bool)
|
origin
|
ndarray
|
A 1D array of shape (3,) representing the origin of the box. Defaults to an array of zeros. |
zeros(3)
|
a
property
¶
First lattice vector of the box in Angstroms.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Column 0 of the box matrix, shape |
angles
property
¶
Lattice angles [alpha, beta, gamma] in degrees.
Alpha is the angle between lattice vectors b and c, beta between a and c, and gamma between a and b.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Angles in degrees, shape |
b
property
¶
Second lattice vector of the box in Angstroms.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Column 1 of the box matrix, shape |
bounds
property
¶
Get the bounds of the box.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A 2D array with shape (3, 2) representing the bounds of the box. |
c
property
¶
Third lattice vector of the box in Angstroms.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Column 2 of the box matrix, shape |
is_periodic
property
¶
Check if the box has periodic boundary conditions in all directions.
l
property
¶
Get the lengths of the box along each axis.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A 1D array containing the lengths of the box along |
ndarray
|
the x, y, and z axes. |
l_inv
property
¶
Reciprocal of the box edge lengths in inverse Angstroms.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: |
lengths
property
writable
¶
Lattice vector magnitudes [a, b, c] in Angstroms.
For a FREE box all lengths are zero. For orthogonal and triclinic boxes the lengths are computed from the box matrix.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Edge lengths, shape |
lx
property
writable
¶
Get the length of the box along the x-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The length of the box in the x-direction, derived from the |
float
|
first element of the matrix representing the box dimensions. |
ly
property
writable
¶
Get the length of the simulation box along the y-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The length of the box in the y-direction. |
lz
property
writable
¶
Get the length of the simulation box along the z-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The length of the box in the z-direction. |
matrix
property
¶
Get the matrix representation of the box.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A 3x3 matrix representing the box dimensions. |
origin
property
writable
¶
Cartesian origin of the box in Angstroms.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Origin coordinates, shape |
pbc
property
¶
Get the periodic boundary conditions of the box.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A boolean array indicating periodicity along each axis. |
periodic
property
writable
¶
Whether the box is periodic in all three directions.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if periodic boundary conditions are active along |
bool
|
every axis. |
periodic_x
property
writable
¶
Whether the box is periodic along the x-axis.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if periodic in x. |
periodic_y
property
writable
¶
Whether the box is periodic along the y-axis.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if periodic in y. |
periodic_z
property
writable
¶
Whether the box is periodic along the z-axis.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if periodic in z. |
style
property
¶
Determine the style of the box based on its matrix.
Returns:
| Name | Type | Description |
|---|---|---|
Style |
Style
|
The style of the box (FREE, ORTHOGONAL, or TRICLINIC). |
tilts
property
¶
Off-diagonal tilt factors of the box matrix in Angstroms.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: |
volume
property
¶
Calculate the volume of the box.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The volume of the box. |
xhi
property
¶
Calculate the upper boundary of the box along the x-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The x-coordinate of the upper boundary of the box, |
float
|
calculated as the difference between the first element of |
|
float
|
the matrix's first row and the x-coordinate of the origin. |
xlo
property
¶
Calculate the lower bound of the box along the x-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The x-coordinate of the lower bound, calculated as the |
float
|
negative of the x-component of the origin. |
xy
property
writable
¶
Retrieve the xy component of the matrix.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The value at the (0, 1) position in the matrix. |
xz
property
writable
¶
Tilt factor between the x and z axes in Angstroms.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The |
yhi
property
¶
Calculate the upper boundary of the box along the y-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The upper boundary value of the box in the y-dimension, |
float
|
calculated as the difference between the y-component of the |
|
float
|
matrix and the y-component of the origin. |
ylo
property
¶
Get the lower boundary of the box along the y-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The negative value of the y-coordinate of the origin. |
yz
property
writable
¶
Tilt factor between the y and z axes in Angstroms.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The |
zhi
property
¶
Calculate the z-component of the box's upper boundary.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The z-coordinate of the upper boundary, calculated as the |
float
|
difference between the z-component of the matrix and the z-component |
|
float
|
of the origin. |
zlo
property
¶
Calculate the lower boundary of the box along the z-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The z-coordinate of the lower boundary, calculated as the |
float
|
negative value of the third component of the origin vector. |
Style ¶
Bases: Enum
Enumeration of simulation-box geometries.
Attributes:
| Name | Type | Description |
|---|---|---|
FREE |
No bounding box (vacuum / non-periodic). |
|
ORTHOGONAL |
Axis-aligned cuboid with three independent edge lengths. |
|
TRICLINIC |
General parallelepiped described by three edge lengths and three tilt factors (xy, xz, yz). |
calc_lengths_angles_from_matrix
staticmethod
¶
Calculate the lengths of the box edges and angles from its matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
A 3x3 matrix representing the box. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
tuple[np.ndarray, np.ndarray]: lengths and angles |
calc_matrix_from_lengths_angles
staticmethod
¶
Compute restricted triclinic box matrix from lengths and angles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
abc
|
ndarray
|
[a, b, c] lattice vector lengths |
required |
angles
|
ndarray
|
[alpha, beta, gamma] in degrees (angles between (b,c), (a,c), (a,b)) |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: 3x3 box matrix with lattice vectors as columns: [a | b | c] |
calc_matrix_from_size_tilts
staticmethod
¶
Get restricted triclinic box matrix from sizes and tilts
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sizes
|
ndarray
|
sizes of box edges |
required |
tilts
|
ndarray
|
tilts between box edges |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: restricted triclinic box matrix |
calc_style_from_matrix
staticmethod
¶
Determine the style of the box based on its matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
A 3x3 matrix representing the box. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Style |
Style
|
The style of the box (FREE, ORTHOGONAL, or TRICLINIC). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the matrix does not correspond to a valid style. |
check_matrix
staticmethod
¶
Validate the box matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
A 3x3 matrix to validate. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The validated matrix. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the matrix is not valid. |
cubic
classmethod
¶
Create a cubic box with equal edge lengths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
float
|
Edge length of the cube in Angstroms. |
required |
pbc
|
ArrayLike
|
Periodic boundary flags per axis, shape |
ones(3, dtype=bool)
|
origin
|
ArrayLike
|
Cartesian origin of the box in Angstroms, shape |
zeros(3)
|
central
|
bool
|
If True, shift the origin so the box is centred at the coordinate origin. |
False
|
Returns:
| Type | Description |
|---|---|
Box
|
A new cubic |
diff ¶
Calculate the difference between two points considering periodic boundary conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r1
|
ndarray
|
The first point. |
required |
r2
|
ndarray
|
The second point. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The difference vector. |
diff_all ¶
Calculate the difference between all pairs of points in two sets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r1
|
ndarray
|
The first set of points. |
required |
r2
|
ndarray
|
The second set of points. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The difference vectors for all pairs. |
diff_dr ¶
Calculate the difference vector considering periodic boundary conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dr
|
ndarray
|
The difference vector. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The adjusted difference vector. |
dist ¶
Calculate the distance between two points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r1
|
ndarray
|
The first point. |
required |
r2
|
ndarray
|
The second point. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The distance between the points. |
dist_all ¶
Calculate the distances between all pairs of points in two sets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r1
|
ndarray
|
The first set of points. |
required |
r2
|
ndarray
|
The second set of points. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The distances for all pairs. |
from_bounds
classmethod
¶
Create an orthogonal box that encloses a set of points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
ArrayLike
|
Point coordinates to enclose, shape |
required |
padding
|
float | ArrayLike
|
Extra space added to each side of the bounding box,
in Angstroms. Either a scalar or a per-axis array of
shape |
0.0
|
pbc
|
ArrayLike
|
Periodic boundary flags per axis, shape |
zeros(3, dtype=bool)
|
Returns:
| Type | Description |
|---|---|
Box
|
A new orthogonal |
Box
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
from_box
classmethod
¶
from_lengths_angles
classmethod
¶
Get box matrix from lengths and angles
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lengths
|
ndarray
|
lengths of box edges |
required |
angles
|
ndarray
|
angles between box edges in degree |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Box |
Box
|
Box instance constructed from lengths and angles. |
general2restrict
staticmethod
¶
Convert general triclinc box matrix to restricted triclinic box matrix
Ref
https://docs.lammps.org/Howto_triclinic.html#transformation-from-general-to-restricted-triclinic-boxes
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
(3, 3) general triclinc box matrix |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: (3, 3) restricted triclinc box matrix |
get_distance_between_faces ¶
Perpendicular distances between opposite faces in Angstroms.
For an orthogonal box these equal the edge lengths. For a triclinic box the distances are computed by projecting each lattice vector onto the normal of the plane spanned by the other two vectors.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Distances |
get_images ¶
Get the image flags of particles, accounting for box origin and triclinic shape.
get_inv ¶
Get the inverse of the box matrix.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The inverse of the box matrix. |
isin ¶
Check if point(s) xyz are inside the box. Args: xyz (np.ndarray): shape (..., 3) Returns: np.ndarray: boolean array, True if inside
make_absolute ¶
Convert fractional coordinates to absolute coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The fractional coordinates. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The absolute coordinates. |
make_fractional ¶
Convert absolute coordinates to fractional coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The absolute coordinates. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The fractional coordinates. |
merge ¶
orth
classmethod
¶
Create an orthogonal (axis-aligned cuboid) box.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lengths
|
ArrayLike
|
Edge lengths |
required |
pbc
|
ArrayLike
|
Periodic boundary flags per axis, shape |
ones(3, dtype=bool)
|
origin
|
ArrayLike
|
Cartesian origin of the box in Angstroms, shape |
zeros(3)
|
central
|
bool
|
If True, shift the origin so the box is centred at the coordinate origin. |
False
|
Returns:
| Type | Description |
|---|---|
Box
|
A new orthogonal |
plot ¶
Plot the box representation. This method is a placeholder and should be implemented to visualize the box in 3D space.
set_angles ¶
Set the lattice angles, preserving current edge lengths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
angles
|
ndarray
|
New angles |
required |
set_lengths ¶
Set the lattice vector magnitudes, preserving current angles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lengths
|
ndarray
|
New edge lengths |
required |
set_lengths_angles ¶
Set both edge lengths and lattice angles simultaneously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lengths
|
ndarray
|
Edge lengths |
required |
angles
|
ndarray
|
Angles |
required |
set_lengths_tilts ¶
Set edge lengths and tilt factors simultaneously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lengths
|
ndarray
|
Diagonal edge lengths |
required |
tilts
|
ndarray
|
Off-diagonal tilt factors |
required |
set_matrix ¶
Replace the box matrix directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
New 3x3 upper-triangular box matrix, shape |
required |
to_dict ¶
Convert the box to a dictionary representation.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A dictionary containing the box properties. |
to_lengths_angles ¶
Get lengths and angles from box matrix
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
tuple[np.ndarray, np.ndarray]: lengths and angles |
transform ¶
Transform the box using a transformation matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transformation_matrix
|
ndarray
|
3x3 transformation matrix. |
required |
Returns:
| Type | Description |
|---|---|
Box
|
New Box with transformed dimensions. |
tric
classmethod
¶
Create a triclinic box from edge lengths and tilt factors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lengths
|
ArrayLike
|
Diagonal edge lengths |
required |
tilts
|
ArrayLike
|
Off-diagonal tilt factors |
required |
pbc
|
ArrayLike
|
Periodic boundary flags per axis, shape |
ones(3, dtype=bool)
|
origin
|
ArrayLike
|
Cartesian origin of the box in Angstroms, shape |
zeros(3)
|
central
|
bool
|
If True, shift the origin so the box is centred at the coordinate origin. |
False
|
Returns:
| Type | Description |
|---|---|
Box
|
A new triclinic |
unwrap ¶
Unwrap the coordinates of a particle based on its image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The coordinates of the particle. |
required |
image
|
ndarray
|
The image of the particle. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The unwrapped coordinates. |
wrap ¶
Wrap Cartesian coordinates into the primary image of the box.
Delegates to style-specific implementations (free, orthogonal, or triclinic).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
Cartesian positions in Angstroms, shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Wrapped coordinates with the same shape as the input, in Angstroms. |
wrap_free ¶
Wrap coordinates for a free box style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The coordinates to wrap. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The wrapped coordinates. |
wrap_orthogonal ¶
Wrap coordinates for an orthogonal box style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The coordinates to wrap. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The wrapped coordinates. |
wrap_triclinic ¶
Wrap coordinates for a triclinic box style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The coordinates to wrap. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The wrapped coordinates. |
Forcefield¶
forcefield ¶
AngleStyle ¶
Bases: Style
Style for angle interactions (e.g. "harmonic").
def_type ¶
to_potential ¶
Create corresponding Potential instance from AngleStyle.
Returns:
| Name | Type | Description |
|---|---|---|
Potential |
Potential
|
Potential instance that accepts string type labels (from Frame). The potential internally uses TypeIndexedArray to map type names to parameters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If corresponding Potential class not found or missing required parameters |
AngleType ¶
Bases: Type
Angle type defined by three atom types
Initialise an angle type defined by three atom types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this angle type. |
required |
itom
|
AtomType
|
First endpoint atom type. |
required |
jtom
|
AtomType
|
Central (vertex) atom type. |
required |
ktom
|
AtomType
|
Third endpoint atom type. |
required |
**kwargs
|
Any
|
Angle parameters (e.g. |
{}
|
matches ¶
Check whether this angle type matches an atom type triple.
Matching considers both forward (at1, at2, at3) and reverse
(at3, at2, at1) orderings; the central atom must always
match jtom.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First endpoint atom type. |
required |
at2
|
AtomType
|
Central atom type. |
required |
at3
|
AtomType
|
Third endpoint atom type. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
AtomType ¶
Bases: Type
Force-field type for a single atom.
An AtomType carries parameters such as mass, charge, and element symbol. Typical keyword parameters include:
mass-- atomic mass in g/mol (amu)charge-- partial charge in elementary charge units (e)element-- chemical element symbol
AtomisticForcefield ¶
Bases: ForceField
Convenience subclass of ForceField with shorthand methods for atomistic styles.
Provides def_*style helpers that create and register the
appropriate Style subclass in a single call, and get_*types
accessors for the most common interaction categories.
def_anglestyle ¶
Create and register an AngleStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the angle style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to AngleStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to AngleStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
AngleStyle
|
The registered (or existing) AngleStyle instance. |
def_atomstyle ¶
Create and register an AtomStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the atom style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to AtomStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to AtomStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
AtomStyle
|
The registered (or existing) AtomStyle instance. |
def_bondstyle ¶
Create and register a BondStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the bond style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to BondStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to BondStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
BondStyle
|
The registered (or existing) BondStyle instance. |
def_dihedralstyle ¶
Create and register a DihedralStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the dihedral style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to DihedralStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to DihedralStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
DihedralStyle
|
The registered (or existing) DihedralStyle instance. |
def_improperstyle ¶
Create and register an ImproperStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the improper style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to ImproperStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to ImproperStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
ImproperStyle
|
The registered (or existing) ImproperStyle instance. |
def_pairstyle ¶
Create and register a PairStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the pair style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to PairStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to PairStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
PairStyle
|
The registered (or existing) PairStyle instance. |
get_angletypes ¶
Return all AngleType instances across all registered styles.
Returns:
| Type | Description |
|---|---|
list[AngleType]
|
Deduplicated list of AngleType instances. |
BondStyle ¶
Bases: Style
Style for bond interactions (e.g. "harmonic").
def_type ¶
to_potential ¶
Create corresponding Potential instance from BondStyle.
Returns:
| Name | Type | Description |
|---|---|---|
Potential |
Potential
|
Potential instance that accepts string type labels (from Frame). The potential internally uses dictionaries to map type names to parameters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If corresponding Potential class not found or missing required parameters |
BondType ¶
Bases: Type
Bond type defined by two atom types
Initialise a bond type between two atom types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this bond type. |
required |
itom
|
AtomType
|
First endpoint atom type. |
required |
jtom
|
AtomType
|
Second endpoint atom type. |
required |
**kwargs
|
Any
|
Bond parameters (e.g. |
{}
|
matches ¶
Check whether this bond type matches an atom type pair.
Matching is order-independent: (at1, at2) matches if
(itom, jtom) equals (at1, at2) or (at2, at1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First atom type. |
required |
at2
|
AtomType
|
Second atom type. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
DihedralStyle ¶
Bases: Style
Style for dihedral (torsion) interactions (e.g. "opls").
def_type ¶
Define dihedral type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType
|
Second atom type |
required |
ktom
|
AtomType
|
Third atom type |
required |
ltom
|
AtomType
|
Fourth atom type |
required |
name
|
str
|
Optional name (defaults to itom-jtom-ktom-ltom) |
''
|
**kwargs
|
Any
|
Dihedral parameters |
{}
|
DihedralType ¶
Bases: Type
Dihedral (torsion) type defined by four atom types.
Initialise a dihedral type for four atom types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this dihedral type. |
required |
itom
|
AtomType
|
First atom type. |
required |
jtom
|
AtomType
|
Second atom type. |
required |
ktom
|
AtomType
|
Third atom type. |
required |
ltom
|
AtomType
|
Fourth atom type. |
required |
**kwargs
|
Any
|
Dihedral parameters (e.g. |
{}
|
matches ¶
Check whether this dihedral type matches an atom type quadruple.
Both forward (at1, at2, at3, at4) and reverse
(at4, at3, at2, at1) orderings are considered equivalent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First atom type. |
required |
at2
|
AtomType
|
Second atom type. |
required |
at3
|
AtomType
|
Third atom type. |
required |
at4
|
AtomType
|
Fourth atom type. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
ForceField ¶
Top-level container for a complete force-field definition.
A ForceField aggregates multiple Style instances (atom, bond,
angle, dihedral, improper, pair) and provides lookup, merging, and
conversion to Potential objects for energy evaluation.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Human-readable name of the force field. |
|
units |
Unit system used by the parameters (e.g. |
Initialise a force field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the force field (e.g. |
''
|
units
|
str
|
Unit convention for parameter values. Defaults to
|
'real'
|
def_style ¶
Register a Style instance with the force field.
The API no longer accepts Style classes. Callers must pass an instantiated
Style (e.g. ff.def_style(AtomStyle("full"))). If a style with the
same runtime class and name already exists it will be returned instead of
registering a duplicate.
get_style_by_name ¶
Get a style by name from the force field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the style to find |
required |
style_class
|
type[S]
|
Class of the style to search for (defaults to Style) |
Style
|
Returns:
| Type | Description |
|---|---|
S | None
|
The first matching Style instance, or None if not found |
get_styles ¶
Retrieve all styles that are instances of the given class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
style_class
|
type[S]
|
The Style subclass to filter by (e.g.
|
required |
Returns:
| Type | Description |
|---|---|
List[S]
|
List of matching Style instances. |
get_types ¶
Collect all types of the given class from every registered style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_class
|
type[Ty]
|
The Type subclass to collect (e.g. |
required |
Returns:
| Type | Description |
|---|---|
list[Ty]
|
Deduplicated list of matching Type instances across all styles. |
merge ¶
Merge another force field's styles and types into this one.
For each style in other, if a style with the same class and name already exists in this force field it is merged in-place; otherwise the style is added as-is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
ForceField
|
The force field whose contents are merged in. |
required |
Returns:
| Type | Description |
|---|---|
ForceField
|
This force field instance (for chaining). |
remove_style ¶
Remove a Style instance of style_class whose name matches.
Returns True if a style was removed.
remove_type ¶
Remove every Type named name from styles of style_class.
Returns the number of Types removed.
rename_type ¶
Rename every Type named old to new in matching styles.
After mutating the internal _name the type is removed and
re-added to its bucket so set-based hash lookups stay consistent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
style_class
|
type[S]
|
Style subclass whose type bucket is targeted. |
required |
old
|
str
|
Existing type name. |
required |
new
|
str
|
Replacement type name. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of Types renamed. |
to_potentials ¶
Create Potential instances from all styles in ForceField.
Returns:
| Name | Type | Description |
|---|---|---|
Potentials |
Potentials
|
Collection containing all created potential instances. |
Note
Only Styles that support to_potential() method will be converted (e.g. BondStyle, AngleStyle, PairStyle)
ImproperStyle ¶
Bases: Style
Style for improper dihedral interactions (e.g. "cvff").
def_type ¶
Define improper dihedral type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType
|
Second atom type (usually central atom) |
required |
ktom
|
AtomType
|
Third atom type |
required |
ltom
|
AtomType
|
Fourth atom type |
required |
name
|
str
|
Optional name (defaults to itom-jtom-ktom-ltom) |
''
|
**kwargs
|
Any
|
Improper dihedral parameters |
{}
|
ImproperType ¶
Bases: Type
Improper dihedral type defined by four atom types.
Improper dihedrals typically have a designated central atom (often
jtom) and are used to enforce planarity or chirality.
Initialise an improper dihedral type for four atom types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this improper type. |
required |
itom
|
AtomType
|
First atom type. |
required |
jtom
|
AtomType
|
Second atom type (typically the central atom). |
required |
ktom
|
AtomType
|
Third atom type. |
required |
ltom
|
AtomType
|
Fourth atom type. |
required |
**kwargs
|
Any
|
Improper parameters (e.g. |
{}
|
matches ¶
Check whether this improper type matches an atom type quadruple.
Uses exact positional matching (no reverse ordering) because improper dihedrals have a specific central atom convention.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First atom type. |
required |
at2
|
AtomType
|
Second atom type. |
required |
at3
|
AtomType
|
Third atom type. |
required |
at4
|
AtomType
|
Fourth atom type. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
PairStyle ¶
Bases: Style
Style for non-bonded pair interactions (e.g. "lj/cut").
def_type ¶
Define non-bonded interaction type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType | None
|
Second atom type (optional, defaults to same as itom for self-interaction) |
None
|
name
|
str
|
Optional name |
''
|
**kwargs
|
Any
|
Non-bonded parameters (e.g. sigma, epsilon, charge, etc.) |
{}
|
PairType ¶
Bases: Type
Non-bonded interaction type defined by one or two atom types
Initialise a non-bonded pair type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this pair type. |
required |
*atom_types
|
AtomType
|
One or two |
()
|
**kwargs
|
Any
|
Pair parameters (e.g. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If not exactly 1 or 2 atom types are provided. |
matches ¶
Check whether this pair type matches an atom type pair.
Matching is order-independent. If only at1 is given, it is treated as a self-interaction query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First atom type. |
required |
at2
|
AtomType | None
|
Second atom type. Defaults to at1 (self-interaction). |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
Parameters ¶
Container for positional and keyword parameters of a force-field type or style.
Provides indexed access to positional arguments (by int or slice)
and keyword arguments (by str).
Initialise with arbitrary positional and keyword arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional parameters (stored as a list). |
()
|
**kwargs
|
Any
|
Keyword parameters (stored as a dict). |
{}
|
Style ¶
Named interaction style that groups related Type instances.
A Style represents a particular functional form for an interaction
category (e.g. BondStyle("harmonic")). It holds a TypeBucket
of Type instances that share the same functional form.
Initialise a named interaction style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the interaction style (e.g. |
required |
*args
|
Any
|
Additional positional parameters forwarded to
|
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to |
{}
|
copy ¶
Create a copy of this style with the same name and parameters (but not types).
Returns:
| Type | Description |
|---|---|
Style
|
A new Style instance with copied name and parameters |
get_type_by_name ¶
Get a type by name from this style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the type to find |
required |
type_class
|
type[Ty]
|
Class of the type to search for (defaults to Type) |
Type
|
Returns:
| Type | Description |
|---|---|
Ty | None
|
The first matching Type instance, or None if not found |
get_types ¶
Get all types of the specified class from this style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_class
|
type[Ty]
|
Class of the types to retrieve (e.g., AtomType, BondType) |
required |
Returns:
| Type | Description |
|---|---|
list[Ty]
|
List of types of the specified class |
merge ¶
Merge another Style's parameters and types into this one.
Parameters from other are appended (positional) or updated (keyword). All types from other are added to this style's type bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Style
|
The style whose contents are merged in. |
required |
Returns:
| Type | Description |
|---|---|
Style
|
This style instance (for chaining). |
Type ¶
Base class for all force-field type descriptors.
A Type carries a unique name together with arbitrary Parameters
that describe a particular force-field entry (e.g. atom type, bond type).
Types are hashed and compared by (class, name) so two instances of
the same subclass with the same name are considered equal.
Initialise a force-field type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this type (e.g. |
required |
*args
|
Any
|
Additional positional parameters forwarded to |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to |
{}
|
copy ¶
Create a copy of this type with the same name and parameters.
Returns:
| Type | Description |
|---|---|
Type
|
A new Type instance with copied parameters |
get ¶
Return a keyword parameter or a default value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Parameter name. |
required |
default
|
Any
|
Value returned when key is absent. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The parameter value if present, otherwise default. |
TypeBucket ¶
A collection that partitions items into buckets keyed by their runtime type.
Items are stored in sets grouped by type(item). Retrieval via
bucket(cls) returns all items whose runtime type is a subclass of
cls, enabling polymorphic queries over heterogeneous collections.
add ¶
Add an item to the bucket corresponding to its runtime type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to store. It is placed in the set keyed by
|
required |
bucket ¶
Retrieve all items whose runtime type is a subclass of cls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
The base class to match against. All items stored under
a key |
required |
Returns:
| Type | Description |
|---|---|
List[T]
|
A flat list of matching items (order is not guaranteed). |
classes ¶
Iterate over the distinct runtime types that have been stored.
Returns:
| Type | Description |
|---|---|
Iterator[type[T]]
|
An iterator of |
Iterator[type[T]]
|
contain at least one item. |
remove ¶
Remove an item from its type bucket.
If the item is not present, this is a no-op (uses discard).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to remove. |
required |
get_nearest_type ¶
Return the most specific runtime type of an item.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
Any object whose runtime class is needed. |
required |
Returns:
| Type | Description |
|---|---|
type[T]
|
The concrete |
Frame¶
frame ¶
Block ¶
Bases: MutableMapping[str, ndarray]
Lightweight container that maps variable names -> NumPy arrays.
• Behaves like a dict but auto-casts any assigned value to ndarray.
• All built-in dict/MutableMapping helpers work out of the box.
• Supports advanced indexing: by key, by index/slice, by mask, by list of keys.
Parameters¶
vars_ : dict[str, ArrayLike] or None, optional Initial data to populate the Block. Keys are variable names, values are array-like data that will be converted to numpy arrays.
Examples¶
Create and access basic data:
blk = Block() blk["x"] = [0.0, 1.0, 2.0] blk["y"] = [0.0, 0.0, 0.0] "x" in blk True len(blk) 2 blk["x"].dtype dtype('float64')
Multiple indexing methods:
blk = Block({"id": [1, 2, 3], "x": [10.0, 20.0, 30.0]}) blk[0] # Access single row, returns dict {'id': 1, 'x': 10.0} blk[0:2] # Slice access {'id': array([1, 2]), 'x': array([10., 20.])} blk[["id", "x"]] # Multi-column access, returns 2D array (requires same dtype) Traceback (most recent call last): ... ValueError: Arrays must have the same dtype...
Using boolean masks for filtering:
blk = Block({"id": [1, 2, 3, 4, 5], "mol_id": [1, 1, 2, 2, 3]}) mask = blk["mol_id"] < 3 sub_blk = blk[mask] sub_blk["id"] array([1, 2, 3, 4]) sub_blk.nrows 4
Sorting:
blk = Block({"x": [3, 1, 2], "y": [30, 10, 20]}) sorted_blk = blk.sort("x") # Returns new Block sorted_blk["x"] array([1, 2, 3]) _ = blk.sort_("x") # In-place sort, returns self blk["x"] array([1, 2, 3])
from_csv
classmethod
¶
Create a Block from a CSV file or StringIO.
Parameters¶
filepath : str, Path, or StringIO Path to the CSV file or StringIO object delimiter : str, default="," CSV delimiter character encoding : str, default="utf-8" File encoding (ignored for StringIO) header : list[str] or None, default=None Column names. If None, first row is used as headers. If provided, CSV is assumed to have no header row. **kwargs Additional arguments passed to csv.reader
Returns¶
Block A new Block instance with data from the CSV file
Examples¶
Read from StringIO:
from io import StringIO csv_data = StringIO("x,y,z\n0,1,2\n3,4,5") block = Block.from_csv(csv_data) block["x"] array([0, 3]) block.nrows 2
CSV without header:
csv_no_header = StringIO("0,1,2\n3,4,5") block = Block.from_csv(csv_no_header, header=["x", "y", "z"]) list(block.keys()) ['x', 'y', 'z'] block.nrows 2
iterrows ¶
Iterate over rows of the block.
Returns¶
Iterator[tuple[int, dict[str, Any]]] An iterator yielding (index, row_data) pairs where: - index: int, the row index - row_data: dict, mapping variable names to their values for this row
Examples¶
blk = Block({ ... "id": [1, 2, 3], ... "type": ["C", "O", "N"], ... "x": [0.0, 1.0, 2.0], ... "y": [0.0, 0.0, 1.0], ... "z": [0.0, 0.0, 0.0] ... }) for index, row in blk.iterrows(): # doctest: +SKIP ... print(f"Row {index}: {row}") Row 0: {'id': 1, 'type': 'C', 'x': 0.0, 'y': 0.0, 'z': 0.0} Row 1: {'id': 2, 'type': 'O', 'x': 1.0, 'y': 0.0, 'z': 0.0} Row 2: {'id': 3, 'type': 'N', 'x': 2.0, 'y': 1.0, 'z': 0.0}
Notes¶
This method is similar to pandas DataFrame.iterrows() but returns a dictionary for each row instead of a pandas Series.
itertuples ¶
Iterate over rows of the block as named tuples.
Parameters¶
index : bool, default=True If True, include the row index as the first element name : str, default="Row" The name of the named tuple class
Returns¶
Iterator[Any] An iterator yielding named tuples for each row
Examples¶
blk = Block({ ... "id": [1, 2, 3], ... "type": ["C", "O", "N"], ... "x": [0.0, 1.0, 2.0] ... }) for row in blk.itertuples(): ... print(f"Index: {row.Index}, ID: {row.id}, Type: {row.type}") Index: 0, ID: 1, Type: C Index: 1, ID: 2, Type: O Index: 2, ID: 3, Type: N
Notes¶
This method is similar to pandas DataFrame.itertuples().
rename ¶
Rename a column key in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_key
|
str
|
Existing column name. |
required |
new_key
|
str
|
New column name. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If old_key does not exist. |
sort ¶
Sort the block by a specific variable and return a new sorted Block.
This method creates a new Block instance with sorted data, leaving the original Block unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The variable name to sort by. |
required |
reverse
|
bool
|
If True, sort in descending order. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Block
|
A new Block with sorted data. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the key variable doesn't exist in the block. |
ValueError
|
If any variable has different length than the key variable. |
Example
blk = Block({"x": [3, 1, 2], "y": [30, 10, 20]}) sorted_blk = blk.sort("x") sorted_blk["x"] array([1, 2, 3]) sorted_blk["y"] array([10, 20, 30])
Original block is unchanged¶
blk["x"] array([3, 1, 2])
sort_ ¶
Sort the block in-place by a specific variable.
This method modifies the current Block instance by sorting all variables according to the specified key. The original data is overwritten.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The variable name to sort by. |
required |
reverse
|
bool
|
If True, sort in descending order. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Self
|
Self (for method chaining). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the key variable doesn't exist in the block. |
ValueError
|
If any variable has different length than the key variable. |
Example
blk = Block({"x": [3, 1, 2], "y": [30, 10, 20]}) _ = blk.sort_("x") # Returns self for chaining blk["x"] array([1, 2, 3]) blk["y"] array([10, 20, 30])
Original data is now sorted¶
Frame ¶
Hierarchical numerical data container with named blocks.
Frame stores multiple Block objects under string keys (e.g., "atoms", "bonds") and allows arbitrary metadata to be attached. It's designed for molecular simulation data where different entity types need separate tabular storage.
Structure
Frame ├─ blocks: dict[str, Block] # Named data blocks └─ metadata: dict[str, Any] # Arbitrary metadata (box, timestep, etc.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
blocks
|
dict[str, Block | dict] | None
|
Initial blocks. If a dict value is not a Block, it will be converted. |
None
|
**props
|
Any
|
Arbitrary keyword arguments stored in metadata. |
{}
|
Examples:
Create Frame and add data blocks:
>>> frame = Frame()
>>> frame["atoms"] = Block({"x": [0.0, 1.0], "y": [0.0, 0.0], "z": [0.0, 0.0]})
>>> frame["atoms"]["x"]
array([0., 1.])
>>> frame["atoms"].nrows
2
Initialize with nested dictionaries:
>>> frame = Frame(blocks={
... "atoms": {"id": [1, 2, 3], "type": ["C", "H", "H"]},
... "bonds": {"atomi": [0, 0], "atomj": [1, 2]}
... })
>>> list(frame._blocks)
['atoms', 'bonds']
>>> frame["atoms"]["id"]
array([1, 2, 3])
Add metadata:
>>> frame = Frame()
>>> frame.metadata["timestep"] = 0
>>> frame.metadata["description"] = "Test system"
>>> frame.metadata["timestep"]
0
>>> frame.metadata["description"]
'Test system'
Chained access:
>>> frame = Frame(blocks={"atoms": {"x": [1, 2, 3], "y": [4, 5, 6]}})
>>> atoms = frame["atoms"]
>>> xyz_combined = atoms[["x", "y"]]
>>> xyz_combined.shape
(3, 2)
Iterate over all blocks and variables:
>>> frame = Frame(blocks={
... "atoms": {"id": [1, 2], "mass": [12.0, 1.0]},
... "bonds": {"atomi": [0], "atomj": [1]}
... })
>>> for block_name in frame._blocks:
... print(f"{block_name}: {list(frame[block_name].keys())}")
atoms: ['id', 'mass']
bonds: ['atomi', 'atomj']
Initialize a Frame with optional blocks and metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
blocks
|
dict[str, Block | BlockLike] | None
|
Initial blocks. If a dict value is not a Block, it will be converted to a Block. Defaults to None. |
None
|
**props
|
Any
|
Arbitrary keyword arguments stored in metadata. |
{}
|
blocks
property
¶
Iterate over stored Block objects.
Returns:
| Type | Description |
|---|---|
Iterator[Block]
|
Iterator[Block]: Iterator over Block values stored in this Frame. |
Note
To iterate over block names use for name in frame._blocks or
frame._blocks.keys().
Examples:
copy ¶
Create a shallow copy of the Frame.
Blocks are copied (shallow), but the underlying numpy arrays are not.
Returns:
| Name | Type | Description |
|---|---|---|
Frame |
Frame
|
A new Frame instance with copied blocks and metadata. |
Examples:
from_dict
classmethod
¶
Create a Frame from a dictionary representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dictionary containing "blocks" and optionally "metadata" keys. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Frame |
Frame
|
A new Frame instance reconstructed from the dictionary. |
Examples:
to_dict ¶
Convert Frame to a dictionary representation.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Dictionary containing "blocks" and "metadata" keys. Blocks are converted to dictionaries via Block.to_dict(). |
Examples:
Topology¶
topology ¶
Molecular topology graph using igraph.
Provides graph-based representation of molecular connectivity with automated detection of angles, dihedrals, and impropers.
Topology ¶
Bases: Graph
Topology graph with bidirectional entity-to-index mapping.
Attributes:
| Name | Type | Description |
|---|---|---|
entity_to_idx |
dict[Any, int]
|
Dictionary mapping Entity objects to their vertex indices |
idx_to_entity |
list[Any]
|
List mapping vertex indices to Entity objects |
Initialize Topology graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Arguments passed to igraph.Graph.init. |
()
|
entity_to_idx
|
dict[Any, int] | None
|
Optional dictionary mapping entities to indices. |
None
|
idx_to_entity
|
list[Any] | None
|
Optional list mapping indices to entities. |
None
|
**kwargs
|
Any
|
Keyword arguments passed to igraph.Graph.init. |
{}
|
Trajectory¶
trajectory ¶
CustomStrategy ¶
Bases: SplitStrategy
Split trajectory using a custom function.
Allows users to define their own splitting logic by providing a function that returns split point indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
split_func
|
Callable[[Trajectory], list[int]]
|
A function that takes a Trajectory and returns a list of split indices. The first index should be 0, and the last should be the total frame count. |
required |
Examples:
>>> def custom_split(traj):
... # Split at frames 0, 5, 10, 15
... return [0, 5, 10, 15]
>>> strategy = CustomStrategy(custom_split)
>>> splitter = TrajectorySplitter(traj)
>>> segments = splitter.split(strategy)
get_split_indices ¶
Get split indices using the custom function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: List of split point indices from the custom function. |
FrameIntervalStrategy ¶
Bases: SplitStrategy
Split trajectory at regular frame intervals.
Splits the trajectory every N frames, creating segments of equal size (except possibly the last segment).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
int
|
Number of frames per segment. Must be positive. |
required |
Examples:
>>> traj = Trajectory([Frame() for _ in range(10)])
>>> strategy = FrameIntervalStrategy(interval=3)
>>> splitter = TrajectorySplitter(traj)
>>> segments = splitter.split(strategy)
>>> len(segments) # Creates segments of 3, 3, 3, and 1 frames
4
get_split_indices ¶
Get split indices at regular frame intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: List of split point indices. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the trajectory doesn't have a known length. |
SplitStrategy ¶
Bases: ABC
Abstract base class for trajectory splitting strategies.
Subclasses implement different strategies for dividing a trajectory into segments based on various criteria (frame count, time intervals, etc.).
get_split_indices
abstractmethod
¶
Get split point indices for dividing the trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: List of indices where the trajectory should be split. The first index should be 0, and the last should be the total number of frames. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Must be implemented by subclasses. |
TimeIntervalStrategy ¶
Bases: SplitStrategy
Split trajectory by time intervals.
Splits the trajectory based on time information stored in frame metadata. Frames must have a "time" key in their metadata dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Time interval for splitting (in the same units as frame time metadata). Must be positive. |
required |
Examples:
>>> frames = [Frame() for _ in range(10)]
>>> for i, frame in enumerate(frames):
... frame.metadata["time"] = i * 0.1 # 0.0, 0.1, 0.2, ...
>>> traj = Trajectory(frames)
>>> strategy = TimeIntervalStrategy(interval=0.5)
>>> splitter = TrajectorySplitter(traj)
>>> segments = splitter.split(strategy)
get_split_indices ¶
Get split indices based on time intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. Frames should have "time" in metadata. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: List of split point indices based on time intervals. |
Note
Frames without time information are skipped. The first frame with time information is used as the reference start time.
Trajectory ¶
A sequence of molecular frames with optional topology.
Trajectory is a container for a sequence of Frame objects, supporting both eager (Sequence) and lazy (Iterable/Generator) frame storage. It provides iteration, indexing, slicing, and mapping operations.
Attributes:
| Name | Type | Description |
|---|---|---|
_frames |
Iterable[Frame]
|
The underlying frame sequence. Can be a Sequence (list, tuple) for random access, or an Iterable (generator) for lazy loading. |
_topology |
Topology | None
|
Optional topology information shared across all frames in the trajectory. |
Examples:
Create from a list of frames:
>>> frames = [Frame(), Frame(), Frame()]
>>> traj = Trajectory(frames)
>>> len(traj)
3
>>> traj[0] # Access first frame
Frame(...)
Create from a generator (lazy loading):
>>> def frame_generator():
... for i in range(10):
... yield Frame()
>>> traj = Trajectory(frame_generator())
>>> # Can iterate but not index
>>> for frame in traj:
... pass
Slice a trajectory:
Map a function over frames:
>>> def center_frame(frame):
... # Center coordinates at origin
... atoms = frame["atoms"]
... xyz = atoms[["x", "y", "z"]]
... center = xyz.mean(axis=0)
... atoms["x"] = atoms["x"] - center[0]
... atoms["y"] = atoms["y"] - center[1]
... atoms["z"] = atoms["z"] - center[2]
... return frame
>>> centered_traj = traj.map(center_frame)
Initialize trajectory with frames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
Iterable[Frame]
|
An iterable or sequence of Frame objects. If a Sequence is provided, the trajectory supports length and indexing. If an Iterable (e.g., generator) is provided, only iteration is supported. |
required |
topology
|
Topology | None
|
Optional topology information for the trajectory. Defaults to None. |
None
|
has_length ¶
Check if this trajectory has a known length without computing it.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the trajectory supports len(), False otherwise. |
Examples:
map ¶
Apply a function to each frame, returning a new trajectory.
The mapping is applied lazily - the function is only called when frames are accessed, making it memory-efficient for large trajectories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[[Frame], Frame]
|
A function that takes a Frame and returns a Frame. The function will be applied lazily as frames are accessed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Trajectory |
Trajectory
|
A new Trajectory with mapped frames. The original trajectory is not modified. |
Examples:
>>> traj = Trajectory([Frame(), Frame()])
>>> def center_frame(frame):
... # Center coordinates at origin
... atoms = frame["atoms"]
... xyz = atoms[["x", "y", "z"]]
... center = xyz.mean(axis=0)
... atoms["x"] = atoms["x"] - center[0]
... atoms["y"] = atoms["y"] - center[1]
... atoms["z"] = atoms["z"] - center[2]
... return frame
>>> centered_traj = traj.map(center_frame)
>>> len(centered_traj)
2
TrajectorySplitter ¶
Splits trajectories into lazy segments.
Provides a convenient interface for splitting trajectories using various strategies. The resulting segments are lazy Trajectory objects that share the same topology as the original.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
Examples:
>>> traj = Trajectory([Frame() for _ in range(100)])
>>> splitter = TrajectorySplitter(traj)
>>> # Split every 10 frames
>>> segments = splitter.split_frames(interval=10)
>>> len(segments)
10
>>> len(segments[0])
10
Initialize the splitter with a trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
split ¶
Split trajectory using a strategy, returning lazy segments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy
|
SplitStrategy
|
The splitting strategy to use. |
required |
Returns:
| Type | Description |
|---|---|
list[Trajectory]
|
list[Trajectory]: List of trajectory segments. Each segment is a new Trajectory containing a subset of frames from the original. |
Examples:
split_frames ¶
Convenience method for frame-based splitting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
int
|
Number of frames per segment. |
required |
Returns:
| Type | Description |
|---|---|
list[Trajectory]
|
list[Trajectory]: List of trajectory segments. |
Examples:
split_time ¶
Convenience method for time-based splitting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Time interval for splitting (in frame time units). |
required |
Returns:
| Type | Description |
|---|---|
list[Trajectory]
|
list[Trajectory]: List of trajectory segments. |
Examples:
Coarse-Grain¶
cg ¶
Bead ¶
Bases: Entity
Coarse-grain bead entity.
A bead can optionally map to an Atomistic structure via the atomistic member. Supports arbitrary attributes via dictionary interface.
Attributes:
| Name | Type | Description |
|---|---|---|
atomistic |
Optional reference to an Atomistic structure this bead represents |
CGBond ¶
CoarseGrain ¶
Bases: Struct, MembershipMixin, SpatialMixin, ConnectivityMixin
Coarse-grained molecular structure container.
Similar to Atomistic but for coarse-grained representations using Beads and CGBonds. Supports bidirectional conversion with Atomistic structures.
align ¶
Align beads. Returns self for chaining.
def_bead ¶
Create a new Bead and add it to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atomistic
|
'Atomistic | None'
|
Optional Atomistic structure this bead represents |
None
|
**attrs
|
Any
|
Bead attributes (x, y, z, type, etc.) |
{}
|
def_cgbond ¶
Create a new CGBond between two beads and add it to the structure.
def_cgbonds ¶
Create multiple CGBonds from a list of (ibead, jbead) or (ibead, jbead, attrs) tuples.
from_atomistic
classmethod
¶
Create CoarseGrain structure from Atomistic using a bead mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atomistic
|
'Atomistic'
|
Atomistic structure to convert |
required |
bead_mask
|
'np.ndarray'
|
Numpy array where each element indicates which bead the atom belongs to. Can be boolean (True = bead 0) or integer indices. |
required |
Returns:
| Type | Description |
|---|---|
'CoarseGrain'
|
CoarseGrain structure with beads mapped to atomistic substructures |
rename_type ¶
Rename all beads/bonds of kind whose type attribute equals old.
Returns the number of items updated.
replicate ¶
Create n copies and merge them into a new system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of copies to create. |
required |
transform
|
Callable | None
|
Optional callable(copy, index) -> None to transform each copy. |
None
|
Example
Create 10 copies in a line¶
cg_line = cg.replicate(10, lambda mol, i: mol.move([i*5, 0, 0]))
rotate ¶
Rotate beads around axis. Returns self for chaining.
scale ¶
Scale beads by factor. Returns self for chaining.
select ¶
Return a new CoarseGrain containing only beads matching predicate.
Bonds whose endpoints are fully inside the selection are carried over.
set_property ¶
Set a property on every bead (or link) matching the callable selector.
to_atomistic ¶
Convert CoarseGrain structure to Atomistic representation.
Beads with atomistic member are expanded to their full atomistic structure. Beads without atomistic mapping create a single atom at the bead position. CGBonds are converted to atomistic bonds between representative atoms.
Returns:
| Type | Description |
|---|---|
'Atomistic'
|
Atomistic structure |
Config¶
config ¶
Global configuration system for MolPy.
This module provides a thread-safe singleton configuration system using Pydantic. Configuration can be accessed globally, updated, reset, or temporarily overridden using a context manager.
Examples:
>>> from molpy.core.config import config, Config
>>>
>>> # Access current config
>>> print(config.log_level)
'INFO'
>>>
>>> # Update config globally
>>> Config.update(log_level='DEBUG', n_threads=4)
>>>
>>> # Temporary override
>>> with Config.temporary(log_level='WARNING'):
... print(config.log_level) # 'WARNING'
>>> print(config.log_level) # Back to 'DEBUG'
Config ¶
Bases: BaseModel
Global configuration for MolPy.
Thread-safe singleton that stores global settings like logging level and parallelization parameters. Use class methods to access and modify the singleton instance.
Attributes:
| Name | Type | Description |
|---|---|---|
log_level |
str
|
Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
n_threads |
int
|
Number of threads for parallel computations |
Examples:
>>> # Get singleton instance
>>> cfg = Config.instance()
>>>
>>> # Update configuration
>>> Config.update(n_threads=8)
>>>
>>> # Temporary override
>>> with Config.temporary(log_level='DEBUG'):
... # Config is DEBUG here
... pass
>>> # Config restored here
instance
classmethod
¶
reset
classmethod
¶
temporary
classmethod
¶
Temporarily override configuration within a context.
Thread-safe context manager that restores original config on exit. Useful for testing or temporary parameter changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**overrides
|
Any
|
Configuration fields to temporarily override. |
{}
|
Yields:
| Type | Description |
|---|---|
None
|
None |
Examples:
update
classmethod
¶
Update the global configuration.
Thread-safe update that creates a new instance with updated values. Changes persist until reset() or another update().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Configuration fields to update (log_level, n_threads, etc.). |
{}
|
Examples:
Script¶
script ¶
Script - Editable script management with filesystem and URL support.
This module provides a Script class for managing script content that can be stored locally or loaded from URLs. It supports editing, formatting, and filesystem operations without any execution logic.
Script
dataclass
¶
Represents an editable script with filesystem and URL support.
This class manages script content, metadata, and filesystem operations. It does NOT provide execution logic - only content management.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Logical name of the script |
language |
ScriptLanguage
|
Script language type |
description |
str | None
|
Optional human-readable description |
_lines |
list[str]
|
Internal storage for multi-line content |
path |
Path | None
|
Local file path if stored on disk |
url |
str | None
|
URL the script was loaded from (if any) |
tags |
set[str]
|
Optional lightweight tag system |
lines
property
¶
Get a copy of all script lines.
Returns:
| Type | Description |
|---|---|
list[str]
|
Copy of internal lines list |
text
property
¶
Get the full script as a single string.
Returns:
| Type | Description |
|---|---|
str
|
Script content with lines joined by newlines, with exactly one trailing newline |
append ¶
Append a single line to the end of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
Line content to append |
''
|
append_block ¶
Append a multi-line block to the script.
The block is dedented, trailing newlines are stripped, and then split into lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
str
|
Multi-line string block to append |
required |
delete ¶
Delete the line at the given index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
0-based index of line to delete |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range |
delete_file ¶
Delete the script file from the filesystem.
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the file does not exist |
OSError
|
If the file cannot be deleted |
extend ¶
Append multiple lines in order to the end of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
Iterable of lines to append |
required |
format ¶
Apply string formatting to all lines and return a new Script.
Uses Python's str.format(**kwargs) on each line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Format arguments |
{}
|
Returns:
| Type | Description |
|---|---|
Script
|
New Script instance with formatted lines |
format_with_mapping ¶
Apply string formatting to all lines using a mapping and return a new Script.
Uses Python's str.format_map(mapping) on each line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping[str, Any]
|
Format mapping |
required |
Returns:
| Type | Description |
|---|---|
Script
|
New Script instance with formatted lines |
from_path
classmethod
¶
Create a Script from a local file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the script file |
required |
language
|
ScriptLanguage | None
|
Optional language override. If None, guessed from extension |
None
|
description
|
str | None
|
Optional description |
None
|
Returns:
| Type | Description |
|---|---|
Script
|
Script instance loaded from file |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist |
IOError
|
If the file cannot be read |
from_text
classmethod
¶
Create a Script from text content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logical name of the script |
required |
text
|
str
|
Multi-line text content |
required |
language
|
ScriptLanguage
|
Script language type |
'bash'
|
description
|
str | None
|
Optional description |
None
|
path
|
str | Path | None
|
Optional local file path |
None
|
url
|
str | None
|
Optional URL source |
None
|
Returns:
| Type | Description |
|---|---|
Script
|
Script instance with normalized content |
from_url
classmethod
¶
Create a Script from a URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to fetch the script from |
required |
name
|
str | None
|
Optional name. If None, derived from URL |
None
|
language
|
ScriptLanguage
|
Script language type |
'other'
|
description
|
str | None
|
Optional description |
None
|
Returns:
| Type | Description |
|---|---|
Script
|
Script instance loaded from URL |
Raises:
| Type | Description |
|---|---|
URLError
|
If the URL cannot be fetched |
insert ¶
Insert a single line at the given index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
0-based index where to insert |
required |
line
|
str
|
Line content to insert |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range |
move ¶
Move the script file to a new location.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_path
|
str | Path
|
New file path |
required |
Returns:
| Type | Description |
|---|---|
Path
|
New path where the script was moved |
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the original file does not exist |
OSError
|
If the file cannot be moved |
preview ¶
Generate a preview of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_lines
|
int
|
Maximum number of lines to show |
20
|
with_line_numbers
|
bool
|
Whether to include line numbers |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Preview string |
reload ¶
Reload the script content from its associated path.
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the file does not exist |
IOError
|
If the file cannot be read |
rename ¶
Rename the script file (keeping the same directory).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_name
|
str
|
New file name (with or without extension) |
required |
Returns:
| Type | Description |
|---|---|
Path
|
New path where the script was renamed |
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the original file does not exist |
OSError
|
If the file cannot be renamed |
replace ¶
Replace the line at the given index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
0-based index of line to replace |
required |
line
|
str
|
New line content |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range |
save ¶
Save the script to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | None
|
Optional path to save to. If None, uses self.path |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path where the script was saved |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no path is provided and self.path is None |
IOError
|
If the file cannot be written |