I/O¶
File readers and writers for molecular data, force fields, and trajectories.
Quick reference¶
Data files¶
| Function | Format | Direction |
|---|---|---|
read_pdb / write_pdb |
PDB | read/write |
read_lammps_data / write_lammps_data |
LAMMPS data | read/write |
read_gro / write_gro |
GROMACS GRO | read/write |
read_mol2 |
MOL2 | read |
read_xyz |
XYZ | read |
XsfReader / XsfWriter |
XSF (crystallographic) | read/write |
read_amber_inpcrd |
AMBER inpcrd | read |
Force fields¶
| Function | Format | Direction |
|---|---|---|
read_xml_forcefield |
OpenMM/OPLS XML | read |
XMLForceFieldWriter |
OpenMM/OPLS XML | write |
read_lammps_forcefield |
LAMMPS *.ff include |
read |
write_lammps_forcefield / LAMMPSForceFieldWriter |
LAMMPS *.ff include |
write (engine units → LAMMPS real) |
GromacsForceFieldWriter |
GROMACS.itp | write |
read_amber |
AMBER prmtop + inpcrd | read |
Trajectories¶
| Function | Format | Direction |
|---|---|---|
read_lammps_trajectory |
LAMMPS dump | read (lazy) |
read_xyz_trajectory |
XYZ trajectory | read (lazy) |
Logs¶
| Function | Format | Direction |
|---|---|---|
read_LAMMPS_log |
LAMMPS log | read |
Canonical examples¶
# docs: skip — reads offline artifact files; I/O unit-tested with fixtures
import molpy as mp
# Read/write structure
frame = mp.io.read_pdb("molecule.pdb")
mp.io.write_lammps_data("system.data", frame, atom_style="full")
# Read force field (XML or LAMMPS *.ff)
ff = mp.io.read_xml_forcefield(mp.data.get_forcefield_path("oplsaa.xml"))
ff = mp.io.read_lammps_forcefield("system.ff")
# Write LAMMPS *.ff (; optional type filter)
mp.io.write_lammps_forcefield("system.ff", ff)
from molpy.io.forcefield import LAMMPSForceFieldWriter
LAMMPSForceFieldWriter("system.ff").write(ff, atom_types={"CT", "HC"})
# Read trajectory (lazy)
traj = mp.io.read_lammps_trajectory("dump.lammpstrj")
for frame in traj:
process(frame)
# Read LAMMPS run output
log = mp.io.read_LAMMPS_log("log.lammps")
thermo = log.runs[0].thermo
print(thermo.columns)
# Write full LAMMPS system (data + ff)
mp.io.write_lammps_system("output_dir", frame, ff)
Related¶
Full API¶
Factory Functions¶
readers ¶
Data file reader factory functions.
This module provides convenient factory functions for creating various data file readers. All functions return Frame objects by populating an optional frame parameter.
read_LAMMPS_log ¶
Read a LAMMPS log file and return a nested dataclass result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to LAMMPS log file |
required |
Returns:
| Type | Description |
|---|---|
LAMMPSLog
|
Parsed |
read_amber ¶
Read AMBER prmtop and optional inpcrd files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prmtop
|
PathLike
|
Path to AMBER prmtop file |
required |
inpcrd
|
PathLike | None
|
Optional path to AMBER inpcrd file |
None
|
frame
|
Any
|
Optional existing Frame to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Tuple of (Frame, ForceField) |
read_amber_ac ¶
Read AC file and return a Frame object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to AC file |
required |
frame
|
Any
|
Optional existing Frame to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Populated Frame object |
read_amber_frcmod ¶
Read an AMBER FRCMOD file.
FRCMOD files contain additional force field parameters generated by parmchk2.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to FRCMOD file |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with sections: 'remark', 'mass', 'bond', 'angle', 'dihe', |
dict[str, Any]
|
'improper', 'nonbon', and 'raw_text'. |
read_amber_inpcrd ¶
Read AMBER inpcrd file and return a Frame object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inpcrd
|
PathLike
|
Path to AMBER inpcrd file |
required |
frame
|
Any
|
Optional existing Frame to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Populated Frame object |
read_dcd_trajectory ¶
Read a DCD trajectory and return a lazy trajectory reader.
Backed by the molrs Rust lazy reader (O(1) random access by frame index).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to a |
required |
Returns:
| Type | Description |
|---|---|
Any
|
molrs |
read_gro ¶
Read a GROMACS GRO file (molrs); returns the first frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to |
required |
frame
|
Any
|
Accepted for API parity; ignored. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
class: |
read_lammps_data ¶
Read a LAMMPS data file and return its explicit parse products.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to LAMMPS data file |
required |
atom_style
|
str
|
LAMMPS atom style (e.g., 'full', 'atomic') |
required |
frame
|
Any
|
Optional existing Frame to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
|
read_lammps_forcefield ¶
Read a LAMMPS force-field include (*.ff) into a ForceField.
Delegates to the native molrs reader (molrs.ff.read_lammps_forcefield),
which parses the include directly into a molrs.ff.ForceField in molrs units
(Å, kcal/mol, radians, e): LAMMPS harmonic K → molrs k = 2K, angle
and dihedral-phase values are converted degrees → radians, and
dihedral_style fourier
maps to the molrs periodic kernel. AMBER 1-4 scaling is recorded on the
force field's special bonds. Per-atom charge and mass live in the LAMMPS
data file, not this include, so they are not read here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scripts
|
PathLike | list[PathLike]
|
Path (or list of paths) to LAMMPS force-field include(s). A list is concatenated and parsed as a single document. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
read_lammps_molecule ¶
Read LAMMPS molecule file and return a Frame object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to LAMMPS molecule file |
required |
frame
|
Any
|
Optional existing Frame to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Populated Frame object |
read_lammps_trajectory ¶
Read LAMMPS trajectory file and return a trajectory reader.
Backed by the molrs Rust lazy reader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
traj
|
PathLike
|
Path to LAMMPS trajectory file |
required |
Returns:
molrs TrajectoryReader object
read_mol2 ¶
Read a Tripos MOL2 file (molrs; first molecule).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to a |
required |
frame
|
Any
|
Accepted for API parity; ignored (molrs returns a new Frame). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Canonical |
Any
|
class: |
read_pdb ¶
Read a PDB file (molrs); CONECT pairs are de-duplicated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to PDB file. |
required |
frame
|
Any
|
Accepted for API parity; ignored (molrs returns a new Frame). |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
class: |
read_pdb_trajectory ¶
Read every model of a (multi-frame) PDB file as a list of Frames.
Each MODEL/END-delimited block becomes one Frame. A single-model PDB
yields a one-element list. Backed by the molrs Rust reader.
read_smiles ¶
Parse a single-component SMILES string into an :class:Atomistic.
Connectivity only: hydrogens implicit in the SMILES are not added, and
no coordinates are generated. Filling open valences is a separate
perception step (mp.Perceive().find_hydrogens(mol)), and 3D embedding a
separate conformer step — :class:~molpy.io.SmilesReader composes all
three when you want the finished molecule.
This is an io entry point, not a constructor on the graph. A SMILES string is a file format, and the layering runs io → core: a core type that could parse one would make the graph depend on the parser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
A SMILES string naming exactly one connected molecule. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The parsed graph. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
Examples:
read_top ¶
Read GROMACS topology file and return a ForceField object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to GROMACS .top file |
required |
forcefield
|
Any
|
Optional existing ForceField to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Populated ForceField object |
read_trr_trajectory ¶
Read a GROMACS TRR trajectory and return a lazy trajectory reader.
Backed by the molrs Rust lazy reader (single/double precision, coordinates plus velocities/forces when present; O(1) random access).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to a |
required |
Returns:
| Type | Description |
|---|---|
Any
|
molrs |
read_xsf ¶
Read XSF file and return a Frame object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to XSF file |
required |
frame
|
Any
|
Optional existing Frame to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Populated Frame object |
read_xtc_trajectory ¶
Read a GROMACS XTC (compressed) trajectory and return a lazy reader.
Backed by the molrs Rust lazy reader (lossy compression; accepts classic 1995 and 2023 magic; O(1) random access after a one-time index scan).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to a |
required |
Returns:
| Type | Description |
|---|---|
Any
|
molrs |
read_xyz ¶
Read an XYZ file (molrs) with molpy column normalization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to XYZ file. |
required |
frame
|
Any
|
Accepted for API parity; ignored. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
class: |
read_xyz_trajectory ¶
Read XYZ trajectory file and return a trajectory reader.
Backed by the molrs Rust lazy reader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to XYZ trajectory file |
required |
Returns:
| Type | Description |
|---|---|
Any
|
molrs |
write_smarts ¶
write_smarts(
mol,
center,
*,
reach=1,
atomic_number=True,
include_degree=True,
include_h_count=True,
include_charge=True,
include_aromatic=True,
include_ring_membership=False,
include_ring_size=False,
include_explicit_h_atoms=False,
include_bond_orders=True,
neighbor_style="chain",
canonical_neighbor_order=True,
)
Encode the local topology around center as a SMARTS string.
Thin wrap of molrs.io.write_smarts. Science flags match the molrs
LocalSmartsOptions surface. This is an io entry — not a method on
:class:~molpy.core.atomistic.Atomistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol
|
Any
|
molpy :class: |
required |
center
|
Any
|
Atom view ( |
required |
reach
|
int
|
Bond radius of the local ball (must be >= 1). |
1
|
atomic_number
|
bool
|
Use |
True
|
include_degree
|
bool
|
Add Daylight |
True
|
include_h_count
|
bool
|
Add |
True
|
include_charge
|
bool
|
Add formal charge when nonzero. |
True
|
include_aromatic
|
bool
|
Mark aromatic atoms / bonds. |
True
|
include_ring_membership
|
bool
|
Add ring-count primitives. |
False
|
include_ring_size
|
bool
|
Add smallest-ring size. |
False
|
include_explicit_h_atoms
|
bool
|
Keep explicit hydrogens in the ball. |
False
|
include_bond_orders
|
bool
|
Emit |
True
|
neighbor_style
|
str
|
|
'chain'
|
canonical_neighbor_order
|
bool
|
Sort neighbors by canonical atom order. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
A SMARTS string that matches |
options: members: true filters: - "!^Base"
writers ¶
Data file writer factory functions.
This module provides convenient factory functions for creating various data file writers. All functions write Frame or ForceField objects to files.
write_amber_frcmod ¶
write_amber_frcmod(
file,
*,
remark="",
mass="",
bond="",
angle="",
dihe="",
improper="",
nonbon="",
)
Write an AMBER FRCMOD file.
FRCMOD files contain additional force field parameters. This function creates a properly formatted file with the provided sections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
remark
|
str
|
Optional comment/remark line |
''
|
mass
|
str
|
MASS section content |
''
|
bond
|
str
|
BOND section content |
''
|
angle
|
str
|
ANGLE section content |
''
|
dihe
|
str
|
DIHEDRAL section content |
''
|
improper
|
str
|
IMPROPER section content |
''
|
nonbon
|
str
|
NONBON section content |
''
|
write_bond_react_map ¶
Write the .map file for a LAMMPS fix bond/react template.
Thin factory over :class:~molpy.io.data.lammps_bond_react.LammpsBondReactWriter,
matching the write_* convention the rest of this module uses.
write_dcd_trajectory ¶
Write frames to a NAMD-compatible DCD trajectory (molrs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output |
required |
frames
|
list
|
Frames with equal atom counts; box presence must be consistent. |
required |
write_lammps_bond_react_system ¶
Write a complete LAMMPS fix bond/react system.
Produces all files needed for a reactive MD simulation:
{stem}.data— system configuration{stem}.ff— force field coefficients{name}_pre.mol/{name}_post.mol— reaction templates{name}.map— atom equivalence maps
Type numbering is unified across the system and all templates so
that fix bond/react can match atom types correctly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workdir
|
PathLike
|
Output directory (created if missing). |
required |
frame
|
Any
|
Packed system Frame. |
required |
forcefield
|
Any
|
ForceField object. |
required |
templates
|
dict[str, Any] | Sequence[Any]
|
Either a |
required |
Example::
mp.io.write_lammps_bond_react_system(
"output", packed_frame, ff,
templates={"rxn1": template},
)
write_lammps_data ¶
Write a Frame to a LAMMPS data file (structure only).
Structure / topology / Masses / type labels go through molrs after the
writer stamps type_id from Frame columns. Force-field * Coeffs are
a separate step — use :func:write_lammps_data_coeffs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path. |
required |
frame
|
Any
|
Frame with |
required |
atom_style
|
str
|
Accepted for API parity (style is inferred from columns). |
'full'
|
type_labels
|
dict[str, list[str]] | None
|
Optional extra unused-type inventory only. |
None
|
write_lammps_data_coeffs ¶
Insert * Coeffs into an existing LAMMPS data file.
Type ids come from the Frame; form map and units conversion live in molrs. Typical composition::
ff.map_type(frame)
write_lammps_data(path, frame)
write_lammps_data_coeffs(path, frame, ff)
write_lammps_forcefield ¶
write_lammps_forcefield(
file,
forcefield,
precision=6,
skip_pair_style=False,
frame=None,
*,
units="real",
)
Write a ForceField object to a LAMMPS force field file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
forcefield
|
Any
|
ForceField object to write |
required |
precision
|
int
|
Number of decimal places for floating point values |
6
|
skip_pair_style
|
bool
|
If True, omit the |
False
|
frame
|
Any
|
When given, restrict emitted coeffs to the types the frame actually uses — so a force field carrying extra types (e.g. cap artifacts from region parameterisation) does not emit a coeff for a type absent from the data file's labelmap (which LAMMPS rejects). |
None
|
units
|
str
|
LAMMPS |
'real'
|
write_lammps_molecule ¶
Write a Frame object to a LAMMPS molecule file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
frame
|
Any
|
Frame object to write |
required |
format_type
|
str
|
Format type (default: 'native') |
'native'
|
write_lammps_system ¶
Write a complete LAMMPS system (data + forcefield) to a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workdir
|
PathLike
|
Output directory path |
required |
frame
|
Any
|
Frame object containing structure |
required |
forcefield
|
Any
|
ForceField object containing parameters |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Path]
|
Dict with keys |
write_lammps_trajectory ¶
Write frames to a LAMMPS dump trajectory (molrs).
Each frame must have box. Optional frame.meta['timestep'] is written
as ITEM: TIMESTEP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path. |
required |
frames
|
list
|
Sequence of Frame objects. |
required |
atom_style
|
str
|
Accepted for API parity; ignored by molrs (columns from frame). |
'full'
|
write_top ¶
Write a Frame object to a GROMACS topology file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
frame
|
Any
|
Frame object to write |
required |
write_trr ¶
Write frames to a GROMACS TRR trajectory (single precision).
Thin delegation to the native molrs writer. Each frame needs x/y/
z (nm); optional vx/vy/vz and fx/fy/fz are
written when present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path. |
required |
frames
|
list
|
List of Frame objects to write. |
required |
write_xsf ¶
Write a Frame object to an XSF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
frame
|
Any
|
Frame object to write |
required |
write_xtc ¶
Write frames to a GROMACS XTC (compressed) trajectory.
Thin delegation to the native molrs writer. Each frame needs x/y/
z (nm); quantization precision comes from frame.meta['precision']
when present, else 1000 (0.001 nm).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path. |
required |
frames
|
list
|
List of Frame objects to write. |
required |
write_xyz_trajectory ¶
Write frames to an XYZ trajectory file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
frames
|
list
|
List of Frame objects to write |
required |
options: members: true
ForceField Modules¶
Base¶
base ¶
Abstract base classes for force field readers and writers.
ForceFieldReader ¶
Bases: ABC
Base class for force field file readers.
read
abstractmethod
¶
Read force field data from file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forcefield
|
ForceField | None
|
Optional existing ForceField to populate. |
None
|
Returns:
| Type | Description |
|---|---|
ForceField
|
Populated ForceField object. |
ForceFieldWriter ¶
Bases: ABC
Base class for force field file writers.
write
abstractmethod
¶
Write force field data to file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forcefield
|
ForceField
|
ForceField object to serialize. |
required |
LAMMPS¶
lammps ¶
LAMMPS force-field include (*.ff) I/O.
Read/write of the AMBER/GAFF-style include is implemented in molrs
(:func:molrs.ff.read_lammps_forcefield, :func:molrs.ff.write_lammps_forcefield).
This module exposes the molpy entry points and parameter formatters for
specialized pair styles (CL&Pol Thole / Tang−Toennies).
LAMMPSForceFieldWriter ¶
Write a :class:~molpy.ForceField to a LAMMPS *.ff include.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fpath
|
str | Path | TextIO
|
Output path or file-like object. |
required |
precision
|
int
|
Decimal places for floating-point coefficients. |
6
|
units
|
str
|
LAMMPS |
'real'
|
write ¶
write(
forcefield,
atom_types=None,
bond_types=None,
angle_types=None,
dihedral_types=None,
improper_types=None,
skip_pair_style=False,
units=None,
)
Write forcefield (molrs store units) as a LAMMPS include.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forcefield
|
ForceField
|
Force field to write. |
required |
atom_types
|
set[str] | None
|
Optional atom-type whitelist for pair coeffs. |
None
|
bond_types
|
set[str] | None
|
Optional bond type-name whitelist. |
None
|
angle_types
|
set[str] | None
|
Optional angle type-name whitelist. |
None
|
dihedral_types
|
set[str] | None
|
Optional dihedral type-name whitelist. |
None
|
improper_types
|
set[str] | None
|
Optional improper type-name whitelist. |
None
|
skip_pair_style
|
bool
|
If True, omit the |
False
|
units
|
str | None
|
Override constructor |
None
|
LammpsForceFieldFormatter ¶
Bases: LammpsFieldFormatter, ForceFieldFormatter
Parameter formatters for LAMMPS pair styles beyond the AMBER/GAFF set.
XML¶
xml ¶
OpenMM / OPLS XML force-field I/O (molrs-backed).
Read: :func:molrs.ff.read_forcefield_xml / :func:molrs.ff.read_opls_xml.
Write: :func:molrs.ff.write_forcefield_xml.
AngleUnitWarning ¶
Bases: UserWarning
An angle value looks inconsistent with its declared angle_unit.
OPLSAAForceFieldReader ¶
XMLForceFieldReader ¶
Deprecated shell: prefer :func:read_xml_forcefield (molrs).
XMLForceFieldWriter ¶
Write a ForceField to OpenMM-style XML (via molrs).
read_oplsaa_forcefield ¶
Read OPLS-AA / OpenMM XML with molrs OPLS unit conversion.
read_xml_forcefield ¶
Read an OpenMM/OPLS XML force field (molrs).
write_xml_forcefield ¶
Convenience function to write a force field to XML.
GROMACS Topology¶
top ¶
GROMACS topology force-field I/O (molrs-backed).
Reader/writer unit conversion lives in
:func:molrs.ff.read_gromacs_top_ff / :func:molrs.ff.write_gromacs_top_ff.
Structure-only topology is :mod:molpy.io.data.top.
GromacsForceFieldWriter ¶
Write a ForceField to GROMACS .top / .itp (via molrs).
GromacsTopReader ¶
Read a GROMACS .top / .itp into a :class:~molpy.ForceField.
Structure tables are handled by :mod:molpy.io.data.top /
:func:molrs.io.read_top. This class owns the force-field half via
:func:molrs.ff.read_gromacs_top_ff (unit normalization at the boundary).
read ¶
Parse the topology file into a ForceField.
AMBER¶
amber ¶
AMBER prmtop I/O — thin molrs façade.
- Structure: :func:
molrs.io.read_amber_prmtop - Force field: :func:
molrs.ff.read_amber_prmtop_ff(LAMMPS form map) - Table decode (POINTERS, bonds, angles, dihedrals, LJ, 20a4 names):
:mod:
molrs.ioprmtop_*helpers — call those directly; this module does not re-export or wrap them.
AmberPrmtopReader ¶
Read AMBER prmtop structure + force field via molrs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
str | Path
|
Path to a |
required |
read ¶
Load structure and force field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
Frame | None
|
Optional destination Frame; when given, structure blocks and
meta are copied into it. When |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Frame, object]
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
Missing path. |
ValueError
|
Invalid / empty prmtop or FF parse failure. |
Data Modules¶
LAMMPS¶
lammps ¶
LAMMPS data file I/O (structure via molrs, coeffs via molrs.ff).
LammpsDataReader ¶
Bases: DataReader[LammpsDataResult]
Reader for LAMMPS data files.
read ¶
Read a LAMMPS data file into frame + forcefield products.
Structure, Type Labels, header counts, and * Coeffs text are
produced by :func:molrs.io.read_lammps_data (single pass). Coeffs
become a :class:~molpy.ForceField via
:func:molrs.ff.read_lammps_data_coeffs. This class only adapts the
molpy surface (type column, atom_style column drop, result bundle).
LammpsDataResult
dataclass
¶
Explicit products of parsing one LAMMPS data file.
LammpsDataWriter ¶
Bases: DataWriter
Structure-only LAMMPS data writer (thin molrs façade).
Structure emission is :func:molrs.io.write_lammps_data. molrs resolves
atom id (1..N when absent), type / type_id numbering, Masses
(element-preferred), and * Type Labels from the Frame. This class only:
- Optionally seeds meta with constructor
type_labels(unused-type inventory) so molrs can merge them with labels present on the Frame. - Prepends a Drude
fix drudecomment when shells are detected.
Force-field * Coeffs are not written here — call
:func:write_lammps_data_coeffs as a separate step.
Frame requirements:
- Atoms must carry type and/or type_id (and connectivity blocks
that are present must too). Prefer
:meth:~molrs.ff.forcefield.ForceField.map_type first.
- Connectivity endpoints are 0-based row indices (as from
Atomistic.to_frame()); molrs maps them to atom IDs.
Structure-only writer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output data file path. |
required |
atom_style
|
str
|
Accepted for API parity (layout from columns). |
'full'
|
type_labels
|
dict[str, list[str]] | None
|
Optional extra unused-type inventory only. Type
ids always come from the Frame ( |
None
|
write ¶
Write Frame structure to a LAMMPS data file (via molrs).
Frame must already carry type and/or type_id on atoms (and on
any connectivity blocks that are present). Force-field * Coeffs are
not written here — call :func:write_lammps_data_coeffs after.
LammpsFieldFormatter ¶
Bases: FieldFormatter
LAMMPS-specific field name translation.
Maps LAMMPS atom_style column names to canonical field names::
"q" → "charge"
"mol" → "mol_id"
write_lammps_data_coeffs ¶
Insert * Coeffs into an existing LAMMPS data file.
Type ids are taken from the Frame (type / type_id), not from a
caller-supplied inventory. Coefficient numbers (form map + units) are
produced entirely by molrs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to a data file already written by :class: |
required |
frame
|
Frame
|
Frame whose type columns define the id space (call
|
required |
forcefield
|
ForceField
|
Force field in molrs store units. |
required |
units
|
str
|
LAMMPS |
'real'
|
precision
|
int
|
Decimal places for floating coefficients. |
6
|
lammps_molecule ¶
LAMMPS molecule template I/O — molrs-backed.
Native .mol and JSON molecule files are read/written by
:func:molrs.io.read_lammps_molecule /
:func:molrs.io.write_lammps_molecule. This module is a thin façade that
keeps the historical class API and applies the LAMMPS field formatter on
read (q → charge when present).
LammpsMoleculeReader ¶
Bases: DataReader
LAMMPS molecule file reader (native or JSON by suffix).
lammps_bond_react ¶
LAMMPS fix bond/react template serialization.
A fix bond/react template is a pre-reaction subgraph, the same subgraph after
the reaction, and the atom map between them. That is an IO artifact, not
reaction machinery: it is one serialization of the local environment a graph edit
disturbed. Nothing produces it but the caller, so it lives with the writer that
consumes it.
File format references
- LAMMPS
fix bond/react: https://docs.lammps.org/fix_bond_react.html - REACTER methodology: https://www.reacter.org (Gissinger, Jensen & Wise, Polymer 128, 211-217 (2017); Macromolecules 53, 9953-9961 (2020))
BondReactTemplate
dataclass
¶
BondReactTemplate(
pre,
post,
initiator_atoms,
edge_atoms,
deleted_atoms,
pre_react_id_to_atom,
post_react_id_to_atom,
)
The pre/post subgraph pair fix bond/react needs, plus its atom map.
Serialized into {name}_pre.mol, {name}_post.mol and {name}.map.
Attributes:
| Name | Type | Description |
|---|---|---|
pre |
Atomistic
|
Pre-reaction subgraph (the local environment before the edit). |
post |
Atomistic
|
Post-reaction subgraph (same atoms, new topology). |
initiator_atoms |
list[Atom]
|
The pair of atoms that trigger the reaction
(LAMMPS |
edge_atoms |
list[Atom]
|
Boundary atoms bonded to topology outside the template
(LAMMPS |
deleted_atoms |
list[Atom]
|
Atoms the reaction removes (LAMMPS |
pre_react_id_to_atom |
dict
|
|
post_react_id_to_atom |
dict
|
|
assign_atom_ids ¶
Assign deterministic 1-based id values to the pre/post atoms.
Insertion order defines the template-local indices the .map file
uses, so writers call this before serializing.
LammpsBondReactWriter ¶
Serialize a :class:BondReactTemplate into the files LAMMPS reads.
The .map file is purely topological and independent of type numbering.
The unified type maps, by contrast, must be shared between the system data
file and every template, which is what lets fix bond/react match template
atoms against the system.
apply_type_maps
staticmethod
¶
Resolve string type labels to unified numeric type_ids, in place.
The number goes in type_id, which is what the Frame vocabulary calls
a numeric type ordinal; type keeps the labels it was given. The IDs
must match the system data file for template matching.
Rows whose type is absent from the mapping (boundary topology with untyped terms) are dropped with a warning.
collect_type_maps
staticmethod
¶
Build unified string-type → 1-based ID mappings across frames.
Scans the type column of every topology section in every frame, keeps
named types (skipping empty strings, "None" placeholders, and purely
numeric labels that are already IDs), sorts them, and assigns 1-based
integer IDs.
Returns:
| Type | Description |
|---|---|
dict[str, list[str]]
|
|
dict[str, dict[str, int]]
|
( |
tuple[dict[str, list[str]], dict[str, dict[str, int]]]
|
section names ( |
write_map ¶
Write {base_path}.map.
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
PDB¶
pdb ¶
PDB file I/O — molrs-backed.
Read: :func:molrs.io.read_pdb plus undirected CONECT de-duplication.
Write: :func:molrs.io.write_pdb on canonical columns. Thin prep only:
inject element from frame.meta['elements'] when the column is absent.
GRO¶
gro ¶
GROMACS .gro file I/O — thin molrs wrappers.
Parse/serialize live in :mod:molrs.io. :class:GroFieldFormatter documents
format-native names for the FieldFormatter hierarchy (no separate Python parser).
Mol2¶
mol2 ¶
Tripos MOL2 structure I/O (molrs-backed).
Read/write go through :func:molrs.io.read_mol2 / :func:molrs.io.write_mol2.
Canonical column names: type (SYBYL atom type), res_id/res_name
(from subst_*).
Mol2Reader ¶
Bases: DataReader
Read a Tripos MOL2 file into a :class:~molpy.Frame (first molecule).
Amber¶
amber ¶
AMBER ASCII inpcrd / restrt I/O (molrs-backed).
Parse lives in :func:molrs.io.read_amber_inpcrd. This module is a thin
façade that keeps the historical :class:AmberInpcrdReader surface, including
optional merge of coordinates into an existing Frame.
AmberInpcrdReader ¶
Bases: DataReader
Reader for AMBER ASCII *.inpcrd (old-style) coordinate files.
- Coordinates: Fortran
6F12.7, 6 numbers per line - Optional velocities section (same length as coordinates; restart only)
- Optional final box line (3–6 floats; first three → orthorhombic diagonal)
read ¶
Populate / update a Frame from the inpcrd path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
Frame | None
|
Optional existing Frame. When it already has an |
None
|
Returns:
| Type | Description |
|---|---|
Frame
|
The populated Frame. |
Raises:
| Type | Description |
|---|---|
ValueError
|
On parse errors or atom-count mismatch with frame. |
AC¶
ac ¶
Top¶
top ¶
GROMACS topology structure I/O (molrs-backed).
Read/write go through :func:molrs.io.read_top / :func:molrs.io.write_top.
Structure only ([ atoms ], bonds/pairs/angles/dihedrals) — not force-field
parameter tables (see :mod:molpy.io.forcefield.top).
Connectivity atom indices are 1-based as written in the file.
TopReader ¶
Bases: DataReader
Read GROMACS topology structure into a :class:~molpy.Frame.
Examples:
>>> reader = TopReader("molecule.top")
>>> frame = reader.read()
>>> frame["atoms"] # Block with atom data
Initialize GROMACS topology reader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to GROMACS .top file |
required |
**open_kwargs
|
Accepted for API parity; unused (molrs opens the path). |
{}
|
XYZ¶
xyz ¶
XYZ file I/O — molrs backend with thin molpy column normalization.
Parse/serialize: :mod:molrs.io. After read, molpy may merge split multi-
columns (CS_1+CS_2→CS), map species→element, and fill
atomic_number when missing.
XSF¶
xsf ¶
XSF (XCrySDen Structure File) I/O — molrs-backed.
Read/write go through :func:molrs.io.read_xsf / :func:molrs.io.write_xsf.
Atoms carry atomic_number, element, and x/y/z; crystal
structures attach a periodic box, molecules a free box.
XsfReader ¶
Bases: DataReader
Read an XSF file into a :class:~molpy.Frame via molrs.
Trajectory Modules¶
Base¶
base ¶
BaseTrajectoryReader ¶
Bases: BaseReader, Iterable['Frame']
Pure, storage-agnostic trajectory reader: a lazy Iterable[Frame].
Subclasses implement only read_frame(index) and the n_frames
property; the random-access and iteration API (__iter__,
__getitem__, slicing, read_frames / read_range / read_all,
__len__) is derived entirely from those two and involves no files.
read_frame
abstractmethod
¶
Read and return the frame at index (negative indices allowed).
read_frames ¶
Read the frames at indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
list[int]
|
Frame indices to read. |
required |
Returns:
| Type | Description |
|---|---|
list[Frame]
|
The frames, in the order requested. |
read_range ¶
Read frames start (inclusive) to stop (exclusive) by step.
LAMMPS¶
lammps ¶
LAMMPS dump trajectory write — molrs-backed.
Incremental :meth:write_frame buffers frames; :meth:close flushes via
:func:molrs.io.raw.write_lammps_traj (requires each frame to carry box).
LammpsTrajectoryWriter ¶
Bases: TrajectoryWriter
Write a LAMMPS dump trajectory (molrs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fpath
|
str | Path
|
Output path. |
required |
atom_style
|
str
|
Accepted for API parity; molrs derives columns from the frame. |
'full'
|
XYZ¶
xyz ¶
XYZTrajectoryWriter ¶
Bases: TrajectoryWriter
Writer for XYZ trajectory files.
Log Modules¶
LAMMPS¶
lammps ¶
LAMMPS log file parser.
Parsing logic lives in molrs (Rust). This module is a thin public façade:
it keeps the nested dataclass API used by callers and hydrates molrs payloads
into those types (including a NumPy structured array for thermo columns).
LAMMPSCPUUse
dataclass
¶
% CPU use summary line.
LAMMPSLoadBalance
dataclass
¶
LAMMPS load-balance statistic plus optional histogram.
LAMMPSLog
dataclass
¶
Parsed LAMMPS log with one structured entry per run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to a LAMMPS log file. |
required |
style
|
str
|
Thermo style. Only |
'default'
|
LAMMPSLogHeader
dataclass
¶
LAMMPSLoopTime
dataclass
¶
Loop time summary line.
LAMMPSMemoryUsage
dataclass
¶
Per MPI rank memory allocation line.
LAMMPSNeighborStatistics
dataclass
¶
LAMMPSNeighborStatistics(
total_neighbors,
ave_neighs_per_atom,
ave_special_neighs_per_atom,
neighbor_list_builds,
dangerous_builds,
raw_lines,
)
Neighbor-list statistics emitted after a run.
LAMMPSPerformance
dataclass
¶
LAMMPSPerformance(
ns_per_day,
hours_per_ns,
timesteps_per_second,
atom_steps_per_second,
atom_steps_units,
raw_line,
)
LAMMPS Performance summary line.
LAMMPSRun
dataclass
¶
LAMMPSRun(
index,
setup_log,
memory,
thermo,
loop_time,
performance,
CPU_use,
MPI_task_timing,
thread_timing,
load_balance,
neighbor_statistics,
warnings,
unparsed_log,
raw_text,
)
One LAMMPS run output block.
LAMMPSThermo
dataclass
¶
LAMMPSTimingBreakdown
dataclass
¶
MPI task timing breakdown or thread timing table.
LAMMPSTimingRow
dataclass
¶
One row from a LAMMPS timing breakdown table.
LAMMPSWarning
dataclass
¶
A warning line from the LAMMPS log.