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 (molrs) |
write_lammps_forcefield / LAMMPSForceFieldWriter |
LAMMPS *.ff include |
write (molrs; molrs 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¶
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("oplsaa.xml")
ff = mp.io.read_lammps_forcefield("system.ff")
# Write LAMMPS *.ff (via molrs; 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.
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'
|
read_LAMMPS_log ¶
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 GROMACS gro file and return a Frame object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to gro file |
required |
frame
|
Any
|
Optional existing Frame to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Populated Frame object |
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.read_lammps_forcefield),
which parses the include directly into a molrs.ForceField in molrs units
(Å, kcal/mol, radians, e): LAMMPS harmonic K → molrs k = 2K, angle
and dihedral-phase values stay in degrees, 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 mol2 file and return a Frame object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to mol2 file |
required |
frame
|
Any
|
Optional existing Frame to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Populated Frame object |
read_pdb ¶
Read PDB file and return a Frame object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to PDB file |
required |
frame
|
Any
|
Optional existing Frame to populate |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Populated Frame object |
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_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_xml_forcefield ¶
Read XML force field file and return a ForceField object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to XML force field file |
required |
Returns:
| Type | Description |
|---|---|
Any
|
ForceField object |
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 |
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.
_frame_used_types ¶
Per-section set of the type names a frame actually uses (None if the
section/column is absent), for whitelisting FF output to the labelmap.
A LAMMPS data file's type labels come from the frame's used types, so any coeff the FF writer emits for a type not in this set references a labelmap entry that does not exist and LAMMPS rejects it. Both the system writer and the engine writer filter against this so their coeffs match the data file.
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_gro ¶
Write a Frame object to a GROMACS GRO file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
frame
|
Any
|
Frame object to write |
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 object to a LAMMPS data file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
frame
|
Any
|
Frame object to write |
required |
atom_style
|
str
|
LAMMPS atom style (default: 'full') |
'full'
|
type_labels
|
dict[str, list[str]] | None
|
Format-owned label inventory, including unused types. |
None
|
forcefield
|
Any
|
Optional ForceField whose coefficients belong in this data file. |
None
|
write_lammps_forcefield ¶
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
|
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 trajectory file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
frames
|
list
|
List of Frame objects to write |
required |
atom_style
|
str
|
LAMMPS atom style (default: 'full') |
'full'
|
write_pdb ¶
Write a Frame object to a PDB file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Output file path |
required |
frame
|
Any
|
Frame object to write |
required |
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 |
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.read_lammps_forcefield, :func:molrs.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
|
write ¶
write(
forcefield,
atom_types=None,
bond_types=None,
angle_types=None,
dihedral_types=None,
improper_types=None,
skip_pair_style=False,
)
Write forcefield (molrs 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
|
LammpsForceFieldFormatter ¶
Bases: LammpsFieldFormatter, ForceFieldFormatter
Parameter formatters for LAMMPS pair styles beyond the AMBER/GAFF set.
XML¶
xml ¶
XML force field parser for atomistic force fields.
AngleUnitWarning ¶
Bases: UserWarning
An angle value looks inconsistent with its declared angle_unit.
OPLSAAForceFieldReader ¶
Bases: XMLForceFieldReader
Specialized reader for OPLS-AA force field with LAMMPS unit conversions.
This reader extends XMLForceFieldReader to: 1. Use lj/cut/coul/long pair style instead of lj/cut/coul/cut 2. Convert epsilon: kJ/mol → kcal/mol (÷4.184) 3. Convert sigma: nm → Å (×10) 4. Convert bond K: kJ/mol/nm² → kcal/mol/Ų (÷(4.184×100), both use 0.5 factor in formula) 5. Convert angle K: kJ/mol/rad² → kcal/mol/deg² (direct to LAMMPS format) Formula: k_lammps = (0.5 * k_opls / 4.184) * (π/180)² Stored internally in LAMMPS format, so no conversion needed when writing 6. Convert dihedral K: kJ/mol → kcal/mol (÷4.184)
XMLForceFieldReader ¶
XML force field parser for atomistic force fields.
Parses XML-formatted force field files (e.g., OPLS-AA) and populates a ForceField object with atom types, bond parameters, angle parameters, dihedral parameters, and nonbonded interactions.
The parser handles: - AtomTypes section: atom type definitions - HarmonicBondForce: harmonic bond parameters - HarmonicAngleForce: harmonic angle parameters - RBTorsionForce: Ryckaert-Bellemans dihedral parameters - NonbondedForce: LJ and Coulomb parameters
Initialize the XML force field reader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the XML force field file, or filename for built-in files (e.g., "oplsaa.xml" will load from molpy/data/forcefield/) |
required |
angle_unit
|
str
|
Unit of angle equilibria ( |
'radian'
|
read ¶
Read and parse the XML force field file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forcefield
|
ForceField | None
|
Optional existing force field to populate. If None, creates new one. |
None
|
layer
|
int
|
Overlay level for this read. |
0
|
Returns:
| Type | Description |
|---|---|
ForceField
|
Populated ForceField object |
XMLForceFieldWriter ¶
Write a ForceField to OpenMM-style XML.
The output is roundtrip-compatible with :class:XMLForceFieldReader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Destination path. |
required |
precision
|
int
|
Number of decimal digits for floating-point values. |
6
|
read_oplsaa_forcefield ¶
Read OPLS-AA force field with proper unit conversions for LAMMPS.
This function uses OPLSAAForceFieldReader which: - Uses lj/cut/coul/long pair style - Converts epsilon: epsilon_lammps = epsilon_opls / 4.184 (kJ/mol to kcal/mol) - Converts sigma: sigma_lammps = sigma_opls * 10.0 (nm to Angstrom)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the OPLS-AA XML file, or "oplsaa.xml" for built-in |
required |
forcefield
|
ForceField | None
|
Optional existing force field to populate |
None
|
Returns:
| Type | Description |
|---|---|
ForceField
|
Populated ForceField object with LAMMPS-compatible units |
Example
ff = read_oplsaa_forcefield("oplsaa.xml")
read_xml_forcefield ¶
Convenience function to read an XML force field file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the XML force field file, or filename for built-in files (e.g., "oplsaa.xml" will load from molpy/data/forcefield/) |
required |
forcefield
|
ForceField | None
|
Optional existing force field to populate |
None
|
layer
|
int
|
Overlay level (0 = base, >0 = overlay that overrides the base
during SMARTS typing). Pass |
0
|
Returns:
| Type | Description |
|---|---|
ForceField
|
Populated ForceField object |
write_xml_forcefield ¶
Convenience function to write a force field to XML.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Output path. |
required |
forcefield
|
ForceField
|
Force field to serialize. |
required |
GROMACS Topology¶
top ¶
GromacsForceFieldWriter ¶
Write a ForceField to GROMACS .top / .itp format.
The output is roundtrip-compatible with :class:GromacsTopReader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Destination path. |
required |
precision
|
int
|
Number of decimal digits for floating-point values. |
6
|
GromacsTopReader ¶
Utility to read a Gromacs .top/.itp topology file into a dictionary.
The returned mapping contains a key for every section header encountered
(e.g. atomtypes, moleculetype), mapping to the raw content lines
(with inline comments stripped) that appear under that section in the order
they occur.
read ¶
Parse the topology file.
Parameters¶
forcefield:
Optional object providing a base_dir or path attribute used
to resolve relative #include statements that point inside the
force-field directory (e.g. ff/amber14sb.ff/ions.itp).
strip_comments:
Whether to remove text following a ; (Gromacs comment
delimiter). Leading/trailing whitespace is always removed.
recursive:
If True (default) #included files are parsed recursively. The
content of an included file is merged into the dictionary being
built; if the same section appears multiple times its content is
extended in occurrence order.
Returns¶
dict[str, list[str]] Mapping from lower‑case section name to list of raw content lines.
AMBER¶
amber ¶
AmberPrmtopReader ¶
get_bond_with_H ¶
Return list of bonded atom pairs, K, and Rmin for each bond with a hydrogen
get_bond_without_H ¶
Return list of bonded atom pairs, K, and Rmin for each bond with no hydrogen
parse_angle_params ¶
Return list of atom triplets, K, and ThetaMin for each bond angle
parse_dihedral_params ¶
Return list of atom quads, K, phase and periodicity for each dihedral angle
parse_nonbond_params ¶
Return list of all rVdw, epsilon pairs for each atom. If off-diagonal elements of the Lennard-Jones A and B coefficient matrices are found, NbfixPresent exception is raised
Data Modules¶
LAMMPS¶
lammps ¶
Modern LAMMPS data file I/O using Block.from_csv.
This module provides a clean, imperative approach to reading and writing LAMMPS data files using the Block.from_csv functionality.
LammpsDataReader ¶
LammpsDataResult
dataclass
¶
Explicit products of parsing one LAMMPS data file.
LammpsDataWriter ¶
Bases: DataWriter
Modern LAMMPS data file writer using Block.to_csv approach.
Important Requirements: - Atoms in the frame must have an 'id' field. This field is required to map atom indices to atom IDs for LAMMPS output. - Connectivity data (bonds, angles, dihedrals) in the frame uses atom indices (0-based from to_frame()). The writer automatically converts these indices to atom IDs using the index->ID mapping from the atoms 'id' field.
Frame Structure: - Atoms: Must include 'id' field. Other required fields depend on atom_style. - Bonds/Angles/Dihedrals: Use atom indices in 'atomi', 'atomj', 'atomk', 'atoml' (from to_frame()). These are 0-based indices that will be converted to 1-based atom IDs.
LammpsFieldFormatter ¶
Bases: FieldFormatter
LAMMPS-specific field name translation.
Maps LAMMPS atom_style column names to canonical field names::
"q" → "charge"
"mol" → "mol_id"
lammps_molecule ¶
LAMMPS molecule file I/O.
This module provides readers and writers for LAMMPS molecule template files, supporting both native format and JSON format as described in the LAMMPS documentation.
LammpsMoleculeReader ¶
Bases: DataReader
LAMMPS molecule file reader supporting both native and JSON formats.
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. It used to live in molpy.reacter because a Reacter subclass
produced it; nothing produces it now 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
¶
Convert string type columns to unified numeric IDs, in place.
Rows whose type is absent from the mapping (boundary topology with untyped terms) are dropped with a warning. The numeric IDs must match the system data file for template matching.
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 ¶
PDBReader ¶
Bases: DataReader
Minimal-yet-robust PDB reader.
- ATOM / HETATM parsed per PDB v3.3 fixed columns
- CRYST1 -> frame.box
- CONECT -> bond list
read ¶
Read a single PDB model via the molrs Rust backend.
Multi-MODEL / multi-frame PDBs are read one model at a time; use
:func:molpy.io.read_pdb_trajectory for all models.
PDBWriter ¶
Bases: DataWriter
Robust PDB file writer that creates properly formatted PDB files.
Features: - Writes ATOM/HETATM records with proper formatting - Handles missing fields with sensible defaults - Writes CRYST1 records from box information - Writes CONECT records for bonds - Ensures PDB format compliance
write ¶
Write frame to PDB file.
Required fields in frame["atoms"]: - x, y, z: coordinates (float, required) - id: atom ID (int, optional, defaults to index+1)
Optional fields in frame["atoms"]: - name: atom name (str) - resName: residue name (str) - element: element symbol (str) - resSeq: residue sequence number (int) - chainID: chain identifier (str) - occupancy: occupancy (float) - tempFactor: temperature factor (float)
Optional typed metadata: - elements: space-separated string of element symbols (one per atom) - name: frame name (str)
The optional CRYST1 cell is read from frame.box.
Raises:
| Type | Description |
|---|---|
ValueError
|
If required fields (x, y, z) are missing or contain None |
GRO¶
gro ¶
GROMACS .gro file I/O — molrs (Rust) backend.
Reader/writer delegate to :mod:molrs.io (parsing + field canonicalization in
Rust). :class:GroFieldFormatter is retained for the formatter hierarchy.
Mol2¶
mol2 ¶
Mol2Reader ¶
Bases: DataReader
Robust MOL2 file reader following TRIPOS MOL2 format specification.
Features: - Parses MOLECULE, ATOM, BOND, and SUBSTRUCTURE sections - Handles various atom types and bond types - Robust error handling for malformed files - Supports partial files with missing sections - Assigns atomic numbers from atom names/types
Amber¶
amber ¶
AmberInpcrdReader ¶
Bases: DataReader
Reader for AMBER ASCII *.inpcrd (old-style) coordinate files.
- Coordinates: 12.7/12.8 format, 6 numbers per line
- Optional velocities section (same length as coordinates)
- Optional final box line (3-6 floats)
AC¶
ac ¶
Antechamber (AC) file format reader.
Reads Antechamber .ac files containing atom and bond information with force field types and charges.
AcFieldFormatter ¶
Bases: FieldFormatter
Antechamber .ac field name translation.
AcReader ¶
Bases: DataReader
Reader for Antechamber .ac format files.
Parses ATOM and BOND sections from Antechamber output files, extracting coordinates, charges, atom types, and connectivity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
str | Path
|
Path to .ac file |
required |
assign_atomic_numbers ¶
Assign atomic numbers by guessing from atom names/types.
Top¶
top ¶
GROMACS topology file reader for Frame objects.
This module provides a reader for GROMACS topology files that extracts structural information (atoms, bonds, angles, dihedrals, pairs) and creates Frame objects with Block containers.
TopReader ¶
Bases: DataReader
Read GROMACS topology files and create Frame objects.
This reader parses GROMACS .top files and extracts structural information from sections like [atoms], [bonds], [angles], [dihedrals], and [pairs].
Examples:
>>> reader = TopReader("molecule.top")
>>> frame = reader.read()
>>> frame["atoms"] # Block with atom data
>>> frame["bonds"] # Block with bond data
Initialize GROMACS topology reader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
PathLike
|
Path to GROMACS .top file |
required |
**open_kwargs
|
Any
|
Additional arguments passed to file open. |
{}
|
read ¶
TopWriter ¶
Bases: DataWriter
Write GROMACS topology files from Frame objects.
Produces a minimal .top file with [ moleculetype ],
[ atoms ], [ bonds ], and optional [ pairs ],
[ angles ], [ dihedrals ] sections, followed by
[ system ] and [ molecules ].
Examples:
XYZ¶
xyz ¶
XYZ file I/O — molrs (Rust) backend.
Reader/writer delegate to :mod:molrs.io. The reader normalizes molrs output to
molpy conventions (merge split multi-columns, species→element, atomic
numbers); the writer ensures separate x/y/z coordinate columns.
XSF¶
xsf ¶
XSF (XCrySDen Structure File) format reader and writer.
XSF is a format for crystal structure visualization, supporting both periodic and non-periodic structures. It can contain atomic coordinates, unit cell parameters, and other structural information.
XsfReader ¶
Bases: DataReader
Parse an XSF file into a Frame.
XSF format supports both crystal structures (with unit cell) and molecular structures. The format can contain: - CRYSTAL or MOLECULE keyword - PRIMVEC or CONVVEC for unit cell vectors - PRIMCOORD for atomic coordinates - Optional comment lines starting with #
XsfWriter ¶
Bases: DataWriter
Write Frame to XSF format.
Features: - Supports both CRYSTAL and MOLECULE structures - Writes PRIMVEC for unit cell vectors - Writes PRIMCOORD for atomic coordinates - Automatically determines structure type based on presence of box
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 ¶
LammpsTrajectoryWriter ¶
XYZ¶
xyz ¶
XYZTrajectoryWriter ¶
Bases: TrajectoryWriter
Writer for XYZ trajectory files.
Log Modules¶
LAMMPS¶
lammps ¶
LAMMPS log file parser.
This module parses the standard LAMMPS run output structure documented in
Run_output.html: thermo tables, loop timing, performance summaries,
CPU/MPI timing, load-balance statistics, neighbor statistics, and warnings.
Unrecognized lines are preserved so callers can still inspect information that
does not yet have a structured representation.
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.