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 |
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 |
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.AtomisticForcefield(name="demo", units="real")
style = ff.def_atomstyle("full")
ct = style.def_type("CT", mass=12.011)
Related¶
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.
Angle ¶
Atom ¶
Bases: Entity
Atom view: one node in a molrs Atomistic world (or pending).
is_virtual
property
¶
True if this node carries a virtual-site marker (vsite field).
The marker is a stored data field, not the Python class: molrs
re-materialises nodes as plain :class:Atom, so identity must be read
from the persisted vsite field rather than isinstance.
Atomistic ¶
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.
adopt
staticmethod
¶
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.
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 ¶
Transfer other's atoms and topology into self in place.
The same view objects are reused (identity preserved): each of
other's atoms/links is detached and re-spawned onto self with a
fresh handle, so external references (e.g. a reacter's leaving-group
list) stay valid. other is emptied and must not be used afterwards.
to_frame ¶
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.
Bond ¶
Dihedral ¶
DrudeParticle ¶
Improper ¶
MasslessSite ¶
VirtualSite ¶
Bases: Atom
A massless / rule-placed auxiliary particle. Data only — no energy.
Carries a persistent vsite marker field (set on construction) plus the
usual atom data. Subclasses set the marker value via _vsite_kind.
Identity after a molrs round-trip is read from the vsite field
(:attr:Atom.is_virtual), since the Python subclass is not preserved.
Box¶
box ¶
Box ¶
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
Styleenum (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 |
None
|
pbc
|
ArrayLike | None
|
Boolean periodic-boundary flags per axis, shape |
None
|
origin
|
ArrayLike | None
|
Cartesian origin in Angstroms, shape |
None
|
is_free
property
¶
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
¶
Lattice vector magnitudes [a, b, c] in Angstroms.
Returns zeros 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 box with three equal edge lengths.
from_bounds
classmethod
¶
Tight orthogonal box around a point cloud (non-periodic by default).
from_box
classmethod
¶
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
¶
Triclinic box from edge lengths and lattice angles (degrees).
general2restrict
staticmethod
¶
General → restricted-triclinic conversion (LAMMPS convention).
orth
classmethod
¶
Orthogonal (axis-aligned cuboid) box.
tric
classmethod
¶
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 ¶
Bases: AngleStyle
Angle class2/ba cross term.
AngleClass2BondBondStyle ¶
Bases: AngleStyle
Angle class2/bb cross term.
AngleClass2Style ¶
Bases: AngleStyle
Angle class2 style.
BondClass2Style ¶
Bases: BondStyle
Bond class2 style.
BondMorseStyle ¶
Bases: BondStyle
Bond morse style (LAMMPS bond_style morse).
DihedralCharmmStyle ¶
Bases: DihedralStyle
Dihedral charmm style.
DihedralClass2Style ¶
Bases: DihedralStyle
Dihedral class2 style.
DihedralFourierStyle ¶
Bases: DihedralStyle
Dihedral fourier style (AMBER multi-term).
DihedralMultiHarmonicStyle ¶
Bases: DihedralStyle
Dihedral multi/harmonic style.
DihedralPeriodicStyle ¶
Bases: DihedralStyle
Dihedral periodic (CHARMM-style charmm/periodic) style.
ImproperClass2Style ¶
Bases: ImproperStyle
Improper class2 style.
ImproperCvffStyle ¶
Bases: ImproperStyle
Improper cvff style.
ImproperHarmonicStyle ¶
Bases: ImproperStyle
Improper harmonic style.
ImproperPeriodicStyle ¶
Bases: ImproperStyle
Improper periodic style.
PairBuckStyle ¶
Bases: PairStyle
Pair buck (Buckingham) style.
PairCoulTTStyle ¶
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 ¶
Bases: PairStyle
Pair lj/class2 style.
PairMorseStyle ¶
Bases: PairStyle
Pair morse style.
PairTholeStyle ¶
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.
TypeBucket ¶
Generic TypeBucket implementation that groups and stores objects by their concrete type.
Supports two storage modes: - Set mode (set): For storing unique type definitions with automatic deduplication - List mode (list): For storing entity objects while maintaining order
Usage example
Set mode (used by forcefield)¶
bucket = TypeBucket(container_type=set)
List mode (used by entity)¶
bucket = TypeBucket(container_type=list)
Initialize TypeBucket
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
container_type
|
type
|
Container type, set (deduplication) or list (maintain order) |
set
|
bucket ¶
Get objects of the specified type and all its subclasses
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type[T]
|
Target type |
required |
Returns:
| Type | Description |
|---|---|
list[T]
|
List containing all matching objects |
exact_bucket ¶
Get objects of exact type (excluding subclasses)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type[T]
|
Target type |
required |
Returns:
| Type | Description |
|---|---|
list[T]
|
List containing exact matching objects |
remove ¶
Remove an object from the bucket
Returns:
| Type | Description |
|---|---|
bool
|
True if successfully removed, False otherwise |
Frame¶
frame ¶
molpy Frame/Block — re-exported from the molrs Rust backend.
After the frame-block-sink cutover (chain 4/4), molpy no longer defines its
own Frame/Block subclasses or any Python-side object-column overflow.
The canonical rich types live in molrs: numpy-only typed columns in the Rust
Store with a pandas-style Python API (selectors, sorting, row iteration, CSV,
and dict conversion).
Identity contract::
molpy.core.frame.Frame is molrs.Frame
molpy.core.frame.Block is molrs.Block
This module exists only so the existing from molpy.core.frame import Frame,
Block call sites keep resolving. Object / None / ragged columns are now
rejected fail-fast at write time (molrs.BlockDtypeError); callers must use
numpy-representable columns.
Trajectory¶
trajectory ¶
Trajectory container (molrs-backed) + split extensions.
The trajectory container sinks to molrs: :class:molpy.Trajectory subclasses
:class:molrs.Trajectory — an eager, materialized sequence of frames with
optional step / time arrays. molpy adds Python-side conveniences: an
associated topology, slice indexing that returns a sub-trajectory, and frame
mapping. Lazy, seekable reading from disk lives in molrs as TrajectoryReader
(molrs.read_lammps_trajectory / read_xyz_trajectory), not here.
Trajectory splitting stays in molpy as an extension layer that operates on the
molrs-backed container (:class:SplitStrategy and :class:TrajectorySplitter).
CustomStrategy ¶
Bases: SplitStrategy
Split a trajectory using a user-provided function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
split_func
|
Callable[[Trajectory], list[int]]
|
A callable taking a :class: |
required |
FrameIntervalStrategy ¶
Bases: SplitStrategy
Split a trajectory at regular frame intervals.
Splits the trajectory every interval frames, creating segments of equal
size (except possibly the last).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
int
|
Number of frames per segment. Must be positive. |
required |
SplitStrategy ¶
Bases: ABC
Abstract base class for trajectory splitting strategies.
Subclasses implement different strategies for dividing a trajectory into segments based on various criteria (frame count, time intervals, etc.).
get_split_indices
abstractmethod
¶
Get split-point indices for dividing the trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Indices where the trajectory should be split. The first index is 0 |
list[int]
|
and the last is the total number of frames. |
TimeIntervalStrategy ¶
Bases: SplitStrategy
Split a trajectory by simulation-time intervals.
Splits based on the trajectory's native per-frame time array (the molrs
container's time representation, set via Trajectory(frames, time=...)).
A trajectory without a time array is left unsplit (single segment).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Time interval for splitting (same units as the trajectory's
|
required |
Trajectory ¶
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: |
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)
has_length ¶
Whether len() is available — always True for the eager container.
Retained for backwards compatibility; the molrs-backed container is always materialized, so this never returns False.
map ¶
Apply func to every frame, returning a new trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[[Frame], Frame]
|
A callable mapping a :class: |
required |
Returns:
| Type | Description |
|---|---|
'Trajectory'
|
A new :class: |
'Trajectory'
|
trajectory's topology. The original is not modified. |
TrajectorySplitter ¶
Split a trajectory into sub-trajectories using a strategy.
The resulting segments are :class:Trajectory objects that share the same
topology as the original.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
split ¶
Split the trajectory using strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy
|
SplitStrategy
|
The splitting strategy to apply. |
required |
Returns:
| Type | Description |
|---|---|
list[Trajectory]
|
A list of :class: |
list[Trajectory]
|
the original frames sharing its topology. |
split_frames ¶
Split every interval frames (convenience for FrameIntervalStrategy).
split_time ¶
Split every interval time units (convenience for TimeIntervalStrategy).
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 molrsCoarseGrainas 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.
Bead ¶
Bases: Entity
Coarse-grained bead view: one node in a molrs CoarseGrain world.
The "atoms" key is not a scalar component: it is the bead's membership
(the underlying atom views it groups), owned by the molrs CoarseGrain as
opaque atom handles and resolved back to views through the source world. It
is intercepted here so bead["atoms"] / bead.get("atoms") keep working
over the membership store rather than the component columns.
CGBond ¶
CoarseGrain ¶
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).
merge ¶
Transfer other's beads and bonds into self in place.
Identity-preserving move (see :meth:molpy.core.atomistic.Atomistic.merge):
the same view objects are reused; other is emptied.
to_frame ¶
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
¶
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
¶
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 configuration to default values in place.
Thread-safe reset. Removes any keys added at runtime and restores the documented defaults.
temporary
classmethod
¶
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 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, ...). |
{}
|
Script¶
script ¶
Script - Editable script management with filesystem and URL support.
This module provides a Script class for managing script content that can be stored locally or loaded from URLs. It supports editing, formatting, and filesystem operations without any execution logic.
Script
dataclass
¶
Represents an editable script with filesystem and URL support.
This class manages script content, metadata, and filesystem operations. It does NOT provide execution logic - only content management.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Logical name of the script |
language |
ScriptLanguage
|
Script language type |
description |
str | None
|
Optional human-readable description |
_lines |
list[str]
|
Internal storage for multi-line content |
path |
Path | None
|
Local file path if stored on disk |
url |
str | None
|
URL the script was loaded from (if any) |
tags |
set[str]
|
Optional lightweight tag system |
lines
property
¶
Get a copy of all script lines.
Returns:
| Type | Description |
|---|---|
list[str]
|
Copy of internal lines list |
text
property
¶
Get the full script as a single string.
Returns:
| Type | Description |
|---|---|
str
|
Script content with lines joined by newlines, with exactly one trailing newline |
append ¶
Append a single line to the end of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
Line content to append |
''
|
append_block ¶
Append a multi-line block to the script.
The block is dedented, trailing newlines are stripped, and then split into lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
str
|
Multi-line string block to append |
required |
delete ¶
Delete the line at the given index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
0-based index of line to delete |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range |
delete_file ¶
Delete the script file from the filesystem.
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the file does not exist |
OSError
|
If the file cannot be deleted |
extend ¶
Append multiple lines in order to the end of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
Iterable of lines to append |
required |
format ¶
Apply string formatting to all lines and return a new Script.
Uses Python's str.format(**kwargs) on each line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Format arguments |
{}
|
Returns:
| Type | Description |
|---|---|
Script
|
New Script instance with formatted lines |
format_with_mapping ¶
Apply string formatting to all lines using a mapping and return a new Script.
Uses Python's str.format_map(mapping) on each line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping[str, Any]
|
Format mapping |
required |
Returns:
| Type | Description |
|---|---|
Script
|
New Script instance with formatted lines |
from_path
classmethod
¶
Create a Script from a local file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the script file |
required |
language
|
ScriptLanguage | None
|
Optional language override. If None, guessed from extension |
None
|
description
|
str | None
|
Optional description |
None
|
Returns:
| Type | Description |
|---|---|
Script
|
Script instance loaded from file |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist |
IOError
|
If the file cannot be read |
from_text
classmethod
¶
Create a Script from text content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logical name of the script |
required |
text
|
str
|
Multi-line text content |
required |
language
|
ScriptLanguage
|
Script language type |
'bash'
|
description
|
str | None
|
Optional description |
None
|
path
|
str | Path | None
|
Optional local file path |
None
|
url
|
str | None
|
Optional URL source |
None
|
Returns:
| Type | Description |
|---|---|
Script
|
Script instance with normalized content |
from_url
classmethod
¶
Create a Script from a URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to fetch the script from |
required |
name
|
str | None
|
Optional name. If None, derived from URL |
None
|
language
|
ScriptLanguage
|
Script language type |
'other'
|
description
|
str | None
|
Optional description |
None
|
Returns:
| Type | Description |
|---|---|
Script
|
Script instance loaded from URL |
Raises:
| Type | Description |
|---|---|
URLError
|
If the URL cannot be fetched |
insert ¶
Insert a single line at the given index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
0-based index where to insert |
required |
line
|
str
|
Line content to insert |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range |
move ¶
Move the script file to a new location.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_path
|
str | Path
|
New file path |
required |
Returns:
| Type | Description |
|---|---|
Path
|
New path where the script was moved |
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the original file does not exist |
OSError
|
If the file cannot be moved |
preview ¶
Generate a preview of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_lines
|
int
|
Maximum number of lines to show |
20
|
with_line_numbers
|
bool
|
Whether to include line numbers |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Preview string |
reload ¶
Reload the script content from its associated path.
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the file does not exist |
IOError
|
If the file cannot be read |
rename ¶
Rename the script file (keeping the same directory).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_name
|
str
|
New file name (with or without extension) |
required |
Returns:
| Type | Description |
|---|---|
Path
|
New path where the script was renamed |
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the original file does not exist |
OSError
|
If the file cannot be renamed |
replace ¶
Replace the line at the given index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
0-based index of line to replace |
required |
line
|
str
|
New line content |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range |
save ¶
Save the script to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | None
|
Optional path to save to. If None, uses self.path |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path where the script was saved |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no path is provided and self.path is None |
IOError
|
If the file cannot be written |
Entity and Link¶
entity ¶
Handle-view structure layer over a molrs ECS world.
molpy's structure containers (:class:~molpy.core.atomistic.Atomistic,
:class:~molpy.core.cg.CoarseGrain) are molrs leaves — they subclass
molrs.Atomistic / molrs.CoarseGrain and the molrs world is the single
source of truth. There is no mirror, no index shifting, no Struct container.
- Entity / Link are handle views holding
(world, handle). Property reads and writes route straight through the molrs component columns via the :class:_NodeProxy/ :class:_LinkProxylive mappings below, decomposing"xyz"to thex/y/zcolumns. There is no Python-side storage: a value molrs cannot represent (not bool/int/float/str) raises at the boundary. - Identity is preserved by interning: a :class:
weakref.WeakValueDictionarykeyed by handle returns the same view object for the same handle, sobond.itom is atom,atom in s.atomsandhash(atom)hold while a reference is alive. A handle whose node is despawned is evicted lazily. - Removal is stable:
world.despawn(handle)plus intern eviction; no reindex, surviving handles and relations stay valid.
The shared base :class:_GraphViews provides interning, the def_* skeleton
and the .atoms / .bonds view surface. The atomistic / CG leaves add their
domain view types.
Entities ¶
Bases: list[E]
A list of entity/link views supporting column access by string key.
ents["symbol"] returns a numpy array (one value per item, None where
unset); ents["xyz"] returns a numpy array of 3-vectors. Integer / slice
indexing behave as a normal list.
Entity ¶
Bases: _DictView
Dict-like view of one node in a molrs world (or a pending node).
Constructed standalone it is pending: self.data is a plain dict it owns
and self._world is None. Once a container's def_* / add_*
spawns a node for it, :meth:_attach flushes the dict into the world and
swaps self.data for a live column proxy — the same object becomes a bound
view, so identity (bond.itom is atom) survives.
Accepts both forms::
Atom(symbol="C", xyz=[0, 0, 0]) # kwargs
Atom({"symbol": "C", "xyz": ...}) # positional mapping
EntityLike ¶
Bases: Protocol
Protocol for objects that can act as Entities (Entity or subclass).
Link ¶
Bases: _DictView
Dict-like view of one relation in a molrs world (or a pending relation).
Holds ordered endpoint :class:Entity views in self.endpoints; when
bound, endpoints are resolved from world.relation_nodes so they are the
interned endpoint views.
LinkLike ¶
Bases: Protocol
Protocol for objects that can act as Links (Link or subclass).
Selector¶
selector ¶
AtomIndexSelector ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
BoxRegion ¶
Region ¶
Bases: MaskPredicate
Geometric region that is also a MaskPredicate.
Responsibilities: - purely geometric point-in-region logic - combination via & | ~ returning Region objects - expose axis-aligned bounding box via .bounds (shape (2,3)) - implement mask(block) by extracting coordinates from block
Units¶
unit ¶
Unit support for MolPy.
:class:UnitSystem is a :class:pint.UnitRegistry subclass. Its
constructor accepts every argument pint's does. On top of pint it:
- Pre-registers three per-molecule energy units
(
kilocalorie_per_mole,kilojoule_per_mole,gram_per_mole) and four LJ reduced-unit symbols (lj_sigma,lj_epsilon,lj_tau,lj_epsilon_over_kB). Names are prefixed so they do not shadow pint'ssigma(Stefan–Boltzmann alias) ortau(:math:2\pi). - Exposes a :attr:
~UnitSystem.base_unitsmapping{dimension: Unit}that records the user's chosen base unit per physical dimension. This is how downstream code (force fields, I/O, compute operators) learns "which length unit does this system use?" — without caring whether the system came from a preset. - Provides :meth:
~UnitSystem.preset(LAMMPS unit-style presets) and :meth:~UnitSystem.lj(Lennard-Jones reduced units) as optional factories.
Example
from molpy import UnitSystem real = UnitSystem.preset("real") 1.5 * real.angstrom
real.base_units["length"] ar = UnitSystem.lj( ... mass=39.948 * real.amu, ... sigma=3.405 * real.angstrom, ... epsilon=0.2381 * real.kilocalorie_per_mole, ... ) with ar.context("lj"): ... (4.0 * ar.angstrom).to(ar.lj_sigma).magnitude # doctest: +ELLIPSIS 1.174743...
UnitSystem ¶
Bases: UnitRegistry
A :class:pint.UnitRegistry with MolPy-specific pre-registered
units and an optional base_units selection per dimension.
The constructor accepts every argument :class:pint.UnitRegistry
accepts, plus one MolPy-specific keyword:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Forwarded to :class: |
()
|
base_units
|
Mapping[str, str] | None
|
Optional |
None
|
**kwargs
|
Any
|
Forwarded to :class: |
{}
|
Example
u = UnitSystem(base_units={"length": "nm", "time": "ps"}) u.base_units["length"]
2.5 * u.nanometer
lj
classmethod
¶
Return a reduced Lennard-Jones unit system.
The three scales mass, sigma (length), and epsilon
(per-molecule energy) fix the system; :math:\tau = \sqrt{m\sigma^2/\varepsilon}
and :math:\varepsilon/k_B are derived. The returned registry
has a pint context named "lj" registered; activate it with
with system.context("lj"): ... to convert across the
physical/reduced boundary.
mass/sigma/epsilon may be Quantities from any pint
registry — they are translated to SI magnitudes before being
rebuilt in the new registry.
preset
classmethod
¶
Return a :class:UnitSystem initialised from a built-in preset.
Currently MolPy ships the seven LAMMPS unit styles (real,
metal, si, cgs, electron, micro, nano).
Preset names and contents are an implementation detail — callers
consuming the resulting :class:UnitSystem must only rely on
:attr:base_units.
Any keyword overrides replace individual dimension entries::
>>> UnitSystem.preset("real", pressure="bar").base_units["pressure"]
<Unit('bar')>
register_preset
classmethod
¶
Register a custom unit-system preset, usable via :meth:preset.
Lets downstream code add unit styles without editing molpy (the preset
table is an extension point, not a closed set). base_units maps a
dimension name to a unit string, the same shape as the built-in
presets, e.g. {"length": "nm", "time": "ps", "energy": "kJ/mol"}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Preset name to register. |
required |
base_units
|
dict[str, str]
|
|
required |
overwrite
|
bool
|
Replace an existing preset of the same name instead of raising. |
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |