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 Blocks + box + exact-dtype MetaValue entries 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
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)
ForceField Force field container (styles → types → potentials) Defining parameters before execution Direct numerical computation
Entity / Link Base classes for graph nodes / edges (atoms are Entities, bonds are Links) Custom graph element types Everyday atom / bond editing
Region Geometric region (box, sphere, boolean combinations) Spatial selection, packing constraints Non-geometric masks (use a Selector)
UnitSystem LAMMPS-style unit-system registry (real, metal, …) Unit conversions and custom presets Unit-agnostic array math

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.ForceField(name="demo", units="real")
style = ff.def_atomstyle("full")
ct = style.def_type("CT", mass=12.011)

Full API

Atomistic

atomistic

All-atom molecular structure as a handle-view over a molrs Atomistic.

Atomistic(_GraphViews, molrs.Atomistic) IS a molrs world — it is accepted directly by every molrs.* system free function (no .to_molrs() bridge). :class:Atom / :class:Bond / :class:Angle / :class:Dihedral / :class:Improper are handle views interned per stable handle.

Atomistic

Atomistic(**props)

Bases: Atomistic, _GraphViews

All-atom molecular structure backed by a molrs Atomistic world.

Note on base order: the pyo3 native molrs.Atomistic must be the first base so the extension instance layout is initialised correctly (a pyo3 extends class cannot sit behind a plain-Python base). _GraphViews contributes only non-conflicting helpers, and the leaf's own methods win in the MRO regardless of order, so this preserves the spec's intent.

symbols property
symbols

Element symbols for every atom (canonical :data:~molpy.core.fields.ELEMENT).

adopt staticmethod
adopt(graph)

Zero-copy take ownership of a molrs-produced Atomistic graph.

Uses the molrs zero-copy adopt to move graph's storage into a fresh molpy Atomistic (graph is left empty). Views over the adopted nodes/relations are interned lazily on access.

copy
copy()

Independent deep copy. Handles are preserved (molrs clone).

from_frame classmethod
from_frame(frame)

Build a molpy Atomistic from a :class:molrs.Frame.

The inverse of :meth:to_frame. molrs' inherited from_frame returns a bare molrs graph; this override adopts it so the result is a molpy Atomistic — the call site never needs a second adopt.

get_topo
get_topo(
    entity_type=Atom,
    link_type=Bond,
    gen_angle=False,
    gen_dihe=False,
    clear_existing=False,
)

Return a copy with angle/dihedral relations perceived from the bonds.

Angle/dihedral perception (2-edge / 3-edge paths over the bond graph) is a molrs-native graph operation; this delegates to that Rust kernel on a copy. With no gen_* flags it is a plain copy. Always returns an :class:Atomistic (never a bare topology graph).

merge
merge(other)

Structural merge of other into self (molrs).

Every node of other is remapped to a fresh handle in self. other is emptied and must not be used afterwards. Cross-graph identity is handle-based — Python view objects are not rebound.

to_frame
to_frame(atom_fields=None)

Export to a tabular :class:Frame (atoms + bonds/angles/dihedrals/ impropers blocks).

Delegates straight to the molrs world's native to_frame: the Rust column store already holds every component as a dense, row-aligned column, so each block is materialized as numpy with zero Python-side conversion. atom_fields optionally restricts the atoms block columns.

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 defined cell, zero volume).

Derived from the molrs base's cell_defined flag — the single source of truth — not a Python-side shadow.

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: str, Enum

Enumeration of simulation-box geometries.

Values are the canonical molrs style strings so a molpy.Box.Style member compares equal to the string returned by molrs.Box.style (e.g. Box.Style.ORTHOGONAL == "orthogonal"), letting frame.box (a molrs box) interoperate with molpy style checks.

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 / upgrade constructor.

Accepts a molpy Box or a bare molrs.Box (e.g. frame.box), reading only the public matrix / pbc / origin accessors so it works across both. A free source box reconstructs a free molpy box.

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

Force-field model — thin re-export of the native molrs hierarchy.

molrs (the Rust extension) natively owns the entire force-field model: ForceField, the Style tree, the Type tree and Parameters. molpy no longer maintains a parallel Python hierarchy; this module simply re-exports the molrs classes and adds the handful of thin specialized Style subclasses that molrs does not ship a named class for (e.g. morse, class2, fourier, periodic variants).

