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; mirrors Atomistic 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, Graph

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=None, origin=None)

Bases: Box

Simulation box — molpy front for the molrs spatial primitive.

Inherits molrs.Box directly, so a molpy.Box instance is accepted by every molrs API (NeighborQuery, RDF, wrap, isin, …) without conversion. molpy adds:

  • the Style enum (FREE / ORTHOGONAL / TRICLINIC),
  • molpy-style accessors (lx, ly, lz, xy, xz, yz, a, b, c, lengths, angles, tilts, bounds, xlo/xhi/…),
  • convenience factories (cubic, orth, tric, from_lengths_angles, from_bounds, from_box),
  • PBC-aware geometry helpers (wrap, unwrap, diff, dist, make_fractional, make_absolute, get_distance_between_faces, get_images).

Immutable. State lives in the molrs base; per-axis setters and set_* methods were removed in this refactor (use one of the classmethod factories to construct a new Box instead). This matches molpy's own coding-style.md "avoid mutation" rule.

Parameters:

Name Type Description Default
matrix ArrayLike | None

A (3, 3) upper-triangular box matrix (lattice vectors as columns). None or an all-zero matrix produces a FREE (non-periodic) box. A (3,) array is promoted to a diagonal matrix.

None
pbc ArrayLike | None

Boolean periodic-boundary flags per axis, shape (3,). Defaults to [True, True, True].

None
origin ArrayLike | None

Cartesian origin in Angstroms, shape (3,). Defaults to [0, 0, 0].

None
angles property
angles

Lattice angles [alpha, beta, gamma] in degrees.

is_free property
is_free

True if this box is FREE (no periodicity, zero volume).

lengths property
lengths

Lattice vector magnitudes [a, b, c] in Angstroms.

Returns zeros for FREE.

matrix property
matrix

Box matrix with lattice vectors as columns, shape (3, 3).

style property
style

FREE / ORTHOGONAL / TRICLINIC depending on the matrix shape.

volume property
volume

Box volume in Angstroms³ (zero for FREE).

Style

Bases: Enum

Enumeration of simulation-box geometries.

cubic classmethod
cubic(length, pbc=None, origin=None, central=False)

Cubic box with three equal edge lengths.

from_bounds classmethod
from_bounds(points, padding=0.0, pbc=None)

Tight orthogonal box around a point cloud (non-periodic by default).

from_box classmethod
from_box(box)

Copy constructor.

from_lengths_angles classmethod
from_lengths_angles(lengths, angles)

Triclinic box from edge lengths and lattice angles (degrees).

general2restrict staticmethod
general2restrict(matrix)

General → restricted-triclinic conversion (LAMMPS convention).

orth classmethod
orth(lengths, pbc=None, origin=None, central=False)

Orthogonal (axis-aligned cuboid) box.

plot
plot()

Placeholder for 3D box visualization.

to_lengths_angles
to_lengths_angles()

Return (lengths, angles); angles in degrees.

tric classmethod
tric(lengths, tilts, pbc=None, origin=None, central=False)

Triclinic box from edge lengths and tilt factors.

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: Block, MutableMapping[str, ndarray]

Lightweight container that maps variable names -> NumPy arrays.

Inherits molrs.Block directly, so a molpy.Block IS-A molrs.Block and is accepted by every molrs.* API that takes a block (Frame.__setitem__, IO writers, …) with no conversion. All numeric / bool / string-list columns live in the Rust Store; object-dtype columns (e.g. element symbols stored as np.array(..., dtype=object)) live on the Python side in self._objects — they have no Rust representation.

• 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 (0 if empty).

shape property
shape

Return the shape (nrows, ncols) of the block.

copy
copy()

Deep copy (data is copied into a new Rust Store).

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)

Create a Block from a dict or alias a molrs.Block.

When data is already a cls instance, it is returned as-is. When data is a bare molrs.Block, the returned block aliases it: numeric read/write operations route through data (so this is a live view of data's storage — useful for the frame[key][col] = arr write-through idiom).

iterrows
iterrows(n=None)

Iterate over rows of the block.

Returns

Iterator[tuple[int, dict[str, Any]]] An iterator yielding (index, row_data) pairs.

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

keys
keys()

All column names (Rust slot + Python-side object columns).

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.

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.

to_dict
to_dict()

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

Frame

Frame(blocks=None, **props)

Bases: Frame

Hierarchical numerical data container with named blocks.

Inherits molrs.Frame directly: a molpy.Frame IS-A molrs.Frame and is accepted by every molrs.* API that takes a frame, with no conversion bridge.

Python-only state lives on the subclass __dict__:

  • metadata: dict[str, Any] — molpy-side annotations (timestep, description, …) invisible to the Rust slot.
  • _block_objects: dict[str, dict[str, np.ndarray]] — per-block cache of object-dtype columns (string arrays etc.) that have no Rust representation; reattached on __getitem__.

The box getter still upgrades molrs.Box → molpy.Box so callers keep molpy's enriched Box API (factories, lengths/angles, PBC helpers).

Parameters:

Name Type Description Default
blocks dict[str, Block | dict] | None

Initial blocks.

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'
blocks property
blocks

Iterate over stored Block objects.

box property writable
box

The simulation Box (FREE box when unset).

copy
copy()

Create a deep copy of the Frame.

Returns:

Name Type Description
Frame Frame

A new Frame with copied blocks and metadata.

from_dict classmethod
from_dict(data)

Create a Frame from a dict or upgrade a molrs.Frame.

When data is already a cls instance it is returned as-is. When data is a bare molrs.Frame, each block is copied into a fresh cls instance; meta (if any) flows into metadata.

keys
keys()

Return block names.

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.

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

Coarse-grained molecular structure.

Mirrors :mod:molpy.core.atomistic in shape and contract; see :doc:../specs/cg-atomistic-mapping-redesign for the design rationale.

Conventional dict keys (none enforced):

  • bead["atoms"] — tuple[Atom, ...] of atom references this bead represents (when projected from an :class:Atomistic). Required only by :meth:CoarseGrain.beads_of.
  • bead["x"], bead["y"], bead["z"] — primary position; consumed by :class:SpatialMixin for move / rotate / scale / align.
  • bead["type"], bead["mass"], bead["charge"] — as needed.

Bead

Bases: Entity

Coarse-grained bead.

Structurally identical to :class:~molpy.core.atomistic.Atom: a dict-like :class:Entity with no mandatory fields. All bead state lives in the underlying dict.

See module docstring for the optional convention keys recognised by :class:CoarseGrain and the spatial mixin.

CGBond

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

Bases: Link

Coarse-grained bond between two beads.

Parallel to :class:~molpy.core.atomistic.Bond: a :class:Link carrying two :class:Bead endpoints plus arbitrary attributes.

Initialise a CG bond between two beads.

Parameters:

Name Type Description Default
a Bead

First bead endpoint.

required
b Bead

Second bead endpoint.

required
**attrs Any

Additional bond attributes.

{}

Raises:

Type Description
AssertionError

If a or b is not a :class:Bead instance.

ibead property
ibead

First bead endpoint.

jbead property
jbead

Second bead endpoint.

CoarseGrain

CoarseGrain(**props)

Bases: Struct, MembershipMixin, SpatialMixin, ConnectivityMixin, Graph

Coarse-grained molecular structure.

Public surface mirrors :class:~molpy.core.atomistic.Atomistic 1:1 except for the single extra method :meth:beads_of. The class makes no assumption about the existence, source, or definition of bead positions, masses, or atom-level provenance — those are dict-key conventions documented at module level.

Initialise an empty coarse-grained structure.

Registers buckets for :class:Bead and :class:CGBond. If the concrete subclass defines a __post_init__ method, it is called with the same keyword arguments (template pattern, parallel to :class:Atomistic).

Parameters:

Name Type Description Default
**props Any

Arbitrary properties stored on the structure (e.g., name="POPC", model="martini3").

{}
beads property
beads

All beads registered in this structure.

cgbonds property
cgbonds

All CG bonds registered in this structure.

add_bead
add_bead(bead)

Register an existing :class:Bead.

Parameters:

Name Type Description Default
bead Bead

The bead to register.

required

Returns:

Type Description
Bead

The same bead, after registration.

add_beads
add_beads(beads)

Register multiple existing beads.

Parameters:

Name Type Description Default
beads list[Bead]

List of :class:Bead instances to register.

required

Returns:

Type Description
list[Bead]

The same list, after registration.

add_cgbond
add_cgbond(bond)

Register an existing :class:CGBond.

Parameters:

Name Type Description Default
bond CGBond

The CG bond to register.

required

Returns:

Type Description
CGBond

The same bond, after registration.

add_cgbonds
add_cgbonds(bonds)

Register multiple existing CG bonds.

Parameters:

Name Type Description Default
bonds list[CGBond]

List of :class:CGBond instances to register.

required

Returns:

Type Description
list[CGBond]

The same list, after registration.

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

Align beads via a vector pair.

Parameters:

Name Type Description Default
a Entity

Source entity defining the start of the alignment vector.

required
b Entity

Target entity defining the end of the alignment vector.

required
a_dir list[float] | None

Optional source direction [x, y, z]; if omitted, the vector from a to b is used.

None
b_dir list[float] | None

Optional target direction [x, y, z].

None
flip bool

If True, reverse the alignment direction.

False
entity_type type[Entity]

Entity subclass to transform (default :class:Bead).

Bead

Returns:

Type Description
'CoarseGrain'

self for method chaining.

beads_of
beads_of(atom)

Return all beads whose bead["atoms"] contains atom.

Justified as a core method by the same standard as :meth:move: operates on a single conventional key ("atoms") and has no second reasonable implementation. Beads without an "atoms" key are skipped silently.

Parameters:

Name Type Description Default
atom 'Atom'

The atom to look up.

required

Returns:

Type Description
Bead

Tuple of beads referencing atom. Empty if none; multiple

...

if the mapping has overlap.

Note

O(N_beads × ⟨|atoms|⟩); no caching. Callers needing speed should build their own id(atom) → list[Bead] index.

def_bead
def_bead(**attrs)

Create a new :class:Bead and register it.

Parameters:

Name Type Description Default
**attrs Any

Bead attributes (any keys; see module docstring for conventional keys).

{}

Returns:

Type Description
Bead

The newly registered Bead.

def_beads
def_beads(beads_data)

Create multiple beads from a list of attribute dicts.

Parameters:

Name Type Description Default
beads_data list[dict[str, Any]]

List of attribute dicts; each dict is forwarded as **attrs to :meth:def_bead.

required

Returns:

Type Description
list[Bead]

List of newly registered beads, one per input dict.

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

Create a new :class:CGBond between two beads and register it.

Parameters:

Name Type Description Default
a Bead

First bead endpoint.

required
b Bead

Second bead endpoint.

required
**attrs Any

Additional bond attributes (e.g., type="A-B").

{}

Returns:

Type Description
CGBond

The newly registered CG bond.

def_cgbonds
def_cgbonds(bonds_data)

Create multiple CG bonds from (a, b) or (a, b, attrs) tuples.

Parameters:

Name Type Description Default
bonds_data list[tuple[Bead, Bead] | tuple[Bead, Bead, dict[str, Any]]]

Iterable of bond specifications. Each item is either a 2-tuple (a, b) of bead endpoints or a 3-tuple (a, b, attrs) where attrs is a dict forwarded as **attrs to :meth:def_cgbond.

required

Returns:

Type Description
list[CGBond]

List of newly registered CG bonds, one per input tuple.

del_bead
del_bead(*beads)

Remove beads (and their incident CG bonds).

Parameters:

Name Type Description Default
*beads Bead

One or more :class:Bead instances to remove. Each bead is unregistered along with any :class:CGBond that references it as an endpoint.

()
del_cgbond
del_cgbond(*bonds)

Remove CG bonds.

Parameters:

Name Type Description Default
*bonds CGBond

One or more :class:CGBond instances to remove.

()
move
move(delta, *, entity_type=Bead)

Translate every bead by delta.

Parameters:

Name Type Description Default
delta list[float]

Translation vector [dx, dy, dz] in Angstroms.

required
entity_type type[Entity]

Entity subclass to translate (default :class:Bead).

Bead

Returns:

Type Description
'CoarseGrain'

self for method chaining.

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

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

Returns:

Type Description
int

Number of items renamed.

replicate
replicate(n, transform=None)

Replicate self n times into a new structure.

Parameters:

Name Type Description Default
n int

Number of copies.

required
transform Callable[['CoarseGrain', int], None] | None

Optional callable (copy, index) -> None applied to each replica before merging.

None

Returns:

Type Description
'CoarseGrain'

A new :class:CoarseGrain containing n merged replicas.

rotate
rotate(axis, angle, about=None, *, entity_type=Bead)

Rotate beads around axis by angle.

Parameters:

Name Type Description Default
axis list[float]

Rotation axis [ax, ay, az] (need not be unit length).

required
angle float

Rotation angle in radians.

required
about list[float] | None

Optional pivot point [x, y, z] in Angstroms; defaults to the origin.

None
entity_type type[Entity]

Entity subclass to rotate (default :class:Bead).

Bead

Returns:

Type Description
'CoarseGrain'

self for method chaining.

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

Scale bead positions by factor.

Parameters:

Name Type Description Default
factor float

Uniform scaling factor (dimensionless).

required
about list[float] | None

Optional pivot point [x, y, z] in Angstroms; defaults to the origin.

None
entity_type type[Entity]

Entity subclass to scale (default :class:Bead).

Bead

Returns:

Type Description
'CoarseGrain'

self for method chaining.

select
select(predicate)

Return a new CoarseGrain containing beads matching predicate.

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

Parameters:

Name Type Description Default
predicate Callable[[Bead], bool]

Callable (bead) -> bool selecting beads to keep.

required

Returns:

Type Description
'CoarseGrain'

A new :class:CoarseGrain containing the selected beads and the

'CoarseGrain'

bonds whose endpoints are entirely within the selection.

Raises:

Type Description
TypeError

If predicate is not callable.

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

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

Parameters:

Name Type Description Default
selector Callable[[Bead], bool]

Callable (item) -> bool returning True for items whose key should be set.

required
key str

Attribute key to assign on matching items.

required
value Any

Value to assign.

required
kind type

Item class to iterate over (default :class:Bead); pass a :class:Link subclass to operate on bonds instead.

Bead

Returns:

Type Description
int

Number of items modified.

Raises:

Type Description
TypeError

If selector is not callable.

to_frame
to_frame(bead_fields=None)

Convert this CoarseGrain into a :class:Frame.

Mirrors :meth:molpy.core.atomistic.Atomistic.to_frame. Beads are flattened into a "beads" :class:Block (struct-of-arrays); CG bonds, when present, become a "cgbonds" block carrying integer endpoint indices ibead / jbead plus any remaining bond attributes.

Parameters:

Name Type Description Default
bead_fields list[str] | None

Optional whitelist of bead dict keys to extract. If None, every key encountered on any bead is included. Note: a bead may carry a "atoms" convention key whose value is a tuple of :class:Atom references; including that key produces an object-dtype column. Pass an explicit whitelist to skip it when writing to numerical formats.

None

Returns:

Name Type Description
A 'Frame'

class:Frame with a "beads" block and (if any CG bonds

'Frame'

exist) a "cgbonds" block. The frame carries no

'Frame'

class:Box; callers attach one as needed.

Raises:

Type Description
ValueError

If a CG bond references a bead that is not registered in this 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