Skip to content

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)

Full API

Atomistic

atomistic

Angle

Angle(a, b, c, /, **attrs)

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., type="C-C-C").

{}

Raises:

Type Description
AssertionError

If any argument is not an Atom instance.

itom property
itom

First atom endpoint of the angle.

jtom property
jtom

Central (vertex) atom of the angle.

ktom property
ktom

Third atom endpoint of the angle.

Atom

Bases: Entity

Atom entity (common keys include {"element": "C", "xyz": [...]})

Atomistic

Atomistic(**props)

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., name="water", charge=0.0).

{}
angles property
angles

All angles in this structure.

Returns:

Type Description
Entities[Angle]

Entities[Angle]: Column-accessible list of Angle objects.

atoms property
atoms

All atoms in this structure.

Returns:

Type Description
Entities[Atom]

Entities[Atom]: Column-accessible list of Atom objects.

bonds property
bonds

All bonds in this structure.

Returns:

Type Description
Entities[Bond]

Entities[Bond]: Column-accessible list of Bond objects.

dihedrals property
dihedrals

All dihedrals in this structure.

Returns:

Type Description
Entities[Dihedral]

Entities[Dihedral]: Column-accessible list of Dihedral objects.

impropers property
impropers

All impropers in this structure.

Returns:

Type Description
Entities[Improper]

Entities[Improper]: Column-accessible list of Improper objects.

positions property
positions

Alias for xyz property.

symbols property
symbols

Element symbols for every atom in insertion order.

Returns:

Type Description
list[str]

list[str]: List of element strings (e.g., ["C", "H", "H"]). Atoms without an "element" key produce an empty string.

xyz property
xyz

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_angle(angle)

Add an existing Angle object to the structure.

Parameters:

Name Type Description Default
angle Angle

Angle instance to register.

required

Returns:

Name Type Description
Angle Angle

The same angle passed in.

add_angles
add_angles(angles)

Add multiple existing Angle objects to the structure.

Parameters:

Name Type Description Default
angles list[Angle]

Angle instances to register.

required

Returns:

Type Description
list[Angle]

list[Angle]: The same list passed in.

add_atom
add_atom(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_atoms(atoms)

Add multiple existing Atom objects to the structure.

Parameters:

Name Type Description Default
atoms list[Atom]

Atom instances to register.

required

Returns:

Type Description
list[Atom]

list[Atom]: The same list passed in.

add_bond
add_bond(bond)

Add an existing Bond object to the structure.

Parameters:

Name Type Description Default
bond Bond

Bond instance to register.

required

Returns:

Name Type Description
Bond Bond

The same bond passed in.

add_bonds
add_bonds(bonds)

Add multiple existing Bond objects to the structure.

Parameters:

Name Type Description Default
bonds list[Bond]

Bond instances to register.

required

Returns:

Type Description
list[Bond]

list[Bond]: The same list passed in.

add_dihedral
add_dihedral(dihedral)

Add an existing Dihedral object to the structure.

Parameters:

Name Type Description Default
dihedral Dihedral

Dihedral instance to register.

required

Returns:

Name Type Description
Dihedral Dihedral

The same dihedral passed in.

add_dihedrals
add_dihedrals(dihedrals)

Add multiple existing Dihedral objects to the structure.

Parameters:

Name Type Description Default
dihedrals list[Dihedral]

Dihedral instances to register.

required

Returns:

Type Description
list[Dihedral]

list[Dihedral]: The same list passed in.

add_improper
add_improper(improper)

Add an existing Improper object to the structure.

Parameters:

Name Type Description Default
improper Improper

Improper instance to register.

required

Returns:

Name Type Description
Improper Improper

The same improper passed in.

align
align(a, b, *, a_dir=None, b_dir=None, flip=False, entity_type=Atom)

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 a (will be normalised).

None
b_dir list[float] | None

Direction vector at b (will be normalised).

None
flip bool

If True, reverse b_dir before alignment.

False
entity_type type[Entity]

Entity type to transform (default: Atom).

Atom

Returns:

Name Type Description
Atomistic 'Atomistic'

self, for chaining.

def_angle
def_angle(a, b, c, /, **attrs)

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., type="C-C-C").

{}

Returns:

Name Type Description
Angle Angle

The newly created and registered angle.

def_angles
def_angles(angles_data)

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 (itom, jtom, ktom) or (itom, jtom, ktom, attrs_dict).

required

Returns:

Type Description
list[Angle]

list[Angle]: Newly created angles in the same order as input.