A specialized style here carries no kernel — it only fixes the style name so callers can write ff.def_style(BondMorseStyle()) instead of ff.def_bondstyle("morse"). Energy/force evaluation lives entirely in molrs via ff.to_potentials().calc_energy(frame) / .calc_forces(frame).

AngleClass2BondAngleStyle

AngleClass2BondAngleStyle(ff=None, name='')

Bases: AngleStyle

Angle class2/ba cross term.

AngleClass2BondBondStyle

AngleClass2BondBondStyle(ff=None, name='')

Bases: AngleStyle

Angle class2/bb cross term.

AngleClass2Style

AngleClass2Style(ff=None, name='')

Bases: AngleStyle

Angle class2 style.

BondClass2Style

BondClass2Style(ff=None, name='')

Bases: BondStyle

Bond class2 style.

BondMorseStyle

BondMorseStyle(ff=None, name='')

Bases: BondStyle

Bond morse style (LAMMPS bond_style morse).

DihedralCharmmStyle

DihedralCharmmStyle(ff=None, name='')

Bases: DihedralStyle

Dihedral charmm style.

DihedralClass2Style

DihedralClass2Style(ff=None, name='')

Bases: DihedralStyle

Dihedral class2 style.

DihedralFourierStyle

DihedralFourierStyle(ff=None, name='')

Bases: DihedralStyle

Dihedral fourier style (AMBER multi-term).

DihedralMultiHarmonicStyle

DihedralMultiHarmonicStyle(ff=None, name='')

Bases: DihedralStyle

Dihedral multi/harmonic style.

DihedralPeriodicStyle

DihedralPeriodicStyle(ff=None, name='')

Bases: DihedralStyle

Dihedral periodic (CHARMM-style charmm/periodic) style.

ForceField

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

Bases: ForceField

A molrs force field with the chainable, object-style builder layer.

Subclasses the Rust :class:molrs.ForceField (inheriting def_type / types / to_potentials) and adds def_*style factories that return chainable :class:Style handles plus style/type query helpers.

def_style
def_style(style)

Register style (an unbound :class:Style, e.g. BondHarmonicStyle()) and return a bound handle of the same class.

get_styles
get_styles(category_or_cls)

Styles of a category (str) or by :class:Style subclass.

get_types
get_types(category_or_cls)

Types of a category (str) or by :class:Type subclass, across styles.

merge
merge(other)

Merge other's styles and types into this force field (in place).

rename_type
rename_type(style_cls, old, new)

Rename type old -> new across all styles of style_cls's category (molpy signature).

ImproperClass2Style

ImproperClass2Style(ff=None, name='')

Bases: ImproperStyle

Improper class2 style.

ImproperCvffStyle

ImproperCvffStyle(ff=None, name='')

Bases: ImproperStyle

Improper cvff style.

ImproperHarmonicStyle

ImproperHarmonicStyle(ff=None, name='')

Bases: ImproperStyle

Improper harmonic style.

ImproperPeriodicStyle

ImproperPeriodicStyle(ff=None, name='')

Bases: ImproperStyle

Improper periodic style.

PairBuckStyle

PairBuckStyle(ff=None, name='')

Bases: PairStyle

Pair buck (Buckingham) style.

PairCoulTTStyle

PairCoulTTStyle(ff=None, name='')

Bases: PairStyle

Pair coul/tt — Tang−Toennies damped charge−dipole Coulomb style.

Style-level parameters: b (1/Å, default 4.5), n (default 4), c (default 1.0). Per-atom-type parameter: charge (e). Damping: f_n(r) = 1 − c·exp(−b·r)·Σ_{k=0}^n (b·r)^k/k!.

Reference: Tang & Toennies, J. Chem. Phys. 80 (1984) 3726, :doi:10.1063/1.447150.

PairLJClass2Style

PairLJClass2Style(ff=None, name='')

Bases: PairStyle

Pair lj/class2 style.

PairMorseStyle

PairMorseStyle(ff=None, name='')

Bases: PairStyle

Pair morse style.

PairTholeStyle

PairTholeStyle(ff=None, name='')

Bases: PairStyle

Pair thole — Thole damped dipole-dipole / core-shell Coulomb style.

Per-atom-type parameters: charge (e), alpha (ų), a_thole (dimensionless Thole damping width, default 2.6). Damping: T(r) = 1 − (1 + s·r/2)·exp(−s·r) where s = a_ij / (α_i·α_j)^(1/6), a_ij = (a_i + a_j)/2.

Reference: Thole, Chem. Phys. 59 (1981) 341, :doi:10.1016/0301-0104(81)85176-2.

Parameters

Parameters(mapping)

The parameter view of a :class:Type — keyword access plus the .kwargs mapping consumers read. The model is keyword-only, so .args is always empty.

Style

Style(ff=None, name='')

Handle view of one style over a :class:ForceField.

Type

Type(ff, style, name)

Handle view of one force-field type over a :class:ForceField.

Frame and Block

Top-level exports — user code: import molpy as mp then mp.Frame / mp.Block. Autodoc uses the package name so mkdocstrings can resolve the re-exports:

Frame

Frame(blocks=None, meta=None)

Bases: Frame

Container of named :class:Block tables plus a box and metadata.

Inherits the PyO3 molrs.Frame: a rich Frame IS-A core frame, accepted by every molrs.* API with no conversion. __getitem__ upgrades the stored block to a rich :class:Block. The box is the native molrs.Box (inherited). Frame has no CSV methods — CSV belongs to Block.

blocks property

blocks

Iterate over the stored blocks (as rich Blocks).

copy

copy()

Deep copy (blocks copied into new storage; box + metadata copied).

from_dict classmethod

from_dict(data)

Build a Frame from a dict, or upgrade a bare molrs.Frame.

to_dict

to_dict()

Frame as {"blocks": {name: block.to_dict()}, "meta": {...}}.

Block

Block(vars_=None)

Bases: Block, MutableMapping[str, ndarray]

Tidy columnar table mapping name -> 1D/2D numpy column.

Inherits the PyO3 molrs.Block so a rich Block IS-A core block and is accepted by every molrs.* API with no conversion. All columns live in the Rust Store (numpy-representable dtypes only); reads are zero-copy views.

Behaves like a dict and supports advanced indexing: by key (column), by int/slice (row / sub-block), by boolean mask, by list of keys (2D array), and by any callable selector (key(self)).

nrows property

nrows

Number of rows (0 if empty).

shape property

shape

(nrows, ncols), or () when empty.

copy

copy()

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

from_csv classmethod

from_csv(
    source,
    *,
    delimiter=",",
    encoding="utf-8",
    header=None,
    skipinitialspace=False,
)

Create a Block from CSV.

The CSV grammar + per-column dtype inference (int → float → str) is implemented in the molrs Rust core; this wrapper only resolves source (text, a file path, or a StringIO) to text and adopts the parsed core block as a rich :class:Block.

Parameters:

Name Type Description Default
skipinitialspace bool

When True, runs of the delimiter are collapsed so whitespace-aligned columns (e.g. LAMMPS data sections) parse cleanly. The core also trims each field; combined, leading and repeated delimiters never produce spurious empty columns.

False

from_dict classmethod

from_dict(data)

Build a Block from a dict, or alias a bare molrs.Block.

An already-rich Block is returned as-is. A bare molrs.Block is aliased (the returned block routes reads/writes through it — a live view of its storage, used for the frame[key][col] = arr write-through).

iterrows

iterrows(n=None)

Yield (index, row_dict) for each row.

itertuples

itertuples(index=True, name='Row')

Yield a named tuple per row.

keys

keys()

All column names.

rename

rename(old_key, new_key)

Rename a column in place. Raises KeyError if old_key is absent.

sort

sort(key, *, reverse=False)

Return a new Block sorted by key (original unchanged).

The argsort + per-column gather runs in the Rust core (molrs.Block.sort); this is a thin call, not a NumPy reimplementation.

sort_

sort_(key, *, reverse=False)

Sort the block in place by key; returns self.

to_csv

to_csv(
    filepath=None,
    *,
    delimiter=",",
    header=True,
    encoding="utf-8",
)

Serialize the block to CSV (inverse of :meth:from_csv).

CSV serialization lives in the molrs Rust core; this wrapper only writes the produced text to filepath (returning None) or returns it as a string when filepath is None.

to_dict

to_dict()

Return each column as a numpy array (views into Rust memory).

Trajectory

Trajectory

Trajectory(frames, topology=None, step=None, time=None)

Bases: Trajectory

An eager sequence of molecular frames with an optional topology.

Subclasses :class:molrs.Trajectory: frame storage, len(), integer indexing, and the frames / step / time accessors all live in the Rust container. molpy adds an associated topology, slice indexing (returns a sub-:class:Trajectory), and :meth:map.

