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)
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.
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.
symbols
property
¶
Element symbols for every atom (canonical :data:~molpy.core.fields.ELEMENT).
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.
from_frame
classmethod
¶
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 ¶
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 ¶
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 ¶
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.
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.
ForceField ¶
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 ¶
Register style (an unbound :class:Style, e.g.
BondHarmonicStyle()) and return a bound handle of the same class.
get_types ¶
Types of a category (str) or by :class:Type subclass, across styles.
rename_type ¶
Rename type old -> new across all styles of style_cls's
category (molpy signature).
ImproperClass2Style ¶
Bases: ImproperStyle
Improper class2 style.
ImproperHarmonicStyle ¶
Bases: ImproperStyle
Improper harmonic style.
ImproperPeriodicStyle ¶
Bases: ImproperStyle
Improper periodic 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.
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.
Parameters ¶
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.
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 ¶
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.
Block ¶
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)).
from_csv
classmethod
¶
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
¶
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).
sort ¶
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.
to_csv ¶
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.
Trajectory¶
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)
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. |
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.
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 ¶
Structural merge of other into self (molrs).
Handles are remapped; other is emptied. View identity is not preserved.
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 ¶
Identity exports for the molrs-owned live graph view layer.
NodeRef ¶
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 ¶
Bases: _DictView
A live relation reference with ordered, interned endpoint views.
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¶
Units¶
unit ¶
Python unit-system sugar over molrs' native unit engine.
UnitSystem ¶
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.