def_atom
def_atom(**attrs)

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 element (str), type (str), charge (float, elementary charge units), mass (float, g/mol), and xyz (sequence of 3 floats in angstroms).

{}

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
def_atoms(atoms_data)

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 **attrs to def_atom. See def_atom for supported keys.

required

Returns:

Type Description
list[Atom]

list[Atom]: Newly created atoms in the same order as input.

def_bond
def_bond(a, b, /, **attrs)

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., type="C-C", order=1).

{}

Returns:

Name Type Description
Bond Bond

The newly created and registered bond.

def_bonds
def_bonds(bonds_data)

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 (itom, jtom) or (itom, jtom, attrs_dict).

required

Returns:

Type Description
list[Bond]

list[Bond]: Newly created bonds in the same order as input.

def_dihedral
def_dihedral(a, b, c, d, /, **attrs)

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., type="C-C-C-C").

{}

Returns:

Name Type Description
Dihedral Dihedral

The newly created and registered dihedral.

def_dihedrals
def_dihedrals(dihedrals_data)

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 (itom, jtom, ktom, ltom) or (itom, jtom, ktom, ltom, attrs_dict).

required

Returns:

Type Description
list[Dihedral]

list[Dihedral]: Newly created dihedrals in the same order as input.

def_improper
def_improper(a, b, c, d, /, **attrs)

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., type="C-C-C-C").

{}

Returns:

Name Type Description
Improper Improper

The newly created and registered improper.

del_angle
del_angle(*angles)

Remove angles from the structure.

Parameters:

Name Type Description Default
*angles Angle

Angle instances to remove.

()
del_atom
del_atom(*atoms)

Remove atoms and all their incident bonds, angles, and dihedrals.

Parameters:

Name Type Description Default
*atoms Atom

Atom instances to remove.

()
del_bond
del_bond(*bonds)

Remove bonds (and any dependent angles / dihedrals that reference them).

Parameters:

Name Type Description Default
*bonds Bond

Bond instances to remove.

()
del_dihedral
del_dihedral(*dihedrals)

Remove dihedrals from the structure.

Parameters:

Name Type Description Default
*dihedrals Dihedral

Dihedral instances to remove.

()
del_improper
del_improper(*impropers)

Remove impropers from the structure.

Parameters:

Name Type Description Default
*impropers Improper

Improper instances to remove.

()
extract_subgraph
extract_subgraph(center_entities, radius, entity_type=Atom, link_type=Bond)

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
get_topo(entity_type=Atom, link_type=Bond, gen_angle=False, gen_dihe=False, clear_existing=False)

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
move(delta, *, entity_type=Atom)

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 [dx, dy, dz] in angstroms.

required
entity_type type[Entity]

Entity type to translate (default: Atom).

Atom

Returns:

Name Type Description
Atomistic 'Atomistic'

self, for chaining (e.g., mol.move([1, 0, 0]).rotate(...)).

rename_type
rename_type(old, new, *, kind=Atom)

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). Pass Bond, Angle, Dihedral to rename those link types.

Atom

Returns:

Type Description
int

Number of entities/links whose type was renamed.

replicate
replicate(n, transform=None)

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 (copy: Atomistic, index: int) -> None applied to each copy before merging. The callable receives the deep-copied replica and its zero-based index.

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(axis, angle, about=None, *, entity_type=Atom)

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 [ax, ay, az] (will be normalised internally).

required
angle float

Rotation angle in radians.

required
about list[float] | None

Point [x, y, z] in angstroms to rotate around. Defaults to the origin [0, 0, 0].

None
entity_type type[Entity]

Entity type to rotate (default: Atom).

Atom

Returns:

Name Type Description
Atomistic 'Atomistic'

self, for chaining.

scale
scale(factor, about=None, *, entity_type=Atom)

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 [x, y, z] in angstroms. Defaults to the origin [0, 0, 0].

None
entity_type type[Entity]

Entity type to scale (default: Atom).

Atom

Returns:

Name Type Description
Atomistic 'Atomistic'

self, for chaining.

select
select(predicate)

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 (atom) -> bool.

required

Returns:

Type Description
'Atomistic'

New Atomistic with the selected atoms and their induced topology.

set_property
set_property(selector, key, value, *, kind=Atom)

Set a property on every atom (or link) matching selector.

Parameters:

Name Type Description Default
selector

Callable (atom) -> bool used to pick targets.

required
key str

Property key to assign.

required
value Any

Value to store.

required
kind type

Entity or Link class to iterate (default: Atom).

Atom

Returns:

Type Description
int

Number of items updated.

to_frame
to_frame(atom_fields=None)

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

Bond(a, b, /, **attrs)

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., type="C-C", order=2).

{}

Raises:

Type Description
AssertionError

If either argument is not an Atom instance.

itom property
itom

First atom endpoint of the bond.

jtom property
jtom

Second atom endpoint of the bond.

Dihedral

Dihedral(a, b, c, d, /, **attrs)

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., type="C-C-C-C").

{}

Raises:

Type Description
AssertionError

If any argument is not an Atom instance.

itom property
itom

First atom endpoint of the dihedral.

jtom property
jtom

Second atom (part of the central bond).

ktom property
ktom

Third atom (part of the central bond).

ltom property
ltom

Fourth atom endpoint of the dihedral.

Improper

Improper(a, b, c, d, /, **attrs)

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., type="C-C-C-C").

{}

Raises:

Type Description
AssertionError

If any argument is not an Atom instance.

itom property
itom

Central atom of the improper torsion.

jtom property
jtom

First substituent atom.

ktom property
ktom

Second substituent atom.

ltom property
ltom

Third substituent atom.

Box

box

Box

Box(matrix=None, pbc=np.ones(3, dtype=bool), origin=np.zeros(3))

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 (3, 3). None or an all-zero matrix produces a FREE box. A 1-D array of shape (3,) is promoted to a diagonal matrix.

None
pbc ArrayLike

Boolean periodic-boundary flags per axis, shape (3,).

ones(3, dtype=bool)
origin ArrayLike

Cartesian origin of the box in Angstroms, shape (3,).

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
a

First lattice vector of the box in Angstroms.

Returns:

Type Description
ndarray

np.ndarray: Column 0 of the box matrix, shape (3,).

angles property
angles

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 (3,).

b property
b

Second lattice vector of the box in Angstroms.

Returns:

Type Description
ndarray

np.ndarray: Column 1 of the box matrix, shape (3,).

bounds property
bounds

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
c

Third lattice vector of the box in Angstroms.

Returns:

Type Description
ndarray

np.ndarray: Column 2 of the box matrix, shape (3,).

is_periodic property
is_periodic

Check if the box has periodic boundary conditions in all directions.

l property
l

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
l_inv

Reciprocal of the box edge lengths in inverse Angstroms.

Returns:

Type Description
ndarray

np.ndarray: 1 / [lx, ly, lz], shape (3,).

lengths property writable
lengths

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 (3,).

lx property writable
lx

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
ly

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
lz

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
matrix

Get the matrix representation of the box.

Returns:

Type Description
ndarray

np.ndarray: A 3x3 matrix representing the box dimensions.

origin property writable
origin

Cartesian origin of the box in Angstroms.

Returns:

Type Description
ndarray

np.ndarray: Origin coordinates, shape (3,).

pbc property
pbc

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
periodic

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
periodic_x

Whether the box is periodic along the x-axis.

Returns:

Name Type Description
bool bool

True if periodic in x.

periodic_y property writable
periodic_y

Whether the box is periodic along the y-axis.

Returns:

Name Type Description
bool bool

True if periodic in y.

periodic_z property writable
periodic_z

Whether the box is periodic along the z-axis.

Returns:

Name Type Description
bool bool

True if periodic in z.

style property
style

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
tilts

Off-diagonal tilt factors of the box matrix in Angstroms.

Returns:

Type Description
ndarray

np.ndarray: [xy, xz, yz], shape (3,).

volume property
volume

Calculate the volume of the box.

Returns:

Name Type Description
float float

The volume of the box.

xhi property
xhi

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
xlo

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
xy

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
xz

Tilt factor between the x and z axes in Angstroms.

Returns:

Name Type Description
float float

The (0, 2) element of the box matrix.

yhi property
yhi

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
ylo

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
yz

Tilt factor between the y and z axes in Angstroms.

Returns:

Name Type Description
float float

The (1, 2) element of the box matrix.

zhi property
zhi

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
zlo

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
calc_lengths_angles_from_matrix(matrix)

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
calc_matrix_from_lengths_angles(abc, angles)

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
calc_matrix_from_size_tilts(sizes, tilts)

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
calc_style_from_matrix(matrix)

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
check_matrix(matrix)

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
cubic(length, pbc=np.ones(3, dtype=bool), origin=np.zeros(3), central=False)

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 (3,).

ones(3, dtype=bool)
origin ArrayLike

Cartesian origin of the box in Angstroms, shape (3,).

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 Box instance.

diff
diff(r1, r2)

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
diff_all(r1, r2)

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
diff_dr(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
dist(r1, r2)

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
dist_all(r1, r2)

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
from_bounds(points, padding=0.0, pbc=np.zeros(3, dtype=bool))

Create an orthogonal box that encloses a set of points.

Parameters:

Name Type Description Default
points ArrayLike

Point coordinates to enclose, shape (N, 3).

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 (3,).

0.0
pbc ArrayLike

Periodic boundary flags per axis, shape (3,). Defaults to non-periodic.

zeros(3, dtype=bool)

Returns:

Type Description
Box

A new orthogonal Box whose matrix and origin tightly fit

Box

points with padding added on every side.

Raises:

Type Description
ValueError

If points is empty or not (N, 3).

from_box classmethod
from_box(box)

Create a new box from an existing box.

Parameters:

Name Type Description Default
box Box

The existing box.

required

Returns:

Name Type Description
Box Box

A new box with the same properties as the existing box.

from_lengths_angles classmethod
from_lengths_angles(lengths, angles)

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
general2restrict(matrix)

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
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 [d_x, d_y, d_z] in Angstroms, shape (3,). All zeros for a FREE box.

get_images
get_images(xyz)

Get the image flags of particles, accounting for box origin and triclinic shape.

get_inv
get_inv()

Get the inverse of the box matrix.

Returns:

Type Description
ndarray

np.ndarray: The inverse of the box matrix.

isin
isin(xyz)

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
make_absolute(xyz)

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
make_fractional(xyz)

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
merge(other)

Merge two boxes to find their common space.

Parameters:

Name Type Description Default
other Box

The other box to merge with.

required

Returns:

Name Type Description
Box Box

A new box representing the common space.

orth classmethod
orth(lengths, pbc=np.ones(3, dtype=bool), origin=np.zeros(3), central=False)

Create an orthogonal (axis-aligned cuboid) box.

Parameters:

Name Type Description Default
lengths ArrayLike

Edge lengths [lx, ly, lz] in Angstroms, shape (3,).

required
pbc ArrayLike

Periodic boundary flags per axis, shape (3,).

ones(3, dtype=bool)
origin ArrayLike

Cartesian origin of the box in Angstroms, shape (3,).

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 Box instance.

plot
plot()

Plot the box representation. This method is a placeholder and should be implemented to visualize the box in 3D space.

set_angles
set_angles(angles)

Set the lattice angles, preserving current edge lengths.

Parameters:

Name Type Description Default
angles ndarray

New angles [alpha, beta, gamma] in degrees, shape (3,).

required
set_lengths
set_lengths(lengths)

Set the lattice vector magnitudes, preserving current angles.

Parameters:

Name Type Description Default
lengths ndarray

New edge lengths [a, b, c] in Angstroms, shape (3,).

required
set_lengths_angles
set_lengths_angles(lengths, angles)

Set both edge lengths and lattice angles simultaneously.

Parameters:

Name Type Description Default
lengths ndarray

Edge lengths [a, b, c] in Angstroms, shape (3,).

required
angles ndarray

Angles [alpha, beta, gamma] in degrees, shape (3,).

required
set_lengths_tilts
set_lengths_tilts(lengths, tilts)

Set edge lengths and tilt factors simultaneously.

Parameters:

Name Type Description Default
lengths ndarray

Diagonal edge lengths [lx, ly, lz] in Angstroms, shape (3,).

required
tilts ndarray

Off-diagonal tilt factors [xy, xz, yz] in Angstroms, shape (3,).

required
set_matrix
set_matrix(matrix)

Replace the box matrix directly.

Parameters:

Name Type Description Default
matrix ndarray

New 3x3 upper-triangular box matrix, shape (3, 3).

required
to_dict
to_dict()

Convert the box to a dictionary representation.

Returns:

Name Type Description
dict dict

A dictionary containing the box properties.

to_lengths_angles
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(transformation_matrix)

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
tric(lengths, tilts, pbc=np.ones(3, dtype=bool), origin=np.zeros(3), central=False)

Create a triclinic box from edge lengths and tilt factors.

Parameters:

Name Type Description Default
lengths ArrayLike

Diagonal edge lengths [lx, ly, lz] in Angstroms, shape (3,).

required
tilts ArrayLike

Off-diagonal tilt factors [xy, xz, yz] in Angstroms, shape (3,).

required
pbc ArrayLike

Periodic boundary flags per axis, shape (3,).

ones(3, dtype=bool)
origin ArrayLike

Cartesian origin of the box in Angstroms, shape (3,).

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 Box instance.

unwrap
unwrap(xyz, image)

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(xyz)

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 (N, 3) or (3,).

required

Returns:

Type Description
ndarray

np.ndarray: Wrapped coordinates with the same shape as the input, in Angstroms.

wrap_free
wrap_free(xyz)

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_orthogonal(xyz)

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_triclinic(xyz)

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

AngleStyle(name, *args, **kwargs)

Bases: Style

Style for angle interactions (e.g. "harmonic").

def_type
def_type(itom, jtom, ktom, name='', **kwargs)

Define angle type

Parameters:

Name Type Description Default
itom AtomType

First atom type

required
jtom AtomType

Central atom type

required
ktom AtomType

Third atom type

required
name str

Optional name (defaults to itom-jtom-ktom)

''
**kwargs Any

Angle parameters (e.g. k, theta0, etc.)

{}
to_potential
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

AngleType(name, itom, jtom, ktom, **kwargs)

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. k in kcal/(mol*rad^2), theta0 in radians).

{}
matches
matches(at1, at2, at3)

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

True if the triple matches this angle type.

AtomStyle

AtomStyle(name, *args, **kwargs)

Bases: Style

Style for atom types (e.g. "full", "charge").

def_type
def_type(name, **kwargs)

Define atom type.

Parameters:

Name Type Description Default
name str

Name for the atom type.

required
**kwargs Any

Other parameters (element, mass, etc.).

{}

Returns:

Name Type Description
AtomType AtomType

Created AtomType instance.

AtomType

AtomType(name, *args, **kwargs)

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

AtomisticForcefield(name='', units='real')

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
def_anglestyle(name, *args, **kwargs)

Create and register an AngleStyle.

Parameters:

Name Type Description Default
name str

Name of the angle style (e.g. "harmonic").

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
def_atomstyle(name, *args, **kwargs)

Create and register an AtomStyle.

Parameters:

Name Type Description Default
name str

Name of the atom style (e.g. "full").

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
def_bondstyle(name, *args, **kwargs)

Create and register a BondStyle.

Parameters:

Name Type Description Default
name str

Name of the bond style (e.g. "harmonic").

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
def_dihedralstyle(name, *args, **kwargs)

Create and register a DihedralStyle.

Parameters:

Name Type Description Default
name str

Name of the dihedral style (e.g. "opls").

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
def_improperstyle(name, *args, **kwargs)

Create and register an ImproperStyle.

Parameters:

Name Type Description Default
name str

Name of the improper style (e.g. "cvff").

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
def_pairstyle(name, *args, **kwargs)

Create and register a PairStyle.

Parameters:

Name Type Description Default
name str

Name of the pair style (e.g. "lj/cut").

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
get_angletypes()

Return all AngleType instances across all registered styles.

Returns:

Type Description
list[AngleType]

Deduplicated list of AngleType instances.

get_atomtypes
get_atomtypes()

Return all AtomType instances across all registered styles.

Returns:

Type Description
list[AtomType]

Deduplicated list of AtomType instances.

get_bondtypes
get_bondtypes()

Return all BondType instances across all registered styles.

Returns:

Type Description
list[BondType]

Deduplicated list of BondType instances.

BondStyle

BondStyle(name, *args, **kwargs)

Bases: Style

Style for bond interactions (e.g. "harmonic").

def_type
def_type(itom, jtom, name='', **kwargs)

Define bond type

Parameters:

Name Type Description Default
itom AtomType

First atom type

required
jtom AtomType

Second atom type

required
name str

Optional name (defaults to itom-jtom)

''
**kwargs Any

Bond parameters (e.g. k, r0, etc.)

{}
to_potential
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

BondType(name, itom, jtom, **kwargs)

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. k in kcal/(mol*A^2), r0 in Angstrom).

{}
matches
matches(at1, at2)

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

True if the pair matches this bond type.

DihedralStyle

DihedralStyle(name, *args, **kwargs)

Bases: Style

Style for dihedral (torsion) interactions (e.g. "opls").

def_type
def_type(itom, jtom, ktom, ltom, name='', **kwargs)

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

DihedralType(name, itom, jtom, ktom, ltom, **kwargs)

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. k in kcal/mol, d sign factor, n multiplicity).

{}
matches
matches(at1, at2, at3, at4)

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