Frames must be :class:molrs.Frame objects — the Rust container copies each into its column store on construction. For lazy, seekable reading from disk use molrs.read_lammps_trajectory / read_xyz_trajectory, which return a lazy TrajectoryReader instead of materializing every frame.

Parameters:

Name Type Description Default
frames Iterable[Frame]

Sequence of :class:molrs.Frame objects.

required
topology Any | None

Optional connectivity/topology object carried alongside the frames (stored and passed through unchanged). Defaults to None.

None
step Any | None

Optional per-frame integer step indices (forwarded to molrs).

None
time Any | None

Optional per-frame simulation times (forwarded to molrs).

None

Examples:

>>> traj = Trajectory([frame0, frame1, frame2])
>>> len(traj)
3
>>> traj[0]            # integer index -> Frame
Frame(...)
>>> traj[0:2]          # slice -> sub-Trajectory
Trajectory(n_frames=2, topology=None)

topology property

topology

The topology object associated with this trajectory (or None).

map

map(func)

Apply func to every frame, returning a new trajectory.

Parameters:

Name Type Description Default
func Callable[[Frame], Frame]

A callable mapping a :class:Frame to a :class:Frame.

required

Returns:

Type Description
'Trajectory'

A new :class:Trajectory of the mapped frames, sharing this

'Trajectory'

trajectory's topology. The original is not modified.

Coarse-Grain

cg

Coarse-grained molecular structure as a handle-view over a molrs CoarseGrain.

Mirrors :mod:molpy.core.atomistic: CoarseGrain(_GraphViews, molrs.CoarseGrain) IS a molrs world; :class:Bead / :class:CGBond are interned handle views.

Dict keys:

  • bead["atoms"]tuple[Atom, ...] of atom views this bead groups. This is the bead's membership, owned by the molrs CoarseGrain as opaque atom handles (not a scalar component) and resolved back to views through the source all-atom world. Drives :meth:CoarseGrain.beads_of.
  • bead["x"] / bead["y"] / bead["z"] — position (molrs columns).
  • bead["type"] / bead["mass"] / bead["charge"] — molrs columns.

CoarseGrain

CoarseGrain(**props)

Bases: CoarseGrain, _GraphViews

Coarse-grained molecular structure backed by a molrs CoarseGrain.

Base order: the pyo3 native molrs.CoarseGrain must be first (see the note on :class:molpy.core.atomistic.Atomistic).

adopt staticmethod
adopt(graph)

Zero-copy take ownership of a molrs-produced CoarseGrain graph.

beads_of
beads_of(atom)

Beads whose membership includes atom (molrs reverse lookup).

copy
copy()

Independent deep copy. Handles are preserved (molrs clone).

merge
merge(other)

Structural merge of other into self (molrs).

Handles are remapped; other is emptied. View identity is not preserved.

to_frame
to_frame(bead_fields=None)

Export to a tabular :class:Frame (beads + cgbonds blocks).

Delegates straight to the molrs world's native to_frame: the Rust column store yields dense numpy columns and applies the CG-domain block / column labels (beads / cgbonds / ibead / jbead) itself, so there is zero Python-side conversion. bead_fields optionally restricts the beads block columns.

Config

config

Global configuration system for MolPy.

Thin singleton over :class:molcfg.Config (the molcrafts configuration library). Configuration can be read globally, updated, reset, or temporarily overridden with a context manager. Because the singleton is mutated in place, the module-level :data:config reference always reflects the current values.

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)
>>> print(config.n_threads)
4
>>>
>>> # Temporary override
>>> with Config.temporary(log_level="WARNING"):
...     print(config.log_level)
WARNING
>>> print(config.log_level)
DEBUG
>>> Config.reset()

config module-attribute

config = Config.instance()

Global config instance. Use this for read access.

Config

Bases: Config

Global configuration for MolPy, backed by :class:molcfg.Config.

Thread-safe singleton storing global settings such as the logging level and parallelization parameters. Use the class methods to access and modify the shared instance; values are read through attribute access (config.log_level) or dotted-path access (config["log_level"]).

Attributes:

Name Type Description
log_level

Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL).

n_threads

Number of threads for parallel computations.

instance classmethod
instance()

Get the singleton Config instance.

Thread-safe lazy initialization. Creates the instance on first call seeded with the default values.

Returns:

Type Description
Config

The singleton Config instance.

reset classmethod
reset()

Reset configuration to default values in place.

Thread-safe reset. Removes any keys added at runtime and restores the documented defaults.

temporary classmethod
temporary(**overrides)

Temporarily override configuration within a context.

Thread-safe context manager that snapshots the current state on entry and restores it on exit. Useful for testing or scoped parameter changes.

Parameters:

Name Type Description Default
**overrides Any

Configuration fields to temporarily override.

{}

Yields:

Type Description
None

None

update classmethod
update(**kwargs)

Update the global configuration in place.

Thread-safe update. Changes persist until :meth:reset or another :meth:update.

Parameters:

Name Type Description Default
**kwargs Any

Configuration fields to update (log_level, n_threads, ...).

{}

get_config

get_config()

Get the global configuration instance.

Convenience function equivalent to :meth:Config.instance.

Returns:

Type Description
Config

The singleton Config instance.

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

entity

Identity exports for the molrs-owned live graph view layer.

GraphViews

GraphViews(**props)

Mixin adding live refs and factories to a native molrs graph leaf.

NodeRef

NodeRef(world, handle)

Bases: _DictView

A live (world, handle) node reference.

Direct construction only wraps an existing handle. Use the owning graph's def_* factory to create a new node.

Refs

Bases: list[R]

List of live refs with vector-style property lookup by field name.

RelationRef

RelationRef(world, kind, handle, endpoints)

Bases: _DictView

A live relation reference with ordered, interned endpoint views.

Selector

selector

AtomIndexSelector

AtomIndexSelector(indices, id_field='id')

Bases: MaskPredicate

Select atoms by their indices.

Initialize atom index Selector.

Parameters:

Name Type Description Default
indices list[int] | ndarray

List or array of atom indices to select

required
id_field str

The field name containing atom IDs (default: "id")

'id'

AtomTypeSelector

AtomTypeSelector(atom_type, field='type')

Bases: MaskPredicate

Select atoms by their type (integer or string).

Initialize atom type Selector.

Parameters:

Name Type Description Default
atom_type int | str

The atom type to select (integer or string)

required
field str

The field name containing atom types (default: "type")

'type'

CoordinateRangeSelector

CoordinateRangeSelector(
    axis, min_value=None, max_value=None
)

Bases: MaskPredicate

Select atoms within a coordinate range.

Initialize coordinate range Selector.

Parameters:

Name Type Description Default
axis str

The coordinate axis ("x", "y", or "z")

required
min_value float | None

Minimum coordinate value (inclusive)

None
max_value float | None

Maximum coordinate value (inclusive)

None

DistanceSelector

DistanceSelector(center, max_distance, min_distance=None)

Bases: MaskPredicate

Select atoms within a distance from a reference point.

Initialize distance-based Selector.

Parameters:

Name Type Description Default
center list[float] | ndarray

Reference point [x, y, z]

required
max_distance float

Maximum distance from center (inclusive)

required
min_distance float | None

Minimum distance from center (inclusive, optional)

None

ElementSelector

ElementSelector(element, field='element')

Bases: MaskPredicate

Select atoms by their element symbol.

Initialize element Selector.

Parameters:

Name Type Description Default
element str

The element symbol to select (e.g., "C", "H", "O")

required
field str

The field name containing element symbols (default: "element")

'element'

MaskPredicate

Bases: ABC

Boolean mask producer combinable with &, |, ~.

Region

region

Selection sugar over molrs' native geometric regions.

Region

Bases: MaskPredicate

Mixin that adds coord_field and mask(Block) to native regions.

Units

unit

Python unit-system sugar over molrs' native unit engine.

UnitSystem

UnitSystem(*, base_units=None)

Bases: UnitRegistry

Native unit registry with LAMMPS presets and LJ construction sugar.

Parsing, definitions, dimensional arithmetic, and conversion all execute in molrs. base_units only records the user's chosen working units.

convert
convert(quantity, target)

Convert with this registry, including registry-local LJ units.

lj classmethod
lj(*, mass, sigma, epsilon)

Create a native Lennard-Jones reduced unit system.

preset classmethod
preset(name, **overrides)

Create a unit system from a LAMMPS unit-style preset.

preset_names classmethod
preset_names()

Return registered preset names.

register_preset classmethod
register_preset(name, base_units, *, overwrite=False)

Register a custom base-unit mapping.