Core¶
Foundational data structures for molecular systems. All available via import molpy as mp.
Quick reference¶
| Symbol | Summary | Preferred for | Avoid when |
|---|---|---|---|
Atomistic |
Editable molecular graph (atoms + bonds) | Building, editing, reacting on chemistry | Array-backed analysis or export |
Block |
Columnar table: column names → NumPy arrays | Tabular data, vectorized computation | Graph-level chemical editing |
Frame |
Named collection of Blocks + metadata | System snapshots, file I/O | Editing individual atoms |
Box |
Periodic simulation cell (3×3 matrix + PBC) | Wrapping, minimum-image distances | Non-periodic systems |
Trajectory |
Ordered sequence of Frames (eager or lazy) | Time-series analysis, streaming I/O | Single-snapshot work |
Topology |
igraph-based bond graph → derived angles/dihedrals | Graph algorithms, connectivity queries | Storing atom properties |
CoarseGrain |
CG molecular graph (beads + CG bonds) | Coarse-grained modelling; mirrors Atomistic |
All-atom work (use Atomistic) |
Config |
Thread-safe global configuration singleton | Logging level, thread count settings | Per-run overrides (use Config.temporary) |
AtomisticForcefield |
Force field container (styles → types → potentials) | Defining parameters before execution | Direct numerical computation |
Canonical examples¶
import molpy as mp
# Atomistic: editable molecular graph
mol = mp.Atomistic(name="water")
o = mol.def_atom(element="O", x=0.0, y=0.0, z=0.0)
h = mol.def_atom(element="H", x=0.957, y=0.0, z=0.0)
mol.def_bond(o, h)
# Block + Frame: tabular snapshot
frame = mp.Frame(blocks={
"atoms": {"element": ["O", "H"], "x": [0.0, 0.957]},
}, timestep=0)
# Box: periodic cell
box = mp.Box.cubic(20.0)
wrapped = box.wrap(coords)
d = box.dist(r1, r2) # minimum-image distance
# ForceField: parameter data
ff = mp.AtomisticForcefield(name="demo", units="real")
style = ff.def_atomstyle("full")
ct = style.def_type("CT", mass=12.011)
Related¶
Full API¶
Atomistic¶
atomistic ¶
Angle ¶
Bases: Link
Valence angle formed by three atoms (i--j--k).
The central atom jtom is the vertex of the angle. Angle values are
measured in radians by convention throughout MolPy.
Create an angle between three atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom (one arm of the angle). |
required |
b
|
Atom
|
Central/vertex atom. |
required |
c
|
Atom
|
Third atom (other arm of the angle). |
required |
**attrs
|
Any
|
Arbitrary angle attributes (e.g., |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any argument is not an Atom instance. |
Atom ¶
Bases: Entity
Atom entity (common keys include {"element": "C", "xyz": [...]})
Atomistic ¶
Bases: Struct, MembershipMixin, SpatialMixin, ConnectivityMixin, Graph
All-atom molecular structure with full topological information.
Atomistic is the primary container for molecular systems in MolPy. It manages collections of atoms, bonds, angles, and dihedrals through typed buckets, and provides factory methods for creating and adding topology elements.
Supports spatial operations (move, rotate, scale, align), system
composition via + / +=, and conversion to tabular Frame format
for I/O.
Initialize an empty atomistic structure.
Registers buckets for Atom, Bond, Angle, and Dihedral types.
If the concrete subclass defines a __post_init__ method, it is
called automatically with the same keyword arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**props
|
Any
|
Arbitrary properties stored on the structure (e.g.,
|
{}
|
angles
property
¶
All angles in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Angle]
|
Entities[Angle]: Column-accessible list of Angle objects. |
atoms
property
¶
All atoms in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Atom]
|
Entities[Atom]: Column-accessible list of Atom objects. |
bonds
property
¶
All bonds in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Bond]
|
Entities[Bond]: Column-accessible list of Bond objects. |
dihedrals
property
¶
All dihedrals in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Dihedral]
|
Entities[Dihedral]: Column-accessible list of Dihedral objects. |
impropers
property
¶
All impropers in this structure.
Returns:
| Type | Description |
|---|---|
Entities[Improper]
|
Entities[Improper]: Column-accessible list of Improper objects. |
symbols
property
¶
Element symbols for every atom in insertion order.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of element strings (e.g., |
xyz
property
¶
Get atomic positions as numpy array.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Nx3 array of atomic coordinates, or list of lists if numpy not available. |
add_angle ¶
add_angles ¶
add_atom ¶
Add an existing Atom object to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom
|
Atom
|
Atom instance to register. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Atom |
Atom
|
The same atom passed in (for chaining convenience). |
Preferred for
Re-using an Atom created elsewhere. Use def_atom to create
and add in one step.
add_atoms ¶
add_bond ¶
add_bonds ¶
add_dihedral ¶
add_dihedrals ¶
add_improper ¶
align ¶
Align this structure so that atom a coincides with atom b.
When direction vectors a_dir and b_dir are given, the
structure is first rotated to align the two directions, then
translated so that a lands on b.
This is an in-place operation that returns self for method
chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Entity
|
Source reference atom (in this structure). |
required |
b
|
Entity
|
Target reference atom (position to align to) with coordinates in angstroms. |
required |
a_dir
|
list[float] | None
|
Direction vector at |
None
|
b_dir
|
list[float] | None
|
Direction vector at |
None
|
flip
|
bool
|
If True, reverse |
False
|
entity_type
|
type[Entity]
|
Entity type to transform (default: Atom). |
Atom
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
|
def_angle ¶
Create a new Angle between three atoms and add it to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom (one arm of the angle). |
required |
b
|
Atom
|
Central/vertex atom. |
required |
c
|
Atom
|
Third atom (other arm of the angle). |
required |
**attrs
|
Any
|
Angle attributes (e.g., |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Angle |
Angle
|
The newly created and registered angle. |
def_angles ¶
Create multiple Angles from a list of atom-triple tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
angles_data
|
list[tuple[Atom, Atom, Atom] | tuple[Atom, Atom, Atom, dict[str, Any]]]
|
Each element is |
required |
Returns:
| Type | Description |
|---|---|
list[Angle]
|
list[Angle]: Newly created angles in the same order as input. |
def_atom ¶
Create a new Atom and add it to the structure.
If an xyz key is provided, it is expanded into separate x,
y, z float fields on the created atom.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**attrs
|
Any
|
Atom attributes. Common keys include |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Atom |
Atom
|
The newly created and registered atom. |
Preferred for
Building structures atom-by-atom. Use add_atom instead when
the Atom object already exists.
def_atoms ¶
Create multiple Atoms from a list of attribute dictionaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms_data
|
list[dict[str, Any]]
|
Each dict is passed as |
required |
Returns:
| Type | Description |
|---|---|
list[Atom]
|
list[Atom]: Newly created atoms in the same order as input. |
def_bond ¶
Create a new Bond between two atoms and add it to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom endpoint. |
required |
b
|
Atom
|
Second atom endpoint. |
required |
**attrs
|
Any
|
Bond attributes (e.g., |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Bond |
Bond
|
The newly created and registered bond. |
def_bonds ¶
Create multiple Bonds from a list of atom-pair tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bonds_data
|
list[tuple[Atom, Atom] | tuple[Atom, Atom, dict[str, Any]]]
|
Each element is |
required |
Returns:
| Type | Description |
|---|---|
list[Bond]
|
list[Bond]: Newly created bonds in the same order as input. |
def_dihedral ¶
Create a new Dihedral between four atoms and add it to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom. |
required |
b
|
Atom
|
Second atom (part of the central bond). |
required |
c
|
Atom
|
Third atom (part of the central bond). |
required |
d
|
Atom
|
Fourth atom. |
required |
**attrs
|
Any
|
Dihedral attributes (e.g., |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Dihedral |
Dihedral
|
The newly created and registered dihedral. |
def_dihedrals ¶
Create multiple Dihedrals from a list of atom-quadruple tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dihedrals_data
|
list[tuple[Atom, Atom, Atom, Atom] | tuple[Atom, Atom, Atom, Atom, dict[str, Any]]]
|
Each element is |
required |
Returns:
| Type | Description |
|---|---|
list[Dihedral]
|
list[Dihedral]: Newly created dihedrals in the same order as input. |
def_improper ¶
Create a new Improper torsion and add it to the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
Central atom. |
required |
b
|
Atom
|
First substituent atom. |
required |
c
|
Atom
|
Second substituent atom. |
required |
d
|
Atom
|
Third substituent atom. |
required |
**attrs
|
Any
|
Improper attributes (e.g., |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Improper |
Improper
|
The newly created and registered improper. |
del_angle ¶
Remove angles from the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*angles
|
Angle
|
Angle instances to remove. |
()
|
del_atom ¶
Remove atoms and all their incident bonds, angles, and dihedrals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*atoms
|
Atom
|
Atom instances to remove. |
()
|
del_bond ¶
Remove bonds (and any dependent angles / dihedrals that reference them).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*bonds
|
Bond
|
Bond instances to remove. |
()
|
del_dihedral ¶
Remove dihedrals from the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*dihedrals
|
Dihedral
|
Dihedral instances to remove. |
()
|
del_improper ¶
Remove impropers from the structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*impropers
|
Improper
|
Improper instances to remove. |
()
|
extract_subgraph ¶
Extract subgraph preserving all topology (bonds, angles, dihedrals).
Overrides ConnectivityMixin.extract_subgraph to ensure all topology types (bonds, angles, dihedrals) are preserved in the extracted subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
center_entities
|
Iterable[Atom]
|
Center atoms for extraction |
required |
radius
|
int
|
Topological radius |
required |
entity_type
|
type[Atom]
|
Entity type (should be Atom) |
Atom
|
link_type
|
type[Link]
|
Link type for topology calculation (should be Bond) |
Bond
|
Returns:
| Type | Description |
|---|---|
tuple['Atomistic', list[Atom]]
|
Tuple of (subgraph Atomistic, edge atoms) |
get_topo ¶
Generate topology (angles and dihedrals) from bonds.
When gen_angle or gen_dihe is True, returns a new Atomistic
with the generated interactions added — the original is not mutated.
When both are False, falls through to the base-class method and returns
a :class:Topology graph (used internally for traversal).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_type
|
type[Entity]
|
Entity type to include in topology (default: Atom) |
Atom
|
link_type
|
type[Link]
|
Link type to use for connections (default: Bond) |
Bond
|
gen_angle
|
bool
|
Whether to generate angles |
False
|
gen_dihe
|
bool
|
Whether to generate dihedrals |
False
|
clear_existing
|
bool
|
If True, clear existing angles/dihedrals before generating new ones. |
False
|
Returns:
| Type | Description |
|---|---|
'Atomistic | Topology'
|
New Atomistic with angles/dihedrals added when gen_angle or |
'Atomistic | Topology'
|
gen_dihe is True; Topology graph otherwise. |
move ¶
Translate all atoms by a displacement vector.
This is an in-place operation that returns self for method
chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta
|
list[float]
|
Translation vector |
required |
entity_type
|
type[Entity]
|
Entity type to translate (default: Atom). |
Atom
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
|
rename_type ¶
Rename all entities/links of kind whose type attribute equals old.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old
|
str
|
Existing type name. |
required |
new
|
str
|
Replacement type name. |
required |
kind
|
type
|
Entity or Link class to target (default: |
Atom
|
Returns:
| Type | Description |
|---|---|
int
|
Number of entities/links whose type was renamed. |
replicate ¶
Create n copies and merge them into a new system.
Each copy is independently deep-copied from self, optionally
transformed, then merged into a single new Atomistic structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of copies to create. |
required |
transform
|
Callable | None
|
Optional callable |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
A new structure containing all replicas merged together. |
Example
waters = Water().replicate(10, lambda mol, i: mol.move([i5, 0, 0])) grid = Methane().replicate(9, lambda mol, i: mol.move([i%35, i//3*5, 0]))
rotate ¶
Rotate all atoms around an axis using the Rodrigues formula.
This is an in-place operation that returns self for method
chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
list[float]
|
Rotation axis |
required |
angle
|
float
|
Rotation angle in radians. |
required |
about
|
list[float] | None
|
Point |
None
|
entity_type
|
type[Entity]
|
Entity type to rotate (default: Atom). |
Atom
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
|
scale ¶
Scale all atom positions by a uniform factor.
This is an in-place operation that returns self for method
chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor
|
float
|
Multiplicative scale factor (dimensionless). |
required |
about
|
list[float] | None
|
Center of scaling |
None
|
entity_type
|
type[Entity]
|
Entity type to scale (default: Atom). |
Atom
|
Returns:
| Name | Type | Description |
|---|---|---|
Atomistic |
'Atomistic'
|
|
select ¶
Return a new Atomistic containing atoms matching predicate.
All bonds/angles/dihedrals whose endpoints are fully contained in the selection are carried over (deep-copied).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicate
|
Callable |
required |
Returns:
| Type | Description |
|---|---|
'Atomistic'
|
New Atomistic with the selected atoms and their induced topology. |
set_property ¶
Set a property on every atom (or link) matching selector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selector
|
Callable |
required | |
key
|
str
|
Property key to assign. |
required |
value
|
Any
|
Value to store. |
required |
kind
|
type
|
Entity or Link class to iterate (default: |
Atom
|
Returns:
| Type | Description |
|---|---|
int
|
Number of items updated. |
to_frame ¶
Convert to LAMMPS data Frame format.
Converts this Atomistic structure into a Frame suitable for writing as a LAMMPS data file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom_fields
|
list[str] | None
|
List of atom fields to extract. If None, extracts all fields. |
None
|
Returns:
| Type | Description |
|---|---|
'Frame'
|
Frame with atoms, bonds, angles, and dihedrals |
Example
butane = CH3() + CH2() + CH3()
Extract all fields¶
frame = butane.to_frame()
Extract specific fields only¶
frame = butane.to_frame( ... atom_fields=['xyz', 'charge', 'element', 'type'], ... bond_fields=['itom', 'jtom', 'type'], ... ) writer = LammpsDataWriter("system.data") writer.write(frame)
Bond ¶
Bases: Link
Covalent bond connecting two atoms.
A Bond holds ordered references to exactly two Atom endpoints and optional key-value attributes (e.g., bond order, force-field type).
Create a bond between two atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom endpoint. |
required |
b
|
Atom
|
Second atom endpoint. |
required |
**attrs
|
Any
|
Arbitrary bond attributes (e.g., |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If either argument is not an Atom instance. |
Dihedral ¶
Bases: Link
Dihedral (torsion) angle between four atoms
Create a dihedral angle between four atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
First atom. |
required |
b
|
Atom
|
Second atom (part of the central bond). |
required |
c
|
Atom
|
Third atom (part of the central bond). |
required |
d
|
Atom
|
Fourth atom. |
required |
**attrs
|
Any
|
Arbitrary dihedral attributes (e.g., |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any argument is not an Atom instance. |
Improper ¶
Bases: Link
Improper torsion between four atoms (i is the central atom).
Impropers constrain out-of-plane geometry around a central atom i
bonded to three substituents j/k/l. They are topologically
distinct from proper :class:Dihedral terms — force fields assign
separate coefficients and LAMMPS/OpenMM/GROMACS all treat the two as
separate lists.
Create an improper torsion between four atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Atom
|
Central atom. |
required |
b
|
Atom
|
First substituent atom. |
required |
c
|
Atom
|
Second substituent atom. |
required |
d
|
Atom
|
Third substituent atom. |
required |
**attrs
|
Any
|
Arbitrary improper attributes (e.g., |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any argument is not an Atom instance. |
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
|
lengths
property
¶
Lattice vector magnitudes [a, b, c] in Angstroms.
Returns zeros for FREE.
Style ¶
Bases: Enum
Enumeration of simulation-box geometries.
cubic
classmethod
¶
Cubic box with three equal edge lengths.
from_bounds
classmethod
¶
Tight orthogonal box around a point cloud (non-periodic by default).
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 ¶
AngleStyle ¶
Bases: Style
Style for angle interactions (e.g. "harmonic").
def_type ¶
to_potential ¶
Create corresponding Potential instance from AngleStyle.
Returns:
| Name | Type | Description |
|---|---|---|
Potential |
Potential
|
Potential instance that accepts string type labels (from Frame). The potential internally uses TypeIndexedArray to map type names to parameters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If corresponding Potential class not found or missing required parameters |
AngleType ¶
Bases: Type
Angle type defined by three atom types
Initialise an angle type defined by three atom types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this angle type. |
required |
itom
|
AtomType
|
First endpoint atom type. |
required |
jtom
|
AtomType
|
Central (vertex) atom type. |
required |
ktom
|
AtomType
|
Third endpoint atom type. |
required |
**kwargs
|
Any
|
Angle parameters (e.g. |
{}
|
matches ¶
Check whether this angle type matches an atom type triple.
Matching considers both forward (at1, at2, at3) and reverse
(at3, at2, at1) orderings; the central atom must always
match jtom.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First endpoint atom type. |
required |
at2
|
AtomType
|
Central atom type. |
required |
at3
|
AtomType
|
Third endpoint atom type. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
AtomType ¶
Bases: Type
Force-field type for a single atom.
An AtomType carries parameters such as mass, charge, and element symbol. Typical keyword parameters include:
mass-- atomic mass in g/mol (amu)charge-- partial charge in elementary charge units (e)element-- chemical element symbol
AtomisticForcefield ¶
Bases: ForceField
Convenience subclass of ForceField with shorthand methods for atomistic styles.
Provides def_*style helpers that create and register the
appropriate Style subclass in a single call, and get_*types
accessors for the most common interaction categories.
def_anglestyle ¶
Create and register an AngleStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the angle style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to AngleStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to AngleStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
AngleStyle
|
The registered (or existing) AngleStyle instance. |
def_atomstyle ¶
Create and register an AtomStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the atom style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to AtomStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to AtomStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
AtomStyle
|
The registered (or existing) AtomStyle instance. |
def_bondstyle ¶
Create and register a BondStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the bond style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to BondStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to BondStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
BondStyle
|
The registered (or existing) BondStyle instance. |
def_dihedralstyle ¶
Create and register a DihedralStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the dihedral style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to DihedralStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to DihedralStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
DihedralStyle
|
The registered (or existing) DihedralStyle instance. |
def_improperstyle ¶
Create and register an ImproperStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the improper style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to ImproperStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to ImproperStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
ImproperStyle
|
The registered (or existing) ImproperStyle instance. |
def_pairstyle ¶
Create and register a PairStyle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the pair style (e.g. |
required |
*args
|
Any
|
Positional parameters forwarded to PairStyle. |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to PairStyle. |
{}
|
Returns:
| Type | Description |
|---|---|
PairStyle
|
The registered (or existing) PairStyle instance. |
get_angletypes ¶
Return all AngleType instances across all registered styles.
Returns:
| Type | Description |
|---|---|
list[AngleType]
|
Deduplicated list of AngleType instances. |
BondStyle ¶
Bases: Style
Style for bond interactions (e.g. "harmonic").
def_type ¶
to_potential ¶
Create corresponding Potential instance from BondStyle.
Returns:
| Name | Type | Description |
|---|---|---|
Potential |
Potential
|
Potential instance that accepts string type labels (from Frame). The potential internally uses dictionaries to map type names to parameters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If corresponding Potential class not found or missing required parameters |
BondType ¶
Bases: Type
Bond type defined by two atom types
Initialise a bond type between two atom types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this bond type. |
required |
itom
|
AtomType
|
First endpoint atom type. |
required |
jtom
|
AtomType
|
Second endpoint atom type. |
required |
**kwargs
|
Any
|
Bond parameters (e.g. |
{}
|
matches ¶
Check whether this bond type matches an atom type pair.
Matching is order-independent: (at1, at2) matches if
(itom, jtom) equals (at1, at2) or (at2, at1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First atom type. |
required |
at2
|
AtomType
|
Second atom type. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
DihedralStyle ¶
Bases: Style
Style for dihedral (torsion) interactions (e.g. "opls").
def_type ¶
Define dihedral type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType
|
Second atom type |
required |
ktom
|
AtomType
|
Third atom type |
required |
ltom
|
AtomType
|
Fourth atom type |
required |
name
|
str
|
Optional name (defaults to itom-jtom-ktom-ltom) |
''
|
**kwargs
|
Any
|
Dihedral parameters |
{}
|
DihedralType ¶
Bases: Type
Dihedral (torsion) type defined by four atom types.
Initialise a dihedral type for four atom types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this dihedral type. |
required |
itom
|
AtomType
|
First atom type. |
required |
jtom
|
AtomType
|
Second atom type. |
required |
ktom
|
AtomType
|
Third atom type. |
required |
ltom
|
AtomType
|
Fourth atom type. |
required |
**kwargs
|
Any
|
Dihedral parameters (e.g. |
{}
|
matches ¶
Check whether this dihedral type matches an atom type quadruple.
Both forward (at1, at2, at3, at4) and reverse
(at4, at3, at2, at1) orderings are considered equivalent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First atom type. |
required |
at2
|
AtomType
|
Second atom type. |
required |
at3
|
AtomType
|
Third atom type. |
required |
at4
|
AtomType
|
Fourth atom type. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
ForceField ¶
Top-level container for a complete force-field definition.
A ForceField aggregates multiple Style instances (atom, bond,
angle, dihedral, improper, pair) and provides lookup, merging, and
conversion to Potential objects for energy evaluation.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Human-readable name of the force field. |
|
units |
Unit system used by the parameters (e.g. |
Initialise a force field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the force field (e.g. |
''
|
units
|
str
|
Unit convention for parameter values. Defaults to
|
'real'
|
def_style ¶
Register a Style instance with the force field.
The API no longer accepts Style classes. Callers must pass an instantiated
Style (e.g. ff.def_style(AtomStyle("full"))). If a style with the
same runtime class and name already exists it will be returned instead of
registering a duplicate.
get_style_by_name ¶
Get a style by name from the force field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the style to find |
required |
style_class
|
type[S]
|
Class of the style to search for (defaults to Style) |
Style
|
Returns:
| Type | Description |
|---|---|
S | None
|
The first matching Style instance, or None if not found |
get_styles ¶
Retrieve all styles that are instances of the given class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
style_class
|
type[S]
|
The Style subclass to filter by (e.g.
|
required |
Returns:
| Type | Description |
|---|---|
List[S]
|
List of matching Style instances. |
get_types ¶
Collect all types of the given class from every registered style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_class
|
type[Ty]
|
The Type subclass to collect (e.g. |
required |
Returns:
| Type | Description |
|---|---|
list[Ty]
|
Deduplicated list of matching Type instances across all styles. |
merge ¶
Merge another force field's styles and types into this one.
For each style in other, if a style with the same class and name already exists in this force field it is merged in-place; otherwise the style is added as-is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
ForceField
|
The force field whose contents are merged in. |
required |
Returns:
| Type | Description |
|---|---|
ForceField
|
This force field instance (for chaining). |
remove_style ¶
Remove a Style instance of style_class whose name matches.
Returns True if a style was removed.
remove_type ¶
Remove every Type named name from styles of style_class.
Returns the number of Types removed.
rename_type ¶
Rename every Type named old to new in matching styles.
After mutating the internal _name the type is removed and
re-added to its bucket so set-based hash lookups stay consistent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
style_class
|
type[S]
|
Style subclass whose type bucket is targeted. |
required |
old
|
str
|
Existing type name. |
required |
new
|
str
|
Replacement type name. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of Types renamed. |
to_potentials ¶
Create Potential instances from all styles in ForceField.
Returns:
| Name | Type | Description |
|---|---|---|
Potentials |
Potentials
|
Collection containing all created potential instances. |
Note
Only Styles that support to_potential() method will be converted (e.g. BondStyle, AngleStyle, PairStyle)
ImproperStyle ¶
Bases: Style
Style for improper dihedral interactions (e.g. "cvff").
def_type ¶
Define improper dihedral type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType
|
Second atom type (usually central atom) |
required |
ktom
|
AtomType
|
Third atom type |
required |
ltom
|
AtomType
|
Fourth atom type |
required |
name
|
str
|
Optional name (defaults to itom-jtom-ktom-ltom) |
''
|
**kwargs
|
Any
|
Improper dihedral parameters |
{}
|
ImproperType ¶
Bases: Type
Improper dihedral type defined by four atom types.
Improper dihedrals typically have a designated central atom (often
jtom) and are used to enforce planarity or chirality.
Initialise an improper dihedral type for four atom types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this improper type. |
required |
itom
|
AtomType
|
First atom type. |
required |
jtom
|
AtomType
|
Second atom type (typically the central atom). |
required |
ktom
|
AtomType
|
Third atom type. |
required |
ltom
|
AtomType
|
Fourth atom type. |
required |
**kwargs
|
Any
|
Improper parameters (e.g. |
{}
|
matches ¶
Check whether this improper type matches an atom type quadruple.
Uses exact positional matching (no reverse ordering) because improper dihedrals have a specific central atom convention.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First atom type. |
required |
at2
|
AtomType
|
Second atom type. |
required |
at3
|
AtomType
|
Third atom type. |
required |
at4
|
AtomType
|
Fourth atom type. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
PairStyle ¶
Bases: Style
Style for non-bonded pair interactions (e.g. "lj/cut").
def_type ¶
Define non-bonded interaction type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType | None
|
Second atom type (optional, defaults to same as itom for self-interaction) |
None
|
name
|
str
|
Optional name |
''
|
**kwargs
|
Any
|
Non-bonded parameters (e.g. sigma, epsilon, charge, etc.) |
{}
|
PairType ¶
Bases: Type
Non-bonded interaction type defined by one or two atom types
Initialise a non-bonded pair type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this pair type. |
required |
*atom_types
|
AtomType
|
One or two |
()
|
**kwargs
|
Any
|
Pair parameters (e.g. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If not exactly 1 or 2 atom types are provided. |
matches ¶
Check whether this pair type matches an atom type pair.
Matching is order-independent. If only at1 is given, it is treated as a self-interaction query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at1
|
AtomType
|
First atom type. |
required |
at2
|
AtomType | None
|
Second atom type. Defaults to at1 (self-interaction). |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
Parameters ¶
Container for positional and keyword parameters of a force-field type or style.
Provides indexed access to positional arguments (by int or slice)
and keyword arguments (by str).
Initialise with arbitrary positional and keyword arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional parameters (stored as a list). |
()
|
**kwargs
|
Any
|
Keyword parameters (stored as a dict). |
{}
|
Style ¶
Named interaction style that groups related Type instances.
A Style represents a particular functional form for an interaction
category (e.g. BondStyle("harmonic")). It holds a TypeBucket
of Type instances that share the same functional form.
Initialise a named interaction style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the interaction style (e.g. |
required |
*args
|
Any
|
Additional positional parameters forwarded to
|
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to |
{}
|
copy ¶
Create a copy of this style with the same name and parameters (but not types).
Returns:
| Type | Description |
|---|---|
Style
|
A new Style instance with copied name and parameters |
get_type_by_name ¶
Get a type by name from this style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the type to find |
required |
type_class
|
type[Ty]
|
Class of the type to search for (defaults to Type) |
Type
|
Returns:
| Type | Description |
|---|---|
Ty | None
|
The first matching Type instance, or None if not found |
get_types ¶
Get all types of the specified class from this style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_class
|
type[Ty]
|
Class of the types to retrieve (e.g., AtomType, BondType) |
required |
Returns:
| Type | Description |
|---|---|
list[Ty]
|
List of types of the specified class |
merge ¶
Merge another Style's parameters and types into this one.
Parameters from other are appended (positional) or updated (keyword). All types from other are added to this style's type bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Style
|
The style whose contents are merged in. |
required |
Returns:
| Type | Description |
|---|---|
Style
|
This style instance (for chaining). |
Type ¶
Base class for all force-field type descriptors.
A Type carries a unique name together with arbitrary Parameters
that describe a particular force-field entry (e.g. atom type, bond type).
Types are hashed and compared by (class, name) so two instances of
the same subclass with the same name are considered equal.
Initialise a force-field type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this type (e.g. |
required |
*args
|
Any
|
Additional positional parameters forwarded to |
()
|
**kwargs
|
Any
|
Keyword parameters forwarded to |
{}
|
copy ¶
Create a copy of this type with the same name and parameters.
Returns:
| Type | Description |
|---|---|
Type
|
A new Type instance with copied parameters |
get ¶
Return a keyword parameter or a default value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Parameter name. |
required |
default
|
Any
|
Value returned when key is absent. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The parameter value if present, otherwise default. |
TypeBucket ¶
A collection that partitions items into buckets keyed by their runtime type.
Items are stored in sets grouped by type(item). Retrieval via
bucket(cls) returns all items whose runtime type is a subclass of
cls, enabling polymorphic queries over heterogeneous collections.
add ¶
Add an item to the bucket corresponding to its runtime type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to store. It is placed in the set keyed by
|
required |
bucket ¶
Retrieve all items whose runtime type is a subclass of cls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
The base class to match against. All items stored under
a key |
required |
Returns:
| Type | Description |
|---|---|
List[T]
|
A flat list of matching items (order is not guaranteed). |
classes ¶
Iterate over the distinct runtime types that have been stored.
Returns:
| Type | Description |
|---|---|
Iterator[type[T]]
|
An iterator of |
Iterator[type[T]]
|
contain at least one item. |
remove ¶
Remove an item from its type bucket.
If the item is not present, this is a no-op (uses discard).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to remove. |
required |
get_nearest_type ¶
Return the most specific runtime type of an item.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
Any object whose runtime class is needed. |
required |
Returns:
| Type | Description |
|---|---|
type[T]
|
The concrete |
Frame¶
frame ¶
Block ¶
Bases: Block, MutableMapping[str, ndarray]
Lightweight container that maps variable names -> NumPy arrays.
Inherits molrs.Block directly, so a molpy.Block IS-A
molrs.Block and is accepted by every molrs.* API that takes a
block (Frame.__setitem__, IO writers, …) with no conversion.
All numeric / bool / string-list columns live in the Rust Store;
object-dtype columns (e.g. element symbols stored as
np.array(..., dtype=object)) live on the Python side in
self._objects — they have no Rust representation.
• Behaves like a dict but auto-casts any assigned value to ndarray.
• All built-in dict/MutableMapping helpers work out of the box.
• Supports advanced indexing: by key, by index/slice, by mask, by list of keys.
Parameters¶
vars_ : dict[str, ArrayLike] or None, optional Initial data to populate the Block. Keys are variable names, values are array-like data that will be converted to numpy arrays.
Examples¶
Create and access basic data:
blk = Block() blk["x"] = [0.0, 1.0, 2.0] blk["y"] = [0.0, 0.0, 0.0] "x" in blk True len(blk) 2 blk["x"].dtype dtype('float64')
Multiple indexing methods:
blk = Block({"id": [1, 2, 3], "x": [10.0, 20.0, 30.0]}) blk[0] # Access single row, returns dict {'id': 1, 'x': 10.0} blk[0:2] # Slice access {'id': array([1, 2]), 'x': array([10., 20.])} blk[["id", "x"]] # Multi-column access, returns 2D array (requires same dtype) Traceback (most recent call last): ... ValueError: Arrays must have the same dtype...
Using boolean masks for filtering:
blk = Block({"id": [1, 2, 3, 4, 5], "mol_id": [1, 1, 2, 2, 3]}) mask = blk["mol_id"] < 3 sub_blk = blk[mask] sub_blk["id"] array([1, 2, 3, 4]) sub_blk.nrows 4
Sorting:
blk = Block({"x": [3, 1, 2], "y": [30, 10, 20]}) sorted_blk = blk.sort("x") # Returns new Block sorted_blk["x"] array([1, 2, 3]) _ = blk.sort_("x") # In-place sort, returns self blk["x"] array([1, 2, 3])
from_csv
classmethod
¶
Create a Block from a CSV file or StringIO.
Parameters¶
filepath : str, Path, or StringIO Path to the CSV file or StringIO object delimiter : str, default="," CSV delimiter character encoding : str, default="utf-8" File encoding (ignored for StringIO) header : list[str] or None, default=None Column names. If None, first row is used as headers. If provided, CSV is assumed to have no header row. **kwargs Additional arguments passed to csv.reader
Returns¶
Block A new Block instance with data from the CSV file
Examples¶
Read from StringIO:
from io import StringIO csv_data = StringIO("x,y,z\n0,1,2\n3,4,5") block = Block.from_csv(csv_data) block["x"] array([0, 3]) block.nrows 2
CSV without header:
csv_no_header = StringIO("0,1,2\n3,4,5") block = Block.from_csv(csv_no_header, header=["x", "y", "z"]) list(block.keys()) ['x', 'y', 'z'] block.nrows 2
from_dict
classmethod
¶
Create a Block from a dict or alias a molrs.Block.
When data is already a cls instance, it is returned as-is.
When data is a bare molrs.Block, the returned block aliases
it: numeric read/write operations route through data (so this
is a live view of data's storage — useful for the
frame[key][col] = arr write-through idiom).
iterrows ¶
Iterate over rows of the block.
Returns¶
Iterator[tuple[int, dict[str, Any]]] An iterator yielding (index, row_data) pairs.
itertuples ¶
rename ¶
Rename a column key in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_key
|
str
|
Existing column name. |
required |
new_key
|
str
|
New column name. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If old_key does not exist. |
sort ¶
Sort the block by a specific variable and return a new sorted Block.
This method creates a new Block instance with sorted data, leaving the original Block unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The variable name to sort by. |
required |
reverse
|
bool
|
If True, sort in descending order. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Block
|
A new Block with sorted data. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the key variable doesn't exist in the block. |
ValueError
|
If any variable has different length than the key variable. |
sort_ ¶
Sort the block in-place by a specific variable.
This method modifies the current Block instance by sorting all variables according to the specified key. The original data is overwritten.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The variable name to sort by. |
required |
reverse
|
bool
|
If True, sort in descending order. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Self
|
Self (for method chaining). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the key variable doesn't exist in the block. |
ValueError
|
If any variable has different length than the key variable. |
Frame ¶
Bases: Frame
Hierarchical numerical data container with named blocks.
Inherits molrs.Frame directly: a molpy.Frame IS-A
molrs.Frame and is accepted by every molrs.* API that takes
a frame, with no conversion bridge.
Python-only state lives on the subclass __dict__:
metadata: dict[str, Any]— molpy-side annotations (timestep,description, …) invisible to the Rust slot._block_objects: dict[str, dict[str, np.ndarray]]— per-block cache of object-dtype columns (string arrays etc.) that have no Rust representation; reattached on__getitem__.
The box getter still upgrades molrs.Box → molpy.Box so
callers keep molpy's enriched Box API (factories, lengths/angles,
PBC helpers).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
blocks
|
dict[str, Block | dict] | None
|
Initial blocks. |
None
|
**props
|
Any
|
Arbitrary keyword arguments stored in metadata. |
{}
|
Examples:
Create Frame and add data blocks:
>>> frame = Frame()
>>> frame["atoms"] = Block({"x": [0.0, 1.0], "y": [0.0, 0.0], "z": [0.0, 0.0]})
>>> frame["atoms"]["x"]
array([0., 1.])
>>> frame["atoms"].nrows
2
Initialize with nested dictionaries:
>>> frame = Frame(blocks={
... "atoms": {"id": [1, 2, 3], "type": ["C", "H", "H"]},
... "bonds": {"atomi": [0, 0], "atomj": [1, 2]}
... })
>>> list(frame._blocks)
['atoms', 'bonds']
>>> frame["atoms"]["id"]
array([1, 2, 3])
Add metadata:
>>> frame = Frame()
>>> frame.metadata["timestep"] = 0
>>> frame.metadata["description"] = "Test system"
>>> frame.metadata["timestep"]
0
>>> frame.metadata["description"]
'Test system'
copy ¶
Create a deep copy of the Frame.
Returns:
| Name | Type | Description |
|---|---|---|
Frame |
Frame
|
A new Frame with copied blocks and metadata. |
from_dict
classmethod
¶
Create a Frame from a dict or upgrade a molrs.Frame.
When data is already a cls instance it is returned as-is.
When data is a bare molrs.Frame, each block is copied into
a fresh cls instance; meta (if any) flows into
metadata.
to_dict ¶
Convert Frame to a dictionary representation.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Dictionary containing "blocks" and "metadata" keys. |
Topology¶
topology ¶
Molecular topology graph using igraph.
Provides graph-based representation of molecular connectivity with automated detection of angles, dihedrals, and impropers.
Topology ¶
Bases: Graph
Topology graph with bidirectional entity-to-index mapping.
Attributes:
| Name | Type | Description |
|---|---|---|
entity_to_idx |
dict[Any, int]
|
Dictionary mapping Entity objects to their vertex indices |
idx_to_entity |
list[Any]
|
List mapping vertex indices to Entity objects |
Initialize Topology graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Arguments passed to igraph.Graph.init. |
()
|
entity_to_idx
|
dict[Any, int] | None
|
Optional dictionary mapping entities to indices. |
None
|
idx_to_entity
|
list[Any] | None
|
Optional list mapping indices to entities. |
None
|
**kwargs
|
Any
|
Keyword arguments passed to igraph.Graph.init. |
{}
|
Trajectory¶
trajectory ¶
CustomStrategy ¶
Bases: SplitStrategy
Split trajectory using a custom function.
Allows users to define their own splitting logic by providing a function that returns split point indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
split_func
|
Callable[[Trajectory], list[int]]
|
A function that takes a Trajectory and returns a list of split indices. The first index should be 0, and the last should be the total frame count. |
required |
Examples:
>>> def custom_split(traj):
... # Split at frames 0, 5, 10, 15
... return [0, 5, 10, 15]
>>> strategy = CustomStrategy(custom_split)
>>> splitter = TrajectorySplitter(traj)
>>> segments = splitter.split(strategy)
get_split_indices ¶
Get split indices using the custom function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: List of split point indices from the custom function. |
FrameIntervalStrategy ¶
Bases: SplitStrategy
Split trajectory at regular frame intervals.
Splits the trajectory every N frames, creating segments of equal size (except possibly the last segment).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
int
|
Number of frames per segment. Must be positive. |
required |
Examples:
>>> traj = Trajectory([Frame() for _ in range(10)])
>>> strategy = FrameIntervalStrategy(interval=3)
>>> splitter = TrajectorySplitter(traj)
>>> segments = splitter.split(strategy)
>>> len(segments) # Creates segments of 3, 3, 3, and 1 frames
4
get_split_indices ¶
Get split indices at regular frame intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: List of split point indices. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the trajectory doesn't have a known length. |
SplitStrategy ¶
Bases: ABC
Abstract base class for trajectory splitting strategies.
Subclasses implement different strategies for dividing a trajectory into segments based on various criteria (frame count, time intervals, etc.).
get_split_indices
abstractmethod
¶
Get split point indices for dividing the trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: List of indices where the trajectory should be split. The first index should be 0, and the last should be the total number of frames. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Must be implemented by subclasses. |
TimeIntervalStrategy ¶
Bases: SplitStrategy
Split trajectory by time intervals.
Splits the trajectory based on time information stored in frame metadata. Frames must have a "time" key in their metadata dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Time interval for splitting (in the same units as frame time metadata). Must be positive. |
required |
Examples:
>>> frames = [Frame() for _ in range(10)]
>>> for i, frame in enumerate(frames):
... frame.metadata["time"] = i * 0.1 # 0.0, 0.1, 0.2, ...
>>> traj = Trajectory(frames)
>>> strategy = TimeIntervalStrategy(interval=0.5)
>>> splitter = TrajectorySplitter(traj)
>>> segments = splitter.split(strategy)
get_split_indices ¶
Get split indices based on time intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. Frames should have "time" in metadata. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: List of split point indices based on time intervals. |
Note
Frames without time information are skipped. The first frame with time information is used as the reference start time.
Trajectory ¶
A sequence of molecular frames with optional topology.
Trajectory is a container for a sequence of Frame objects, supporting both eager (Sequence) and lazy (Iterable/Generator) frame storage. It provides iteration, indexing, slicing, and mapping operations.
Attributes:
| Name | Type | Description |
|---|---|---|
_frames |
Iterable[Frame]
|
The underlying frame sequence. Can be a Sequence (list, tuple) for random access, or an Iterable (generator) for lazy loading. |
_topology |
Topology | None
|
Optional topology information shared across all frames in the trajectory. |
Examples:
Create from a list of frames:
>>> frames = [Frame(), Frame(), Frame()]
>>> traj = Trajectory(frames)
>>> len(traj)
3
>>> traj[0] # Access first frame
Frame(...)
Create from a generator (lazy loading):
>>> def frame_generator():
... for i in range(10):
... yield Frame()
>>> traj = Trajectory(frame_generator())
>>> # Can iterate but not index
>>> for frame in traj:
... pass
Slice a trajectory:
Map a function over frames:
>>> def center_frame(frame):
... # Center coordinates at origin
... atoms = frame["atoms"]
... xyz = atoms[["x", "y", "z"]]
... center = xyz.mean(axis=0)
... atoms["x"] = atoms["x"] - center[0]
... atoms["y"] = atoms["y"] - center[1]
... atoms["z"] = atoms["z"] - center[2]
... return frame
>>> centered_traj = traj.map(center_frame)
Initialize trajectory with frames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
Iterable[Frame]
|
An iterable or sequence of Frame objects. If a Sequence is provided, the trajectory supports length and indexing. If an Iterable (e.g., generator) is provided, only iteration is supported. |
required |
topology
|
Topology | None
|
Optional topology information for the trajectory. Defaults to None. |
None
|
has_length ¶
Check if this trajectory has a known length without computing it.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the trajectory supports len(), False otherwise. |
Examples:
map ¶
Apply a function to each frame, returning a new trajectory.
The mapping is applied lazily - the function is only called when frames are accessed, making it memory-efficient for large trajectories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[[Frame], Frame]
|
A function that takes a Frame and returns a Frame. The function will be applied lazily as frames are accessed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Trajectory |
Trajectory
|
A new Trajectory with mapped frames. The original trajectory is not modified. |
Examples:
>>> traj = Trajectory([Frame(), Frame()])
>>> def center_frame(frame):
... # Center coordinates at origin
... atoms = frame["atoms"]
... xyz = atoms[["x", "y", "z"]]
... center = xyz.mean(axis=0)
... atoms["x"] = atoms["x"] - center[0]
... atoms["y"] = atoms["y"] - center[1]
... atoms["z"] = atoms["z"] - center[2]
... return frame
>>> centered_traj = traj.map(center_frame)
>>> len(centered_traj)
2
TrajectorySplitter ¶
Splits trajectories into lazy segments.
Provides a convenient interface for splitting trajectories using various strategies. The resulting segments are lazy Trajectory objects that share the same topology as the original.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
Examples:
>>> traj = Trajectory([Frame() for _ in range(100)])
>>> splitter = TrajectorySplitter(traj)
>>> # Split every 10 frames
>>> segments = splitter.split_frames(interval=10)
>>> len(segments)
10
>>> len(segments[0])
10
Initialize the splitter with a trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trajectory
|
Trajectory
|
The trajectory to split. |
required |
split ¶
Split trajectory using a strategy, returning lazy segments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy
|
SplitStrategy
|
The splitting strategy to use. |
required |
Returns:
| Type | Description |
|---|---|
list[Trajectory]
|
list[Trajectory]: List of trajectory segments. Each segment is a new Trajectory containing a subset of frames from the original. |
Examples:
split_frames ¶
Convenience method for frame-based splitting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
int
|
Number of frames per segment. |
required |
Returns:
| Type | Description |
|---|---|
list[Trajectory]
|
list[Trajectory]: List of trajectory segments. |
Examples:
split_time ¶
Convenience method for time-based splitting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Time interval for splitting (in frame time units). |
required |
Returns:
| Type | Description |
|---|---|
list[Trajectory]
|
list[Trajectory]: List of trajectory segments. |
Examples:
Coarse-Grain¶
cg ¶
Coarse-grained molecular structure.
Mirrors :mod:molpy.core.atomistic in shape and contract; see
:doc:../specs/cg-atomistic-mapping-redesign for the design rationale.
Conventional dict keys (none enforced):
bead["atoms"]—tuple[Atom, ...]of atom references this bead represents (when projected from an :class:Atomistic). Required only by :meth:CoarseGrain.beads_of.bead["x"],bead["y"],bead["z"]— primary position; consumed by :class:SpatialMixinformove/rotate/scale/align.bead["type"],bead["mass"],bead["charge"]— as needed.
Bead ¶
Bases: Entity
Coarse-grained bead.
Structurally identical to :class:~molpy.core.atomistic.Atom: a dict-like
:class:Entity with no mandatory fields. All bead state lives in the
underlying dict.
See module docstring for the optional convention keys recognised by
:class:CoarseGrain and the spatial mixin.
CGBond ¶
Bases: Link
Coarse-grained bond between two beads.
Parallel to :class:~molpy.core.atomistic.Bond: a :class:Link carrying
two :class:Bead endpoints plus arbitrary attributes.
Initialise a CG bond between two beads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Bead
|
First bead endpoint. |
required |
b
|
Bead
|
Second bead endpoint. |
required |
**attrs
|
Any
|
Additional bond attributes. |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If |
CoarseGrain ¶
Bases: Struct, MembershipMixin, SpatialMixin, ConnectivityMixin, Graph
Coarse-grained molecular structure.
Public surface mirrors :class:~molpy.core.atomistic.Atomistic 1:1
except for the single extra method :meth:beads_of. The class makes no
assumption about the existence, source, or definition of bead positions,
masses, or atom-level provenance — those are dict-key conventions
documented at module level.
Initialise an empty coarse-grained structure.
Registers buckets for :class:Bead and :class:CGBond. If the
concrete subclass defines a __post_init__ method, it is called
with the same keyword arguments (template pattern, parallel to
:class:Atomistic).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**props
|
Any
|
Arbitrary properties stored on the structure (e.g.,
|
{}
|
add_bead ¶
add_beads ¶
add_cgbond ¶
add_cgbonds ¶
align ¶
Align beads via a vector pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Entity
|
Source entity defining the start of the alignment vector. |
required |
b
|
Entity
|
Target entity defining the end of the alignment vector. |
required |
a_dir
|
list[float] | None
|
Optional source direction |
None
|
b_dir
|
list[float] | None
|
Optional target direction |
None
|
flip
|
bool
|
If |
False
|
entity_type
|
type[Entity]
|
Entity subclass to transform (default :class: |
Bead
|
Returns:
| Type | Description |
|---|---|
'CoarseGrain'
|
|
beads_of ¶
Return all beads whose bead["atoms"] contains atom.
Justified as a core method by the same standard as :meth:move:
operates on a single conventional key ("atoms") and has no
second reasonable implementation. Beads without an "atoms"
key are skipped silently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom
|
'Atom'
|
The atom to look up. |
required |
Returns:
| Type | Description |
|---|---|
Bead
|
Tuple of beads referencing |
...
|
if the mapping has overlap. |
Note
O(N_beads × ⟨|atoms|⟩); no caching. Callers needing speed
should build their own id(atom) → list[Bead] index.
def_bead ¶
Create a new :class:Bead and register it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**attrs
|
Any
|
Bead attributes (any keys; see module docstring for conventional keys). |
{}
|
Returns:
| Type | Description |
|---|---|
Bead
|
The newly registered Bead. |
def_beads ¶
Create multiple beads from a list of attribute dicts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
beads_data
|
list[dict[str, Any]]
|
List of attribute dicts; each dict is forwarded as
|
required |
Returns:
| Type | Description |
|---|---|
list[Bead]
|
List of newly registered beads, one per input dict. |
def_cgbond ¶
Create a new :class:CGBond between two beads and register it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Bead
|
First bead endpoint. |
required |
b
|
Bead
|
Second bead endpoint. |
required |
**attrs
|
Any
|
Additional bond attributes (e.g., |
{}
|
Returns:
| Type | Description |
|---|---|
CGBond
|
The newly registered CG bond. |
def_cgbonds ¶
Create multiple CG bonds from (a, b) or (a, b, attrs) tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bonds_data
|
list[tuple[Bead, Bead] | tuple[Bead, Bead, dict[str, Any]]]
|
Iterable of bond specifications. Each item is either
a 2-tuple |
required |
Returns:
| Type | Description |
|---|---|
list[CGBond]
|
List of newly registered CG bonds, one per input tuple. |
del_bead ¶
Remove beads (and their incident CG bonds).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*beads
|
Bead
|
One or more :class: |
()
|
del_cgbond ¶
Remove CG bonds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*bonds
|
CGBond
|
One or more :class: |
()
|
move ¶
Translate every bead by delta.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta
|
list[float]
|
Translation vector |
required |
entity_type
|
type[Entity]
|
Entity subclass to translate (default :class: |
Bead
|
Returns:
| Type | Description |
|---|---|
'CoarseGrain'
|
|
rename_type ¶
Rename all beads/bonds of kind whose type equals old.
Returns:
| Type | Description |
|---|---|
int
|
Number of items renamed. |
replicate ¶
Replicate self n times into a new structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of copies. |
required |
transform
|
Callable[['CoarseGrain', int], None] | None
|
Optional callable |
None
|
Returns:
| Type | Description |
|---|---|
'CoarseGrain'
|
A new :class: |
rotate ¶
Rotate beads around axis by angle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
list[float]
|
Rotation axis |
required |
angle
|
float
|
Rotation angle in radians. |
required |
about
|
list[float] | None
|
Optional pivot point |
None
|
entity_type
|
type[Entity]
|
Entity subclass to rotate (default :class: |
Bead
|
Returns:
| Type | Description |
|---|---|
'CoarseGrain'
|
|
scale ¶
Scale bead positions by factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor
|
float
|
Uniform scaling factor (dimensionless). |
required |
about
|
list[float] | None
|
Optional pivot point |
None
|
entity_type
|
type[Entity]
|
Entity subclass to scale (default :class: |
Bead
|
Returns:
| Type | Description |
|---|---|
'CoarseGrain'
|
|
select ¶
Return a new CoarseGrain containing beads matching predicate.
Bonds whose endpoints are both inside the selection are carried over.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicate
|
Callable[[Bead], bool]
|
Callable |
required |
Returns:
| Type | Description |
|---|---|
'CoarseGrain'
|
A new :class: |
'CoarseGrain'
|
bonds whose endpoints are entirely within the selection. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
set_property ¶
Set a property on every bead (or link) matching selector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selector
|
Callable[[Bead], bool]
|
Callable |
required |
key
|
str
|
Attribute key to assign on matching items. |
required |
value
|
Any
|
Value to assign. |
required |
kind
|
type
|
Item class to iterate over (default :class: |
Bead
|
Returns:
| Type | Description |
|---|---|
int
|
Number of items modified. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
to_frame ¶
Convert this CoarseGrain into a :class:Frame.
Mirrors :meth:molpy.core.atomistic.Atomistic.to_frame. Beads are
flattened into a "beads" :class:Block (struct-of-arrays);
CG bonds, when present, become a "cgbonds" block carrying
integer endpoint indices ibead / jbead plus any remaining
bond attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bead_fields
|
list[str] | None
|
Optional whitelist of bead dict keys to extract.
If |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
'Frame'
|
class: |
'Frame'
|
exist) a |
|
'Frame'
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a CG bond references a bead that is not registered in this structure. |
Config¶
config ¶
Global configuration system for MolPy.
This module provides a thread-safe singleton configuration system using Pydantic. Configuration can be accessed globally, updated, reset, or temporarily overridden using a context manager.
Examples:
>>> from molpy.core.config import config, Config
>>>
>>> # Access current config
>>> print(config.log_level)
'INFO'
>>>
>>> # Update config globally
>>> Config.update(log_level='DEBUG', n_threads=4)
>>>
>>> # Temporary override
>>> with Config.temporary(log_level='WARNING'):
... print(config.log_level) # 'WARNING'
>>> print(config.log_level) # Back to 'DEBUG'
Config ¶
Bases: BaseModel
Global configuration for MolPy.
Thread-safe singleton that stores global settings like logging level and parallelization parameters. Use class methods to access and modify the singleton instance.
Attributes:
| Name | Type | Description |
|---|---|---|
log_level |
str
|
Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
n_threads |
int
|
Number of threads for parallel computations |
Examples:
>>> # Get singleton instance
>>> cfg = Config.instance()
>>>
>>> # Update configuration
>>> Config.update(n_threads=8)
>>>
>>> # Temporary override
>>> with Config.temporary(log_level='DEBUG'):
... # Config is DEBUG here
... pass
>>> # Config restored here
instance
classmethod
¶
reset
classmethod
¶
temporary
classmethod
¶
Temporarily override configuration within a context.
Thread-safe context manager that restores original config on exit. Useful for testing or temporary parameter changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**overrides
|
Any
|
Configuration fields to temporarily override. |
{}
|
Yields:
| Type | Description |
|---|---|
None
|
None |
Examples:
update
classmethod
¶
Update the global configuration.
Thread-safe update that creates a new instance with updated values. Changes persist until reset() or another update().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Configuration fields to update (log_level, n_threads, etc.). |
{}
|
Examples:
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 |