True if the quadruple matches this dihedral type.

ForceField

ForceField(name='', units='real')

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. "real", "metal", "lj").

Initialise a force field.

Parameters:

Name Type Description Default
name str

Name of the force field (e.g. "OPLS-AA").

''
units str

Unit convention for parameter values. Defaults to "real" (kcal/mol, Angstrom).

'real'
def_style
def_style(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_style_by_name(name, style_class=Style)

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
get_styles(style_class)

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. BondStyle).

required

Returns:

Type Description
List[S]

List of matching Style instances.

get_types
get_types(type_class)

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. AtomType).

required

Returns:

Type Description
list[Ty]

Deduplicated list of matching Type instances across all styles.

merge
merge(other)

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_style(style_class, name)

Remove a Style instance of style_class whose name matches.

Returns True if a style was removed.

remove_type
remove_type(style_class, name)

Remove every Type named name from styles of style_class.

Returns the number of Types removed.

rename_type
rename_type(style_class, old, new)

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
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

ImproperStyle(name, *args, **kwargs)

Bases: Style

Style for improper dihedral interactions (e.g. "cvff").

def_type
def_type(itom, jtom, ktom, ltom, name='', **kwargs)

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

ImproperType(name, itom, jtom, ktom, ltom, **kwargs)

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. k in kcal/mol, d sign factor, n multiplicity).

{}
matches
matches(at1, at2, at3, at4)

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

True if the quadruple matches this improper type exactly.

PairStyle

PairStyle(name, *args, **kwargs)

Bases: Style

Style for non-bonded pair interactions (e.g. "lj/cut").

def_type
def_type(itom, jtom=None, name='', **kwargs)

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.)

{}
to_potential
to_potential()

Create corresponding Potential instance from PairStyle.

Returns:

Name Type Description
Potential Potential

Potential instance containing all PairType parameters.

Raises:

Type Description
ValueError

If corresponding Potential class not found or missing required parameters

PairType

PairType(name, *atom_types, **kwargs)

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 AtomType instances. A single type implies a self-interaction.

()
**kwargs Any

Pair parameters (e.g. epsilon in kcal/mol, sigma in Angstrom).

{}

Raises:

Type Description
ValueError

If not exactly 1 or 2 atom types are provided.

matches
matches(at1, at2=None)

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

True if the pair matches this pair type.

Parameters

Parameters(*args, **kwargs)

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

Style(name, *args, **kwargs)

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. "harmonic", "lj/cut").

required
*args Any

Additional positional parameters forwarded to Parameters.

()
**kwargs Any

Keyword parameters forwarded to Parameters.

{}
copy
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_type_by_name(name, type_class=Type)

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_types(type_class)

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(other)

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

Type(name, *args, **kwargs)

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. "opls_135").

required
*args Any

Additional positional parameters forwarded to Parameters.

()
**kwargs Any

Keyword parameters forwarded to Parameters (e.g. mass=12.011, charge=-0.18).

{}
name property
name

The unique name identifying this type.

copy
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
get(key, default=None)

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.

None

Returns:

Type Description
Any

The parameter value if present, otherwise default.

TypeBucket

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(item)

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 type(item).

required
bucket
bucket(cls)

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 k where issubclass(k, cls) is True are included.

required

Returns:

Type Description
List[T]

A flat list of matching items (order is not guaranteed).

classes
classes()

Iterate over the distinct runtime types that have been stored.

Returns:

Type Description
Iterator[type[T]]

An iterator of type objects representing all buckets that

Iterator[type[T]]

contain at least one item.

remove
remove(item)

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

get_nearest_type(item)

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 type of item.

Frame

frame

Block

Block(vars_=None)

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])

nrows property
nrows

Return the number of rows in the first variable (if any).

shape property
shape

Return the shape of the first variable (if any).

copy
copy()

Shallow copy (arrays are not copied).

from_csv classmethod
from_csv(filepath, *, delimiter=',', encoding='utf-8', header=None, **kwargs)

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

from_dict classmethod
from_dict(data)

Inverse of :meth:to_dict.

iterrows
iterrows(n=None)

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
itertuples(index=True, name='Row')

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(old_key, new_key)

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(key, *, reverse=False)

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_(key, *, reverse=False)

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
to_dict
to_dict()

Return a JSON-serialisable copy (arrays -> Python lists).

Frame

Frame(blocks=None, **props)

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
blocks

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:

>>> frame = Frame(blocks={"atoms": {"x": [1]}, "bonds": {"atomi": [0]}})
>>> [b for b in frame.blocks]
[Block(x: shape=(1,), atomi: shape=(1,))]
copy
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:

>>> frame = Frame(blocks={"atoms": {"x": [1, 2, 3]}}, timestep=0)
>>> frame_copy = frame.copy()
>>> frame_copy.metadata["timestep"] = 1
>>> frame.metadata["timestep"]  # Original unchanged
0
from_dict classmethod
from_dict(data)

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:

>>> data = {
...     "blocks": {"atoms": {"x": [1, 2, 3]}},
...     "metadata": {"timestep": 0}
... }
>>> frame = Frame.from_dict(data)
>>> frame["atoms"]["x"]
array([1, 2, 3])
>>> frame.metadata["timestep"]
0
to_dict
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:

>>> frame = Frame(blocks={"atoms": {"x": [1, 2]}}, timestep=0)
>>> data = frame.to_dict()
>>> "blocks" in data
True
>>> "metadata" in data
True

Topology

topology

Molecular topology graph using igraph.

Provides graph-based representation of molecular connectivity with automated detection of angles, dihedrals, and impropers.

Topology

Topology(*args, entity_to_idx=None, idx_to_entity=None, **kwargs)

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.

{}
angles property
angles

Array of unique angle triplets (N×3), deduplicated.

atoms property
atoms

Array of atom indices.

bonds property
bonds

Array of bond pairs (N×2).

dihedrals property
dihedrals

Array of unique proper dihedral quartets (N×4), deduplicated.

improper property
improper

Array of unique improper dihedral quartets (N×4).

n_angles property
n_angles

Number of unique angles (i-j-k triplets).

n_atoms property
n_atoms

Number of atoms (vertices).

n_bonds property
n_bonds

Number of bonds (edges).

n_dihedrals property
n_dihedrals

Number of unique proper dihedrals (i-j-k-l quartets).

add_angle
add_angle(idx_i, idx_j, idx_k, **props)

Add angle by ensuring bonds i-j and j-k exist.

add_angles
add_angles(angle_idx)

Add multiple angles from array of triplets.

add_atom
add_atom(name, **props)

Add a single atom vertex.

add_atoms
add_atoms(n_atoms, **props)

Add multiple atom vertices.

add_bond
add_bond(idx_i, idx_j, **props)

Add bond between atoms i and j if not already connected.

add_bonds
add_bonds(bond_idx, **props)

Add multiple bonds from array of pairs.

delete_atom
delete_atom(index)

Delete atom(s) by index.

delete_bond
delete_bond(index)

Delete bond(s) by index.

union
union(other)

Merge another topology into this one.

Trajectory

trajectory

CustomStrategy

CustomStrategy(split_func)

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(trajectory)

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

FrameIntervalStrategy(interval)

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(trajectory)

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_indices(trajectory)

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

TimeIntervalStrategy(interval)

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(trajectory)

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

Trajectory(frames, topology=None)

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:

>>> traj_slice = traj[0:5]  # First 5 frames
>>> len(traj_slice)
5

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
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:

>>> traj1 = Trajectory([Frame(), Frame()])
>>> traj1.has_length()
True
>>> traj2 = Trajectory((f for f in [Frame(), Frame()]))
>>> traj2.has_length()
False
map
map(func)

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

TrajectorySplitter(trajectory)

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(strategy)

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:

>>> traj = Trajectory([Frame() for _ in range(20)])
>>> strategy = FrameIntervalStrategy(interval=5)
>>> splitter = TrajectorySplitter(traj)
>>> segments = splitter.split(strategy)
>>> len(segments)
4
split_frames
split_frames(interval)

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:

>>> traj = Trajectory([Frame() for _ in range(20)])
>>> splitter = TrajectorySplitter(traj)
>>> segments = splitter.split_frames(interval=5)
>>> len(segments)
4
split_time
split_time(interval)

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:

>>> frames = [Frame() for _ in range(10)]
>>> for i, frame in enumerate(frames):
...     frame.metadata["time"] = i * 0.1
>>> traj = Trajectory(frames)
>>> splitter = TrajectorySplitter(traj)
>>> segments = splitter.split_time(interval=0.5)

Coarse-Grain

cg

Bead

Bead(data_dict=None, /, atomistic=None, **attrs)

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

CGBond(a, b, /, **attrs)

Bases: Link

Coarse-grained bond connecting two beads.

ibead property
ibead

First bead endpoint.

jbead property
jbead

Second bead endpoint.

CoarseGrain

CoarseGrain(**props)

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.

beads property
beads

Collection of all beads in the structure.

cgbonds property
cgbonds

Collection of all CG bonds in the structure.

add_bead
add_bead(bead)

Add an existing Bead object to the structure.

add_beads
add_beads(beads)

Add multiple existing Bead objects to the structure.

add_cgbond
add_cgbond(bond)

Add an existing CGBond object to the structure.

add_cgbonds
add_cgbonds(bonds)

Add multiple existing CGBond objects to the structure.

align
align(a, b, *, a_dir=None, b_dir=None, flip=False, entity_type=Bead)

Align beads. Returns self for chaining.

def_bead
def_bead(atomistic=None, **attrs)

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_beads
def_beads(beads_data)

Create multiple Beads from a list of attribute dictionaries.

def_cgbond
def_cgbond(a, b, /, **attrs)

Create a new CGBond between two beads and add it to the structure.

def_cgbonds
def_cgbonds(bonds_data)

Create multiple CGBonds from a list of (ibead, jbead) or (ibead, jbead, attrs) tuples.

del_bead
del_bead(*beads)

Remove beads and all their incident CG bonds.

del_cgbond
del_cgbond(*bonds)

Remove CG bonds from the structure.

from_atomistic classmethod
from_atomistic(atomistic, bead_mask)

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

Example

atomistic = Atomistic()

... create atoms and bonds ...
Group atoms: [0,1,2] -> bead 0, [3,4] -> bead 1

mask = np.array([0, 0, 0, 1, 1]) cg = CoarseGrain.from_atomistic(atomistic, mask)

move
move(delta, *, entity_type=Bead)

Move all beads by delta. Returns self for chaining.

rename_type
rename_type(old, new, *, kind=Bead)

Rename all beads/bonds of kind whose type attribute equals old.

Returns the number of items updated.

replicate
replicate(n, transform=None)

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(axis, angle, about=None, *, entity_type=Bead)

Rotate beads around axis. Returns self for chaining.

scale
scale(factor, about=None, *, entity_type=Bead)

Scale beads by factor. Returns self for chaining.

select
select(predicate)

Return a new CoarseGrain containing only beads matching predicate.

Bonds whose endpoints are fully inside the selection are carried over.

set_property
set_property(selector, key, value, *, kind=Bead)

Set a property on every bead (or link) matching the callable selector.

to_atomistic
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 module-attribute

config = instance()

Global config instance. Use this for read access.

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
instance()

Get the singleton Config instance.

Thread-safe lazy initialization. Creates instance on first call.

Returns:

Type Description
Self

The singleton Config instance

Examples:

>>> cfg = Config.instance()
>>> print(cfg.log_level)
'INFO'
reset classmethod
reset()

Reset configuration to default values.

Thread-safe reset. Creates a new instance with all default values.

Examples:

>>> Config.update(n_threads=8)
>>> Config.reset()
>>> print(Config.instance().n_threads)
1
temporary classmethod
temporary(**overrides)

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:

>>> original_level = Config.instance().log_level
>>> with Config.temporary(log_level='DEBUG'):
...     print(Config.instance().log_level)  # 'DEBUG'
>>> print(Config.instance().log_level)  # original_level
update classmethod
update(**kwargs)

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:

>>> Config.update(log_level='DEBUG', n_threads=4)
>>> cfg = Config.instance()
>>> print(cfg.n_threads)
4

get_config

get_config()

Get the global configuration instance.

Convenience function equivalent to Config.instance().

Returns:

Type Description
Config

The singleton Config instance

Examples:

>>> cfg = get_config()
>>> print(cfg.log_level)
'INFO'

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

Script(name, language='bash', description=None, _lines=list(), path=None, url=None, tags=set())

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
lines

Get a copy of all script lines.

Returns:

Type Description
list[str]

Copy of internal lines list

text property
text

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(line='')

Append a single line to the end of the script.

Parameters:

Name Type Description Default
line str

Line content to append

''
append_block
append_block(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
clear
clear()

Remove all lines from the script.

delete
delete(index)

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_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
extend(lines)

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
format(**kwargs)

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
format_with_mapping(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
from_path(path, *, language=None, description=None)

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
from_text(name, text, *, language='bash', description=None, path=None, url=None)

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
from_url(url, *, name=None, language='other', description=None)

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(index, line)

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(new_path)

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
preview(max_lines=20, *, with_line_numbers=True)

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()

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(new_name)

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(index, line)

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(path=None)

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