Skip to content

Python Reference

Canonical import style:

import molrs as mr

This page is rendered from the installed molrs package by mkdocstrings-python. Autodoc identifiers use the package name (molrs.Frame); user code should import molrs as mr and write mr.Frame. The type stub in molrs-python/python/molrs/_lib.pyi is the committed companion artifact that keeps signatures visible to static tools and the docs build.

Core Model

Box

Simulation box with periodic boundary conditions, exposed to Python as molrs.Box.

The box is defined by a 3x3 cell matrix H whose columns are the lattice vectors, an origin point, and per-axis PBC flags.

Python Examples

import numpy as np
from molrs import Box

box = Box.cube(10.0)                       # 10 x 10 x 10 cubic
box = Box.ortho(np.array([10, 20, 30]))    # orthorhombic
print(box.volume())                        # 6000.0

__doc__ = 'Simulation box with periodic boundary conditions, exposed to Python as\n`molrs.Box`.\n\nThe box is defined by a 3x3 cell matrix **H** whose columns are the\nlattice vectors, an origin point, and per-axis PBC flags.\n\n# Python Examples\n\n```python\nimport numpy as np\nfrom molrs import Box\n\nbox = Box.cube(10.0) # 10 x 10 x 10 cubic\nbox = Box.ortho(np.array([10, 20, 30])) # orthorhombic\nprint(box.volume()) # 6000.0\n```' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

angles property

Lattice angles [alpha, beta, gamma] in degrees.

bounds property

Per-axis coordinate bounds as [[xlo, xhi], [ylo, yhi], [zlo, zhi]].

cell_defined property

Whether the cell is geometrically defined. False marks a "no-cell" box (undefined / zero-volume), distinct from is_free (periodicity).

h property

Cell matrix H (3x3), lattice vectors as columns.

Returns:

Type Description
numpy.ndarray, shape (3, 3), dtype float

inverse property

Inverse cell matrix.

is_free property

True when the box is free (non-periodic on every axis).

lengths property

Lengths of the three lattice vectors (property; [|a|, |b|, |c|]).

nearest_plane_distance property

Perpendicular distances between opposite cell faces.

origin property

Box origin in Cartesian coordinates.

Returns:

Type Description
numpy.ndarray, shape (3,), dtype float

pbc property

Periodic boundary condition flags [pbc_x, pbc_y, pbc_z].

Returns:

Type Description
numpy.ndarray, shape (3,), dtype bool

style property

Geometry style label: "free", "orthogonal", or "triclinic".

tilts property

LAMMPS-convention tilt factors (xy, xz, yz). Zero on orthogonal boxes.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

approx_eq(other, tol) method descriptor

Whether other describes the same cell within an absolute tolerance.

True iff every cell-matrix entry and origin component differ by at most tol (length units), the PBC flags are identical and both boxes agree on cell_defined. tol=0.0 is exact equality.

Raises:

Type Description
ValueError

If tol is negative or NaN.

corners() method descriptor

Eight Cartesian cell corners.

cube(a, origin=None, pbc=None) staticmethod

Create a cubic simulation box.

Parameters:

Name Type Description Default
a float

Side length of the cube in the same length unit as coordinates.

required
origin (ndarray, shape(3))

Box origin. Defaults to [0, 0, 0].

None
pbc numpy.ndarray, shape (3,), dtype bool

Periodic boundary flags. Defaults to [True, True, True].

None

Returns:

Type Description
Box

Examples:

>>> box = Box.cube(10.0)
>>> box.volume()
1000.0

delta(xyzu1, xyzu2, minimum_image=False) method descriptor

Compute displacement vectors between two point sets.

Calculates xyzu2 - xyzu1 with optional minimum-image convention for periodic systems.

Parameters:

Name Type Description Default
xyzu1 numpy.ndarray, shape (N, 3) or (3,), dtype float

First set of Cartesian coordinates.

required
xyzu2 numpy.ndarray, shape (N, 3) or (3,), dtype float

Second set of Cartesian coordinates. Must have the same rank as xyzu1 (both 1-D or both 2-D).

required
minimum_image bool

If True, apply the minimum-image convention to displacements. Default is False.

False

Returns:

Type Description
numpy.ndarray, shape (N, 3) or (3,), dtype float

Displacement vectors xyzu2 - xyzu1. Rank matches the inputs.

Raises:

Type Description
ValueError

If ranks differ, 1-D length is not 3, columns != 3, or N differs.

distance(r1, r2) method descriptor

Minimum-image distance between two points.

distance_squared(r1, r2) method descriptor

Squared minimum-image distance between two points.

distances(points1, points2) method descriptor

Row-wise minimum-image distances between equally sized point arrays.

from_bounds(points, padding, pbc=None) staticmethod

Create a tight orthorhombic box around a point cloud.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), or Frame

The points to enclose. A Frame contributes the x/y/z columns of its atoms block.

required
padding (float or ndarray, shape(3))

Margin added on each side, one value for all axes or one per axis. Must be non-negative.

required
pbc numpy.ndarray, shape (3,), dtype bool

Periodic boundary flags. Defaults to [True, True, True].

None

Raises:

Type Description
ValueError

If there are no points, a coordinate column is missing or has holes, padding is negative or not of length 3, or the box is degenerate.

images(xyz) method descriptor

Integer periodic image flags for Cartesian coordinates.

The flags are int32, the schema's integer type for the ix/iy/iz columns.

isin(xyz) method descriptor

Test whether each point lies inside the primary simulation cell.

Parameters:

Name Type Description Default
xyz numpy.ndarray, shape (N, 3), dtype float

Cartesian coordinates.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside the cell.

Raises:

Type Description
ValueError

If xyz does not have 3 columns.

lattice(index) method descriptor

Return a lattice vector by index.

Parameters:

Name Type Description Default
index int

Lattice vector index: 0, 1, or 2.

required

Returns:

Type Description
(ndarray, shape(3))

The lattice vector as a Cartesian 3-vector.

Raises:

Type Description
ValueError

If index is not 0, 1, or 2.

ortho(lengths, origin=None, pbc=None) staticmethod

Create an orthorhombic (rectangular) simulation box.

Parameters:

Name Type Description Default
lengths numpy.ndarray, shape (3,), dtype float

Side lengths [Lx, Ly, Lz].

required
origin (ndarray, shape(3))

Box origin. Defaults to [0, 0, 0].

None
pbc numpy.ndarray, shape (3,), dtype bool

Periodic boundary flags. Defaults to [True, True, True].

None

Returns:

Type Description
Box

Raises:

Type Description
ValueError

If lengths does not have exactly 3 elements.

Examples:

>>> box = Box.ortho(np.array([10.0, 20.0, 30.0]))

pairwise_delta(points1, points2) method descriptor

All pairwise minimum-image displacement vectors (points2 - points1).

pairwise_distances(points1, points2) method descriptor

All pairwise minimum-image distances.

shortest_vector(r1, r2) method descriptor

Minimum-image displacement from r1 to r2.

to_cart(xyzs) method descriptor

Convert fractional coordinates to Cartesian coordinates.

Parameters:

Name Type Description Default
xyzs numpy.ndarray, shape (N, 3), dtype float

Fractional coordinates.

required

Returns:

Type Description
numpy.ndarray, shape (N, 3), dtype float

Cartesian coordinates.

Raises:

Type Description
ValueError

If xyzs does not have 3 columns.

to_frac(xyz) method descriptor

Convert Cartesian coordinates to fractional coordinates.

Parameters:

Name Type Description Default
xyz numpy.ndarray, shape (N, 3), dtype float

Cartesian coordinates.

required

Returns:

Type Description
numpy.ndarray, shape (N, 3), dtype float

Fractional coordinates in the range [0, 1) for wrapped points.

Raises:

Type Description
ValueError

If xyz does not have 3 columns.

transformed(transformation) method descriptor

Return a box whose cell matrix is right-multiplied by transformation.

unwrap(xyz, images) method descriptor

Reconstruct unwrapped coordinates from wrapped coordinates and images.

images is int32, the schema's integer type, so a frame's ix/iy/iz columns pass in without a cast.

volume() method descriptor

Volume of the simulation box.

Returns:

Type Description
float

Volume in length_unit^3 (e.g. angstrom^3).

wrap(xyzu) method descriptor

Wrap coordinates into the primary simulation cell.

Applies periodic wrapping along axes where PBC is enabled.

Parameters:

Name Type Description Default
xyzu numpy.ndarray, shape (N, 3), dtype float

Unwrapped Cartesian coordinates.

required

Returns:

Type Description
numpy.ndarray, shape (N, 3), dtype float

Wrapped Cartesian coordinates.

Raises:

Type Description
ValueError

If xyzu does not have 3 columns.

Block

Heterogeneous column store exposed to Python as molrs.Block.

Each column is a named, typed array. All columns share the same number of rows (axis-0 length). The underlying storage lives in an FFI Store and is accessed through a version-tracked [BlockHandle]; a block read from a frame (frame["atoms"]) is a handle on the frame's stored block, so every method below reads and writes the frame's data.

A column is dense, so a per-row component that only some rows carry is stored alongside a validity mask: Block.validity(key) returns it, or None when every cell of that column is a real value.

Every column-key argument accepts a str or a :class:molrs.keys.Key.

Python Examples

import numpy as np
from molrs import Block

b = Block({"x": [1.0, 2.0, 3.0], "element": ["C", "H", "H"]})
assert b.nrows == 3
assert "x" in b
arr = b["x"]                 # zero-copy numpy view
names = b["element"]         # numpy str array; a copy, shape preserved
xyz = b["x", "x", "x"]             # (3, 3) stacked columns
sub = b[b["x"] > 1.5]       # a new Block of the selected rows
assert b.validity("x") is None   # no holes in that column

__doc__ = 'Heterogeneous column store exposed to Python as `molrs.Block`.\n\nEach column is a named, typed array. All columns share the same number of\nrows (axis-0 length). The underlying storage lives in an FFI `Store` and is\naccessed through a version-tracked [`BlockHandle`]; a block read from a\nframe (``frame["atoms"]``) is a handle on the frame\'s stored block, so every\nmethod below reads and writes the frame\'s data.\n\nA column is dense, so a per-row component that only some rows carry is\nstored alongside a validity mask: `Block.validity(key)` returns it, or\n`None` when every cell of that column is a real value.\n\nEvery column-key argument accepts a ``str`` or a :class:`molrs.keys.Key`.\n\n# Python Examples\n\n```python\nimport numpy as np\nfrom molrs import Block\n\nb = Block({"x": [1.0, 2.0, 3.0], "element": ["C", "H", "H"]})\nassert b.nrows == 3\nassert "x" in b\narr = b["x"] # zero-copy numpy view\nnames = b["element"] # numpy str array; a copy, shape preserved\nxyz = b["x", "x", "x"] # (3, 3) stacked columns\nsub = b[b["x"] > 1.5] # a new Block of the selected rows\nassert b.validity("x") is None # no holes in that column\n```' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs._lib' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

coords property

Positions as an (nrows, 3) float64 array, gathered from the x / y / z columns (a copy).

Assigning an (N, 3) array-like writes it back into x / y / z (each replaced as a float64 column; a missing one is added).

Raises:

Type Description
KeyError

On read, if x, y or z is missing.

ValueError

On write, if the array is not (N, 3) or N differs from the block's row count.

nrows property

Number of rows (axis-0 length); 0 for a block with no rows.

Returns:

Type Description
int

shape property

Reported shape: [nrows] for a table, the declared N-D shape for a grid, [] for an empty block.

structural_shape property

Explicit N-D structural shape, or None for a plain row table.

__contains__(key) method descriptor

Return bool(key in self).

__delitem__(key) method descriptor

Delete self[key].

__getitem__(key) method descriptor

Return self[key].

__iter__() method descriptor

Implement iter(self).

__len__() method descriptor

Return len(self).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__reduce__() method descriptor

Pickle by logical state: columns, validity masks, declared precisions, row count and structural shape.

__repr__() method descriptor

Return repr(self).

__setitem__(key, value) method descriptor

Set self[key] to value.

__setstate__(state) method descriptor

Restore the state __reduce__ produced.

copy() method descriptor

A deep copy: new buffers for every column, masks and shape included.

Writing into the copy's columns (through numpy) never reaches this block, nor the numpy array a column was built from.

copy_column(key) method descriptor

Owned numpy array of one column, shape included.

Numeric, bool and complex columns are copies of the zero-copy view block[key] returns. A string column is already a copy under block[key] — a numpy str array of the column's shape — and this returns another one.

Parameters:

Name Type Description Default
key str | Key

Column name.

required

Raises:

Type Description
KeyError

If key does not exist in this block.

Examples:

>>> names = block.copy_column("element")

dtype(key) method descriptor

Return the dtype string for the given column.

Returns:

Type Description
str

"float", "int", "i64", "uint", "bool", "u8", "string", …

Raises:

Type Description
KeyError

If key does not exist.

has_f64(key) method descriptor

True when key exists and is f64.

has_int(key) method descriptor

True when key exists and is a signed integer column (i8, i16, i32, or i64).

has_string(key) method descriptor

True when key exists and is a string column.

has_uint(key) method descriptor

True when key exists and is an unsigned integer column (u8, u16, u32, or u64).

insert(key, array) method descriptor

Insert a numpy array (or list of strings) as a named column, at the width given.

The typed write: unlike block[key] = array it does not convert to the schema dtype (an i64 column stays i64; a narrow float is promoted to float64, the one float width); a dtype the schema refuses raises. If a column with the same key already exists it is replaced. The array length must match the row count of existing columns, or the block must be empty.

Parameters:

Name Type Description Default
key str | Key

Column name (e.g. "x", "element").

required
array ndarray | list[str]

Column data.

required

Raises:

Type Description
TypeError

If the array dtype is not supported.

ValueError

If the row count does not match existing columns.

Examples:

>>> b = Block()
>>> b.insert("x", np.zeros(10, dtype=np.float32))

insert_nullable(key, array, validity) method descriptor

Insert a named column together with a per-row validity mask.

The write side of :meth:validity. validity[i] is False where row i of array is a hole: the array still carries something there — whatever the caller put in, typically a zero — and the mask is the only place that says it is not a stated value.

An all-True mask states nothing :meth:insert does not, so it is dropped rather than stored and :meth:validity keeps answering None. Apart from the mask this is :meth:insert, with the same accepted dtypes and the same row-count rule.

Parameters:

Name Type Description Default
key str | Key

Column name (e.g. "frag_id").

required
array ndarray | list[str]

Column data; see :meth:insert for the accepted dtypes.

required
validity ndarray | Sequence[bool]

1-D boolean mask in row order, one entry per row of array.

required

Raises:

Type Description
TypeError

If the array dtype is not supported, or validity is not a 1-D bool array or a sequence of bools.

ValueError

If the row count does not match existing columns, or validity does not have exactly one entry per row of array.

Examples:

>>> b = Block()
>>> b.insert_nullable("frag_id", np.array([7, 0, 0]), [True, False, False])
>>> b.validity("frag_id")
array([ True, False, False])

keys() method descriptor

List all column names.

precision(key) method descriptor

The declared precision of a column, or None when it declares none.

Raises:

Type Description
KeyError

If key does not exist in this block.

remove(key) method descriptor

Remove a column by name.

Raises:

Type Description
KeyError

If key does not exist.

rename(old_key, new_key) method descriptor

Rename a column in place, keeping its data and validity mask.

Renaming is a write into new_key: when the Frame schema declares new_key with a different dtype, the column adopts it if the values survive the conversion (a file's int64 serial renamed onto id becomes uint), and the rename is refused otherwise.

Parameters:

Name Type Description Default
old_key str | Key

Existing column name.

required
new_key str | Key

New column name.

required

Raises:

Type Description
KeyError

If old_key does not exist or new_key already does.

ValueError

If the values do not survive the schema dtype of new_key.

resize(nrows) method descriptor

Axis-0 length of an empty block, or reshape every column.

select_rows(indices) method descriptor

Return a new Block with rows gathered at indices (preserves the column set, dtypes and validity masks).

Raises:

Type Description
ValueError

If any index is out of range.

set_precision(key, precision) method descriptor

Declare (or, with None, withdraw) the precision of an f64 column: an absolute tolerance in the column's own units.

A record writer rounds the column to the largest power of two not above precision (ties to even) before storing it, so the stored values are within precision / 2 of these and compress several times better; the values in memory are not touched. The declaration is stored with the column (frame / system) or in the trajectory's schema, and reads back. A rename keeps it; replacing the column with another dtype, or removing it, drops it.

Parameters:

Name Type Description Default
key str | Key

Column name.

required
precision float | None

Finite, within [2**-1000, 2**1000]; None withdraws it.

required

Raises:

Type Description
KeyError

If key does not exist in this block.

ValueError

If the column is not float64 or precision is out of bounds.

Examples:

>>> b = molrs.Block({"x": np.array([0.12345, 1.5])})
>>> b.set_precision("x", 1e-3)
>>> b.precision("x")
0.001

set_shape(shape) method descriptor

Declare this block as N-dimensional. Product of shape must equal the row count when the block has columns.

set_target(key, target) method descriptor

Declare (or, with None, withdraw) that a uint64 column holds 0-based row indices into target: "<block>" of the same frame, or "/<section>/<block>" of a frame-shaped section of the record ("/frame/atoms").

The relation endpoints atomi … atoml reference atoms without one; a declaration overrides that, and names what any other referencing column (members.atom) points into. Subsetting and replicating renumber same-frame references; a *.mrec writer and reader refuse a reference that does not resolve.

Raises:

Type Description
KeyError

If key does not exist in this block.

ValueError

If the column is not uint64 or target is malformed or names a trajectory block ("/trajectory/…").

set_validity(key, mask) method descriptor

Attach a validity mask to an existing column, whatever its dtype.

mask[i] is False where row i holds no value. The mask replaces any the column had; an all-True mask clears it, so :meth:validity answers None afterwards.

Parameters:

Name Type Description Default
key str | Key

Column name.

required
mask ndarray | Sequence[bool]

1-D boolean mask, one entry per row.

required

Raises:

Type Description
KeyError

If key does not exist in this block.

TypeError

If mask is not a 1-D bool array or a sequence of bools.

ValueError

If mask does not have exactly one entry per row.

sort(key, reverse=False) method descriptor

Return a new Block sorted by the key column (original unchanged).

Parameters:

Name Type Description Default
key str | Key

Column to sort by.

required
reverse bool

Descending order (the ascending order reversed). Default False.

False

Raises:

Type Description
KeyError

If key is not a column.

stack(parts) staticmethod

Row-wise union of parts: their rows in order, under the union of their columns (first-seen order).

A column a part lacks is filled with the dtype's default for that part's rows and marked null in the column's validity mask. A part's own masks travel with its rows. The parts are not modified.

Parameters:

Name Type Description Default
parts Sequence[Block]
required

Returns:

Type Description
Block

A new block (new buffers).

Raises:

Type Description
ValueError

If two parts carry one column under different dtypes or per-row shapes.

Examples:

>>> s = Block.stack([Block({"x": [0.0]}), Block({"x": [1.0], "q": [2.0]})])
>>> s.validity("q")
array([False,  True])

target(key) method descriptor

The declared target of a column, or None.

Raises:

Type Description
KeyError

If key does not exist in this block.

targets() method descriptor

Every declared target, as {column: target}.

validity(key) method descriptor

The validity mask of a column, or None when the column has no holes.

A block column is dense, so a component that only some rows carry — frag_id on a partially labelled molecule, h_count declared on one bracket atom — needs a second array saying which cells are real. None is the common case and means "every cell is a stated value"; it is not an all-True array, and a caller must not read a missing mask as "all holes". A key that names no column is a different question and raises KeyError, as indexing and :meth:dtype do — were it to answer None, a misspelled key would read as a dense column.

Parameters:

Name Type Description Default
key str | Key

Column name.

required

Returns:

Type Description
ndarray | None

A 1-D bool array in row order — True where the cell holds a real value, False where it is a hole — or None when the column carries no mask.

Raises:

Type Description
KeyError

If key does not exist in this block.

Frame

Hierarchical data container exposed to Python as molrs.Frame.

A Frame is a dictionary of named Blocks with optional simulation box and metadata. It is the primary exchange format for molecular data across the molrs ecosystem, and the only Frame class: every reader, graph serialiser and builder returns it.

Python Examples

import numpy as np
from molrs import Frame, Box

frame = Frame(
    {"atoms": {"element": ["O", "H", "H"], "x": [0.0, 0.76, -0.76]}},
    meta={"title": "water"},
    box=Box.cube(10.0),
)
frame["atoms"]["y"] = np.zeros(3)   # writes into the stored block
print(frame)          # Frame(blocks=['atoms'], box=yes)

__doc__ = 'Hierarchical data container exposed to Python as `molrs.Frame`.\n\nA `Frame` is a dictionary of named [`Block`](crate::core::store::block::PyBlock)s with\noptional simulation box and metadata. It is the primary exchange format for\nmolecular data across the molrs ecosystem, and the only `Frame` class:\nevery reader, graph serialiser and builder returns it.\n\n# Python Examples\n\n```python\nimport numpy as np\nfrom molrs import Frame, Box\n\nframe = Frame(\n {"atoms": {"element": ["O", "H", "H"], "x": [0.0, 0.76, -0.76]}},\n meta={"title": "water"},\n box=Box.cube(10.0),\n)\nframe["atoms"]["y"] = np.zeros(3) # writes into the stored block\nprint(frame) # Frame(blocks=[\'atoms\'], box=yes)\n```' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs._lib' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

box property

The simulation :class:Box attached to this frame, or None.

Returns:

Type Description
Box | None

Periodic simulation box, if set.

Examples:

>>> if frame.box is not None:
...     print(frame.box.volume())

coords property

The atoms block's positions as an (N, 3) float64 array (a copy), gathered from its x / y / z columns.

Assigning an (N, 3) array-like writes it back into atoms (created when the frame has none).

Raises:

Type Description
KeyError

On read, if there is no atoms block or it lacks x, y or z.

ValueError

On write, if the array is not (N, 3) or N differs from the atoms row count.

meta property

Live, write-through view of this frame's metadata.

Every door hands back a frozen value: scalars unwrap, a fixed-length vector is a tuple, a JSON array is a tuple, and a JSON object is a :class:MetaDocument. frame.meta["run"]["step"] = 3 raises TypeError. json.dumps rejects a document; use json.dumps(frame.meta["run"].copy()). Order inside a nested document is unspecified.

Returns:

Type Description
FrameMeta

Mutations of the mapping persist. dtype(k) reports the tag stored right now; a plain write re-infers it, and a :class:MetaValue fixes the dtype of that one write. A tag survives a round trip through a *.mrec frame or system, a declared sequence schema and the serde frame document.

__contains__(key) method descriptor

Return bool(key in self).

__delitem__(key) method descriptor

Delete self[key].

__getitem__(key) method descriptor

Return self[key].

__len__() method descriptor

Return len(self).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__reduce__() method descriptor

Pickle by logical state: the blocks, the typed metadata and the box.

__repr__() method descriptor

Return repr(self).

__setitem__(key, value) method descriptor

Set self[key] to value.

__setstate__(state) method descriptor

Restore the state __reduce__ produced.

copy() method descriptor

Return a deep copy of this frame.

All blocks (new column buffers), the simulation box, and typed metadata are copied into a new, independent frame backed by its own store.

Returns:

Type Description
Frame

An independent copy.

keys() method descriptor

List all block names.

Returns:

Type Description
list[str]

replicate(count) method descriptor

A new frame holding count copies of this one, concatenated block by block — the inverse of :meth:subset for count identical molecules.

Copy c of row r lands at c * nrows + r. Every endpoint of a relation block (bonds, angles, …, or any block carrying atomi..atoml) in copy c is offset by c times the row count of the block it indexes. Every other column — identifiers (id, mol_id) included — is copied verbatim; regenerate them if the copies need distinct labels. Validity masks travel; meta and the box are copied unchanged. This frame is never modified.

Parameters:

Name Type Description Default
count int

Number of copies; 0 gives zero-row blocks.

required

Returns:

Type Description
Frame

A new, independent frame.

Raises:

Type Description
ValueError

If a relation block indexes a block the frame lacks, lacks a UInt endpoint column, or the frame carries a members block.

subset(rows, block='atoms') method descriptor

A new frame holding rows rows of block, with every relation block that indexes it cut down and renumbered.

Old row rows[k] becomes new row k; every column travels. A relation block whose endpoints index block (bonds, angles, …, or any block carrying atomi..atoml) keeps only the rows whose endpoints all lie in the selection, in their original order, with each endpoint rewritten. Every other block, the box and meta are copied unchanged. Values keep their units. This frame is never modified.

Parameters:

Name Type Description Default
rows ArrayLike

A 1-D bool mask of length block.nrows (e.g. frame["atoms"]["mol_id"] == 1), which keeps its True rows in order, or 1-D integer row indices, which may be negative down to -nrows; the k-th selected old row becomes new row k.

required
block str

The block to select from (default "atoms").

'atoms'

Returns:

Type Description
Frame

A new, independent frame (no buffer shared with this one).

Raises:

Type Description
KeyError

If there is no block block.

IndexError

If rows is not 1-D, a mask has the wrong length, or an index is below -nrows.

TypeError

If rows is neither bool nor integer.

ValueError

If a row is past the end or repeated, a relation block indexing block lacks a UInt endpoint column, or the frame carries a members block.

validate() method descriptor

Judge this frame against the canonical Frame schema.

Delegates to molrs's Validator::canonical — dtype, shape, required columns, and endpoint ranges. Callers must not re-implement those checks in Python.

Raises:

Type Description
ValueError

If the frame does not conform (message is the full report).

FrameMeta

Live, write-through view of a frame's metadata.

Every door hands back a frozen value. Scalars unwrap, a fixed-length vector is a tuple (not a list), a JSON array — including one nested inside a document — is a tuple, and a JSON object is a MetaDocument. Writing a value lands in the frame. copy is the only mutable container this surface hands out; its values are still frozen, and MetaDocument::copy is that unfreeze one level down.

dtype reports the tag of the value stored right now; any plain write re-infers it. MetaValue fixes the dtype of that write only — it does not pin the key. A tag survives a round trip through a *.mrec frame or system (_meta_types), a declared sequence schema and the serde frame document.

frame.meta["run"]["step"] = 3 raises TypeError. Read, unfreeze, write back: doc = frame.meta["run"].copy(); doc["step"] = 3; frame.meta["run"] = doc. json.dumps accepts a tuple and rejects a document; the idiom is json.dumps(frame.meta["run"].copy()).

Iteration order of this mapping is insertion order. Order inside a nested MetaDocument is unspecified.

keys, values, and items are live collections.abc views in insertion order. A non-str lookup is absent; a non-str write raises TypeError. Deleting a not-yet-visited key while iterating values() or items() raises KeyError.

__doc__ = 'Live, write-through view of a frame\'s metadata.\n\nEvery door hands back a frozen value. Scalars unwrap, a fixed-length vector\nis a `tuple` (not a `list`), a JSON array — including one nested inside a\ndocument — is a `tuple`, and a JSON object is a [`MetaDocument`](PyMetaDocument).\nWriting a value lands in the frame. [`copy`](Self::copy) is the only mutable\ncontainer this surface hands out; its values are still frozen, and\n[`MetaDocument::copy`](PyMetaDocument::copy) is that unfreeze one level down.\n\n[`dtype`](Self::dtype) reports the tag of the value stored right now; any\nplain write re-infers it. [`MetaValue`](PyMetaValue) fixes the dtype of that\nwrite only — it does not pin the key. A tag survives a round trip through a\n`*.mrec` frame or system (`_meta_types`), a declared sequence schema and the\nserde frame document.\n\n`frame.meta["run"]["step"] = 3` raises `TypeError`. Read, unfreeze, write\nback: `doc = frame.meta["run"].copy(); doc["step"] = 3; frame.meta["run"] = doc`.\n`json.dumps` accepts a tuple and rejects a document; the idiom is\n`json.dumps(frame.meta["run"].copy())`.\n\nIteration order of this mapping is insertion order. Order inside a nested\n[`MetaDocument`](PyMetaDocument) is unspecified.\n\n[`keys`](Self::keys), [`values`](Self::values), and [`items`](Self::items)\nare live `collections.abc` views in insertion order. A non-`str` lookup is\nabsent; a non-`str` write raises `TypeError`. Deleting a not-yet-visited\nkey while iterating `values()` or `items()` raises `KeyError`.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs._lib' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__contains__(key) method descriptor

Return bool(key in self).

__delitem__(key) method descriptor

Delete self[key].

__eq__(value) method descriptor

Return self==value.

__ge__(value) method descriptor

Return self>=value.

__getitem__(key) method descriptor

Return self[key].

__gt__(value) method descriptor

Return self>value.

__ior__(value) method descriptor

Return self|=value.

__iter__() method descriptor

Implement iter(self).

__le__(value) method descriptor

Return self<=value.

__len__() method descriptor

Return len(self).

__lt__(value) method descriptor

Return self<value.

__ne__(value) method descriptor

Return self!=value.

__or__(value) method descriptor

Return self|value.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

__setitem__(key, value) method descriptor

Set self[key] to value.

copy() method descriptor

A plain dict snapshot; mutating it does not touch the frame.

dtype(key) method descriptor

The dtype tag stored for key, or None when the key is absent.

typed() method descriptor

The same snapshot with every dtype kept, as dict[str, MetaValue].

dict(meta) throws the tags away, which is the right default for reading; this is what a copy or a pickle has to carry instead.

MetaValue

Exact-dtype frame metadata value.

__doc__ = 'Exact-dtype frame metadata value.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

dtype property

value property

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

Every door of frame.meta hands back a frozen value: a fixed-length vector is a tuple, and a JSON object is a MetaDocument. Nested arrays are tuples. json.dumps accepts a tuple and rejects a document — use json.dumps(frame.meta["run"].copy()). Order inside a nested document is unspecified.

MetaDocument

Frozen JSON object returned by every frame.meta door.

A fixed-length vector comes back as a tuple and a JSON object as a MetaDocument. Nested arrays are tuples; nested objects are documents. Item assignment raises TypeError — the snapshot does not write through. copy() is the unfreeze: a deep plain dict whose nested documents are dicts and whose nested arrays are lists. json.dumps rejects a document and accepts that copy: json.dumps(frame.meta["run"].copy()).

Iteration order is unspecified. frame.meta itself enumerates in insertion order; the two levels differ.

__doc__ = 'Frozen JSON object returned by every ``frame.meta`` door.\n\nA fixed-length vector comes back as a ``tuple`` and a JSON object as a\n``MetaDocument``. Nested arrays are tuples; nested objects are documents.\nItem assignment raises ``TypeError`` — the snapshot does not write through.\n``copy()`` is the unfreeze: a deep plain ``dict`` whose nested documents are\ndicts and whose nested arrays are lists. ``json.dumps`` rejects a document\nand accepts that copy: ``json.dumps(frame.meta["run"].copy())``.\n\nIteration order is unspecified. ``frame.meta`` itself enumerates in\ninsertion order; the two levels differ.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__hash__ = None class-attribute

The type of the None singleton.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__contains__(key) method descriptor

Return bool(key in self).

__eq__(value) method descriptor

Return self==value.

__ge__(value) method descriptor

Return self>=value.

__getitem__(key) method descriptor

Return self[key].

__gt__(value) method descriptor

Return self>value.

__iter__() method descriptor

Implement iter(self).

__le__(value) method descriptor

Return self<=value.

__len__() method descriptor

Return len(self).

__lt__(value) method descriptor

Return self<value.

__ne__(value) method descriptor

Return self!=value.

__reduce__() method descriptor

Pickle by content: the plain copy, rebuilt through _from_plain — a document has no constructor.

__repr__() method descriptor

Return repr(self).

copy() method descriptor

Deep plain decode. Nested documents become dicts, nested arrays lists.

Topology and SMILES

Atomistic

Bases: molrs.Graph

All-atom molecular graph, exposed to Python as molrs.Atomistic.

Holds a core [Atomistic] from construction; it is never converted from a MolGraph. Subclasses Graph; the generic API operates on this leaf's own graph. Atomistic(**props): the keywords are the graph's :attr:props.

__doc__ = "All-atom molecular graph, exposed to Python as `molrs.Atomistic`.\n\nHolds a core [`Atomistic`] from construction; it is never converted from a\n`MolGraph`. Subclasses `Graph`; the generic API operates on this leaf's own\ngraph. ``Atomistic(**props)``: the keywords are the graph's :attr:`props`." class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs._lib' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

angles property

Every angle, in row order.

atoms property

Every atom, in row order.

bonds property

Every bond, in row order.

dihedrals property

Every proper dihedral, in row order.

impropers property

Every improper, in row order.

The graph's relations, selected by view class (graph.links.exact_bucket(Bond)).

n_atoms property

Number of atoms.

n_bonds property

Number of bonds.

n_nodes property

Number of entities.

n_ports property

Number of ports (0 when the graph carries none).

ports property

Every port, in row order (empty when the graph carries none).

props property

Whole-graph annotations (a name, a provenance tag): the keyword arguments the graph was built with, as a live dict. A copy, a pickle and every graph derived from this one (perception, typing, conformers, subgraphs) carry them.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

add_angle(i, j, k) method descriptor

Add an angle over three atom handles (j central).

add_atom(symbol, x=None, y=None, z=None) method descriptor

Add an atom with element symbol and optional coordinates. Returns its stable handle.

add_bond(a, b) method descriptor

Add a bond between two atom handles (default order 1.0). Returns its handle.

add_dihedral(i, j, k, l) method descriptor

Add a dihedral over four atom handles.

add_improper(i, j, k, l) method descriptor

Add an improper over four atom handles.

add_port(anchor, handle, kind, label='', order=1) method descriptor

Record a descriptor on the (anchor, handle) valence; the ports relation kind is registered on first use.

Parameters:

Name Type Description Default
anchor int

The node that keeps its place in the product.

required
handle int

A node bonded to anchor: the root of the leaving group. Endpoint order is load-bearing.

required
kind str

The notation glyph — one of "$", "<", ">", "!".

required
label str

Free-form descriptor label; "" (the default) means unnamed.

''
order int

Multiplicity of the bond this port will form, 1 to 4 (default 1).

1

Returns:

Type Description
int

The port's stable relation handle.

Raises:

Type Description
ValueError

If kind is not one of the four glyphs, handle is not bonded to anchor, order is not a definite bond number, the valence already carries a port, or a handle is stale or unknown.

add_relation(kind, nodes) method descriptor

Add a relation of kind over node handles, returning its handle.

adopt(other) method descriptor

Zero-copy adopt: move other's graph storage into self, leaving other empty. Handles in the adopted graph stay valid (the whole generational slotmap is moved, not reindexed). For taking ownership of a graph produced elsewhere without a per-node copy. Defined per leaf so it swaps the leaf's own backing store. Views of either graph taken before are stale afterwards.

bond_number(handle) method descriptor

The bond's localized (Kekulé) bond number; 0 when it has none.

bond_type(handle) method descriptor

The bond's chemical class code; 0 when it has none.

canonical_order() method descriptor

Deterministic canonical atom ordering (a list of atom handles) from the WL refinement, so two isomorphic molecules line up node-by-node.

center() method descriptor

Mass-weighted centre of every atom.

R = sum_i m_i r_i / sum_i m_i over all atoms, reading positions from x / y / z (Å) and masses from mass (g/mol). No periodic imaging: a molecule split across a box face must be unwrapped first (:meth:Box.unwrap).

Returns:

Type Description
(ndarray, shape(3), float64)

The centre in Å.

Raises:

Type Description
ValueError

If the molecule has no atoms; if an atom lacks a finite x / y / z or a finite, non-negative mass (the message names its int handle); or if the total mass is not positive.

column(key) method descriptor

The component column key, aligned to row order (length == n_nodes), as a numpy array of the column's own element type.

A f64 column is a zero-copy view that writes through to the world (col[i] = v updates the entity at row i); i32, bool and str columns are copied. The view borrows the world's storage; structural mutation (spawn/despawn) may reallocate or reorder the column and invalidate an outstanding view — re-fetch after such ops.

Every entity must carry the component: a column with a hole is a KeyError naming how many entities lack it, never a silently zero-filled array. Use :meth:validity to find the holes and :meth:get for entity-wise reads.

columns() method descriptor

Names of every component column registered on the node table (a component set on at least one entity), in no particular order.

copy() method descriptor

Return an independent deep copy of this Atomistic, with a copy of its :attr:props.

Handles are preserved (same generational keys as in self).

def_angle(a, b, c, /, **attrs) method descriptor

Add an angle a–b–c (b the vertex) and return its view.

Raises:

Type Description
ValueError

If an endpoint belongs to another graph, or an attr is refused.

def_atom(mapping=None, /, **attrs) method descriptor

Add an atom carrying the fields of mapping and attrs (a None value is skipped) and return its view.

Raises:

Type Description
TypeError

If a value is not a bool, int, float or str; the graph is then unchanged.

def_bond(a, b, /, **attrs) method descriptor

Add a single bond between two atoms of this graph and return its view.

Routes through the native writer, so the bond carries both bond facts — bond_type = 1 and bond_number = 1 — before attrs are applied.

Raises:

Type Description
ValueError

If an endpoint belongs to another graph, or an attr is refused.

def_dihedral(a, b, c, d, /, **attrs) method descriptor

Add a proper dihedral a–b–c–d and return its view.

Raises:

Type Description
ValueError

If an endpoint belongs to another graph, or an attr is refused.

def_improper(a, b, c, d, /, **attrs) method descriptor

Add an improper over a, b, c, d in its style's slot order and return its view.

Raises:

Type Description
ValueError

If an endpoint belongs to another graph, or an attr is refused.

def_port(anchor, handle_atom, kind, label='', order=1) method descriptor

Record a bonding descriptor on the (anchor, handle_atom) valence and return the port's view.

Routes through the native writer, which is where the validation lives: the anchor–handle bond check, the one-port-per-valence check, the glyph parse and the order check.

Parameters:

Name Type Description Default
anchor Atom

The atom that keeps its place in the product molecule.

required
handle_atom Atom

The atom bonded to anchor that roots the leaving group.

required
kind str

The notation glyph -- one of "$", "<", ">", "!".

required
label str

Descriptor label; "" (the default) means unnamed.

''
order int

Multiplicity of the bond this port will form, 1 to 4.

1

Raises:

Type Description
ValueError

If an endpoint belongs to another graph, kind is not one of the four glyphs, handle_atom is not bonded to anchor, that valence already carries a port, or order is not a definite bond number.

def_virtual_site(mapping=None, /, *, kind=None, **attrs) method descriptor

Add a virtual site — an atom with a vsite field naming its kind — and return its view, of class kind (VirtualSite by default, DrudeParticle or MasslessSite). An explicit vsite in attrs wins over the one kind implies.

Raises:

Type Description
TypeError

If kind is not one of the three virtual-site classes.

del_atom(*atoms) method descriptor

Remove each of atoms and every relation touching it. Their views go stale: a read raises.

Raises:

Type Description
ValueError

If an atom belongs to another graph or was removed already.

delete(h, key) method descriptor

Clear entity h's component key (no-op if absent).

key is a :class:molrs.keys.Key or str.

delete_relation_prop(kind, rh, key) method descriptor

Clear property key on relation rh of kind (no-op if absent).

despawn(h) method descriptor

Remove an entity (cascades incident relations). Errors if stale.

entities() method descriptor

All live entity handles, in row order.

extract_subgraph(centers, radius, *, regenerate_topology=False, max_ring_size=None) method descriptor

Radius ball around centers over the bond graph.

When regenerate_topology is true, only bonds are copied and angles/dihedrals are perceived on the ball. When false, higher-order terms fully inside the ball are copied from the parent.

max_ring_size closes the ball on ring systems: a ring of at most that many atoms which the radius only partly reaches comes along whole, together with everything fused or bridged to it. A cut ring is not a smaller molecule — ring perception, and with it aromaticity and every ring-aware atom type, reads the remainder as something else. The added atoms lie beyond radius, so they arrive as context: their hops are larger than the radius asked for.

The bound is not a tuning knob, it is the claim's domain. Cutting a benzene changes the chemistry; cutting a 5000-membered macrocycle changes nothing any typifier can see, while closing on it would drag the whole loop into a ball that asked for nine atoms. Pass the largest ring your typifier can actually distinguish. None disables closure; the cost then, and with a bound, follows the ball and its neighbourhood — never the size of the parent graph.

frag_id(node) method descriptor

The unit instance node came from, or None.

from_frame(frame) staticmethod

Build an Atomistic from a [Frame] (registers the chemistry kinds, then reads the relation blocks). A leaf constructor, not a conversion.

generate_topology(gen_angle=True, gen_dihedral=True, gen_improper=False, clear_existing=False) method descriptor

Perceive angle, dihedral and improper relations from the bond graph.

Angles are 2-edge paths i-j-k and proper dihedrals 3-edge paths i-j-k-l over the bonds (graph-theory via the native Topology-backed Topology). Impropers are the molecular-mechanics reading: one [centre, i, j, k] quartet per atom with exactly three neighbours, centre first, peripherals sorted — not every 3-combination at every centre of degree >= 3, which would hand an sp3 carbon four quartets. Whether a trivalent centre is planar enough to carry the term is force-field data, not a graph property, so every one is emitted.

Idempotent; clear_existing wipes existing relations of the requested kinds first. Returns (n_angles_added, n_dihedrals_added, n_impropers_added).

get(h, key) method descriptor

Read entity h's component key (None if absent).

key is a :class:molrs.keys.Key or str.

get_relation_prop(kind, rh, key) method descriptor

Read a property of relation rh of kind (None if absent).

has(h, key) method descriptor

Whether entity h has component key.

key is a :class:molrs.keys.Key or str.

has_entity(h) method descriptor

Whether h is a live entity handle.

incident_relations(nh, kind) method descriptor

Relations of kind incident to node nh, as (relation_handle, other_node_handle) pairs, via the adjacency index (O(degree)). Only arity-2 kinds are tracked in adjacency.

induced_subgraph(nodes) method descriptor

Induced subgraph on an explicit list of atom handles.

Returns (subgraph, {parent_handle: new_handle}). Stale handles raise.

inherit_frag_ids() method descriptor

Propagate each frag_id to the unlabelled degree-1 nodes hanging off a labelled one (one pass); returns how many were labelled. The relabel step after a conformer added hydrogens.

is_isomorphic(other) method descriptor

Whether self and other are isomorphic as labeled molecular graphs.

kind_arity(kind) method descriptor

Fixed endpoint count for a registered relation kind.

kinds() method descriptor

Names of all registered relation kinds.

Join port a to port b with a new anchor–anchor bond.

Both leaving groups are removed, their partial charge (e) folds onto the anchors, and the anchors are bonded with the port order. No coordinate moves.

Returns:

Type Description
int

The new bond's relation handle.

Raises:

Type Description
ValueError

If a handle names no live port, a port is stale, the two ports do not accept each other, share an anchor, their anchors are already bonded, or the leaving groups overlap or reach an anchor; the graph is unchanged.

OverflowError

If a or b is negative.

max_ring_system_size() method descriptor

Atom count of the largest fused/bridged ring system (naphthalene → 10).

Acyclic molecules → 0. Pure structure fact for molpy region typing.

merge(other) method descriptor

Structural merge of other into self.

Consumes other's storage (other is left empty). Every node handle from other is remapped; returns {old_handle: new_handle}.

Raises:

Type Description
ValueError

If a property of other contradicts the type this graph holds for that key (a string tag into an int tag column).

n_relations(kind) method descriptor

Number of relations of kind.

node_keys(h) method descriptor

Component keys currently set on entity h, in column order.

register_kind(kind, arity) method descriptor

Register a relation kind (idempotent for a matching arity).

relation_ids(kind) method descriptor

Live relation handles of kind, in row order.

Authoritative enumeration — callers must not probe opaque handle ranges. Returns an empty list for a registered kind with no relations; errors only if kind is unregistered.

relation_keys(kind, rh) method descriptor

Property keys currently set on relation rh of kind.

relation_nodes(kind, rh) method descriptor

Endpoint node handles of relation rh of kind.

remove_atom(handle) method descriptor

Remove an atom by handle, cascading incident bonds / angles / dihedrals / impropers. Errors if the handle is stale.

remove_bond(handle) method descriptor

Remove a bond by handle (a relation handle from :meth:add_bond).

Remove each of links (relation views of this graph).

Raises:

Type Description
ValueError

If a relation belongs to another graph.

remove_relation(kind, rh) method descriptor

Remove relation rh of kind.

replicate(template, rotations, translations, frag_ids) method descriptor

Grow this graph by one rigid copy of template per transform.

Copy c is template moved by rotations[c] @ r + translations[c] and every node of it is stamped frag_id = frag_ids[c]. Every relation kind of template is copied with it. Column-wise and atomic: on an error this graph is unchanged. template is never mutated. The GIL is released while the copies are written.

Parameters:

Name Type Description Default
template Atomistic

Another graph: this graph cannot be its own template.

required
rotations (ndarray, shape(N, 3, 3), float64)
required
translations (ndarray, shape(N, 3), float64)
required
frag_ids (ndarray, shape(N), int32)
required

Returns:

Type Description
list[int]

The new atom handles, copy-major.

Raises:

Type Description
ValueError

If template is this graph, on a wrong shape, disagreeing counts, or a column of template whose type contradicts the one this graph holds.

rotate(axis, angle, about=None) method descriptor

Rotate every node that has coordinates by angle radians about axis, pivoting on about (default: the origin). Returns this graph, so moves chain.

scale(factor, about=None) method descriptor

Scale every node that has coordinates by a per-axis factor about about (default: the origin). Pass [s, s, s] for a uniform scale. Returns this graph, so moves chain.

set(h, key, value) method descriptor

Set entity h's component key (value is int|float|str).

key is a :class:molrs.keys.Key or str.

set_bond_class(handle, bond_type, bond_number) method descriptor

Set a bond's chemical class and its localized bond number.

The two are set together because they are only meaningful together: a class without a number leaves the bond un-standardized, and a number without a class leaves a consumer no way to tell aromatic from double.

Parameters:

Name Type Description Default
handle int

A relation handle from :meth:add_bond.

required
bond_type int

0 unknown, 1 single, 2 double, 3 triple, 4 aromatic.

required
bond_number int

0 unknown, 1 single, 2 double, 3 triple, 4 quadruple.

required

set_bond_type(handle, bond_type) method descriptor

Set a plain (non-aromatic) bond, whose class implies its number.

Aromatic (4) implies no number — the phase is a Kekulé assignment's to decide — so it goes through :meth:set_bond_class.

set_frag_id(node, id) method descriptor

Record the unit instance node came from, under frag_id.

Raises:

Type Description
ValueError

If id exceeds the widest identifier a node column stores, or node is stale or unknown.

set_relation_prop(kind, rh, key, value) method descriptor

Set a property on relation rh of kind.

spawn() method descriptor

Spawn a new entity, returning its stable handle.

structural_hash() method descriptor

Isomorphism-invariant Weisfeiler–Lehman structural hash (int).

A stable, reproducible dedup key over the molecular graph (element / charge / aromatic node labels, bond-order edge labels): identical for a node-permuted copy, sensitive to any label or connectivity change. Reproducible across runs and processes.

to_frame(atom_fields=None) method descriptor

Export to a tabular [Frame] (atoms / bonds / angles / dihedrals / impropers blocks). Leaf-owned — self.inner.to_frame(), zero conversion.

Raises:

Type Description
ValueError

If an atom or relation property contradicts the dtype the Frame schema declares for its key (a string under "x").

topo_distances(source, max_hops=None) method descriptor

Single-source shortest-path (BFS) distances over the bond graph from source (a node handle), as (node_handle, hops) pairs for every atom reachable from source (including source itself at distance 0). Unreachable atoms (a different connected component) are omitted; an unknown source handle yields an empty list.

translate(delta) method descriptor

Translate every node that has coordinates by delta. Returns this graph, so moves chain.

validity(key) method descriptor

Validity mask (numpy bool array, copied) of component column key, aligned to row order. True where the entity at that row has the component set.

key is a :class:molrs.keys.Key or str.

CoarseGrain

Bases: molrs.Graph

Coarse-grained molecular graph, exposed to Python as molrs.CoarseGrain.

CoarseGrain(**props): the keywords are the graph's :attr:props. A bead built with def_bead(atoms=...) groups atom views of one source graph (its member world); bead["atoms"] answers with those views.

__doc__ = 'Coarse-grained molecular graph, exposed to Python as `molrs.CoarseGrain`.\n\n``CoarseGrain(**props)``: the keywords are the graph\'s :attr:`props`. A\nbead built with ``def_bead(atoms=...)`` groups atom views of one source\ngraph (its *member world*); ``bead["atoms"]`` answers with those views.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs._lib' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

beads property

Every bead, in row order.

cgbonds property

Every CG bond, in row order.

The graph's relations, selected by view class (graph.links.exact_bucket(Bond)).

n_beads property

Number of beads.

n_nodes property

Number of entities.

n_ports property

Number of ports (0 when the graph carries none).

props property

Whole-graph annotations (a name, a provenance tag): the keyword arguments the graph was built with, as a live dict. A copy, a pickle and every graph derived from this one (perception, typing, conformers, subgraphs) carry them.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

add_bead(bead_type, x=None, y=None, z=None) method descriptor

Add a bead with bead_type and optional coordinates. Returns its handle.

add_bond(a, b) method descriptor

Add a CG bond between two bead handles. Returns its handle.

add_port(anchor, handle, kind, label='', order=1) method descriptor

Record a descriptor on the (anchor, handle) valence; the ports relation kind is registered on first use.

Parameters:

Name Type Description Default
anchor int

The node that keeps its place in the product.

required
handle int

A node bonded to anchor: the root of the leaving group. Endpoint order is load-bearing.

required
kind str

The notation glyph — one of "$", "<", ">", "!".

required
label str

Free-form descriptor label; "" (the default) means unnamed.

''
order int

Multiplicity of the bond this port will form, 1 to 4 (default 1).

1

Returns:

Type Description
int

The port's stable relation handle.

Raises:

Type Description
ValueError

If kind is not one of the four glyphs, handle is not bonded to anchor, order is not a definite bond number, the valence already carries a port, or a handle is stale or unknown.

add_relation(kind, nodes) method descriptor

Add a relation of kind over node handles, returning its handle.

adopt(other) method descriptor

Zero-copy adopt: move other's graph storage into self, leaving other empty. Handles in the adopted graph stay valid (the whole generational slotmap is moved, not reindexed). For taking ownership of a graph produced elsewhere without a per-node copy. Defined per leaf so it swaps the leaf's own backing store. Views of either graph taken before are stale afterwards.

axes(beads) method descriptor

The site axes of beads, one row per listed bead, in the listed order. A site from Coarsener.coarsen carries the vector from the first bead of its group to the site; a one-bead site's axis is zero.

Parameters:

Name Type Description Default
beads Sequence[int]

Bead handles.

required

Returns:

Type Description
(ndarray, shape(k, 3), float64)

axis_x / axis_y / axis_z as stored (Å).

Raises:

Type Description
ValueError

If a handle is not a live bead of this graph, or a bead lacks a finite axis; the message names its int handle.

bead_members(bead) method descriptor

The atom handles a bead groups (empty if none recorded).

bead_types(beads) method descriptor

The bead_type of each of beads, in the listed order (a bead listed twice appears twice).

Parameters:

Name Type Description Default
beads Sequence[int]

Bead handles.

required

Returns:

Type Description
list[str]

One type per listed bead.

Raises:

Type Description
ValueError

If a handle is not a live bead of this graph, or a bead carries no bead_type; the message names its int handle.

beads_of_atom(atom) method descriptor

Bead handles whose membership includes atom, in bead-handle order.

canonical_order() method descriptor

Deterministic canonical bead ordering (a list of bead handles) from the WL refinement.

center(group) method descriptor

Mass-weighted centre of the bead group group.

R = sum_i m_i r_i / sum_i m_i over the listed beads, reading positions from x / y / z (Å) and masses from mass (g/mol). A bead listed twice counts twice. :meth:add_bead writes no mass, so give each bead one (or read it from a frame's mass column with :meth:from_frame) before asking for a centre.

No periodic imaging: the group's coordinates are used as stored. A group that straddles a box face must be unwrapped first (:meth:Box.unwrap), otherwise the centre lands between the images.

Parameters:

Name Type Description Default
group Sequence[int]

Bead handles, e.g. one group from SubgraphMatcher.find.

required

Returns:

Type Description
(ndarray, shape(3), float64)

The centre in Å.

Raises:

Type Description
ValueError

If group is empty; if a handle is not a live bead of this graph, or a bead lacks a finite x / y / z or a finite, non-negative mass (the message names its int handle); or if the total mass is not positive.

OverflowError

If a handle in group is negative (handles are unsigned ints).

column(key) method descriptor

The component column key, aligned to row order (length == n_nodes), as a numpy array of the column's own element type.

A f64 column is a zero-copy view that writes through to the world (col[i] = v updates the entity at row i); i32, bool and str columns are copied. The view borrows the world's storage; structural mutation (spawn/despawn) may reallocate or reorder the column and invalidate an outstanding view — re-fetch after such ops.

Every entity must carry the component: a column with a hole is a KeyError naming how many entities lack it, never a silently zero-filled array. Use :meth:validity to find the holes and :meth:get for entity-wise reads.

columns() method descriptor

Names of every component column registered on the node table (a component set on at least one entity), in no particular order.

copy() method descriptor

Independent deep copy, with a copy of its :attr:props and the same member world. Handles are preserved.

def_bead(mapping=None, /, **attrs) method descriptor

Add a bead carrying the fields of mapping and attrs (a None value is skipped) and return its view. An atoms field is the bead's membership: atom views of one source graph.

Raises:

Type Description
ValueError

If the member atoms do not all come from the graph earlier memberships came from.

TypeError

If a value is not a bool, int, float or str.

def_cgbond(a, b, /, **attrs) method descriptor

Add a CG bond between two beads of this graph and return its view.

Raises:

Type Description
ValueError

If an endpoint belongs to another graph, or an attr is refused.

delete(h, key) method descriptor

Clear entity h's component key (no-op if absent).

key is a :class:molrs.keys.Key or str.

delete_relation_prop(kind, rh, key) method descriptor

Clear property key on relation rh of kind (no-op if absent).

despawn(h) method descriptor

Remove an entity (cascades incident relations). Errors if stale.

entities() method descriptor

All live entity handles, in row order.

extract_subgraph(centers, radius) method descriptor

Radius ball around bead centers over CG bonds.

frag_id(node) method descriptor

The unit instance node came from, or None.

from_frame(frame) staticmethod

Build a CoarseGrain from a frame holding one molecule.

Every atoms row becomes a bead and every bonds row a CG bond (atomi / atomj are 0-based atoms rows); a members block, when present, is read back as bead membership. bead_type comes from the first column present: bead_type, then type, then type_id (rendered in decimal). Other blocks are ignored.

Parameters:

Name Type Description Default
frame Frame

One molecule in the atoms / bonds vocabulary. Select one molecule of a many-molecule frame with Frame.subset first.

required

Returns:

Type Description
CoarseGrain

Raises:

Type Description
ValueError

If the frame has no atoms rows; if mol_id holds a null row, is not an unsigned-int column, or holds more than one distinct value (the message points at Frame.subset); if none of bead_type / type / type_id is present, or the chosen one has a null row or the wrong dtype (string for bead_type / type, unsigned int for type_id); if a bond row names no bead row; or if the members block lacks an unsigned-int ibead or atom column, names no bead row, or repeats an (ibead, atom) pair.

get(h, key) method descriptor

Read entity h's component key (None if absent).

key is a :class:molrs.keys.Key or str.

get_relation_prop(kind, rh, key) method descriptor

Read a property of relation rh of kind (None if absent).

has(h, key) method descriptor

Whether entity h has component key.

key is a :class:molrs.keys.Key or str.

has_entity(h) method descriptor

Whether h is a live entity handle.

incident_relations(nh, kind) method descriptor

Relations of kind incident to node nh, as (relation_handle, other_node_handle) pairs, via the adjacency index (O(degree)). Only arity-2 kinds are tracked in adjacency.

induced_subgraph(nodes) method descriptor

Induced subgraph on bead handles. Returns (subgraph, node_map).

inherit_frag_ids() method descriptor

Propagate each frag_id to the unlabelled degree-1 nodes hanging off a labelled one (one pass); returns how many were labelled. The relabel step after a conformer added hydrogens.

is_isomorphic(other) method descriptor

Whether self and other are isomorphic as labeled bead graphs.

kind_arity(kind) method descriptor

Fixed endpoint count for a registered relation kind.

kinds() method descriptor

Names of all registered relation kinds.

Join port a to port b with a new anchor–anchor bond.

Both leaving groups are removed, their partial charge (e) folds onto the anchors, and the anchors are bonded with the port order. No coordinate moves.

Returns:

Type Description
int

The new bond's relation handle.

Raises:

Type Description
ValueError

If a handle names no live port, a port is stale, the two ports do not accept each other, share an anchor, their anchors are already bonded, or the leaving groups overlap or reach an anchor; the graph is unchanged.

OverflowError

If a or b is negative.

merge(other) method descriptor

Structural merge of other into self; other is emptied. Returns {old_handle: new_handle}.

Raises:

Type Description
ValueError

If a property of other contradicts the type this graph holds for that key (a string tag into an int tag column).

n_relations(kind) method descriptor

Number of relations of kind.

node_keys(h) method descriptor

Component keys currently set on entity h, in column order.

positions(beads) method descriptor

The positions of beads, one row per listed bead, in the listed order (a bead listed twice appears twice).

Parameters:

Name Type Description Default
beads Sequence[int]

Bead handles.

required

Returns:

Type Description
(ndarray, shape(k, 3), float64)

x / y / z as stored (Å).

Raises:

Type Description
ValueError

If a handle is not a live bead of this graph, or a bead lacks a finite x / y / z; the message names its int handle.

register_kind(kind, arity) method descriptor

Register a relation kind (idempotent for a matching arity).

relation_ids(kind) method descriptor

Live relation handles of kind, in row order.

Authoritative enumeration — callers must not probe opaque handle ranges. Returns an empty list for a registered kind with no relations; errors only if kind is unregistered.

relation_keys(kind, rh) method descriptor

Property keys currently set on relation rh of kind.

relation_nodes(kind, rh) method descriptor

Endpoint node handles of relation rh of kind.

Remove each of links (relation views of this graph).

Raises:

Type Description
ValueError

If a relation belongs to another graph.

remove_relation(kind, rh) method descriptor

Remove relation rh of kind.

replicate(template, rotations, translations, frag_ids) method descriptor

Grow this graph by one rigid copy of template per transform.

Copy c is template moved by rotations[c] @ r + translations[c] and every node of it is stamped frag_id = frag_ids[c]. Every relation kind of template is copied with it. Column-wise and atomic: on an error this graph is unchanged. template is never mutated. The GIL is released while the copies are written.

Parameters:

Name Type Description Default
template CoarseGrain

Another graph: this graph cannot be its own template.

required
rotations (ndarray, shape(N, 3, 3), float64)
required
translations (ndarray, shape(N, 3), float64)
required
frag_ids (ndarray, shape(N), int32)
required

Returns:

Type Description
list[int]

The new bead handles, copy-major.

Raises:

Type Description
ValueError

If template is this graph, on a wrong shape, disagreeing counts, or a column of template whose type contradicts the one this graph holds.

rotate(axis, angle, about=None) method descriptor

Rotate every node that has coordinates by angle radians about axis, pivoting on about (default: the origin). Returns this graph, so moves chain.

scale(factor, about=None) method descriptor

Scale every node that has coordinates by a per-axis factor about about (default: the origin). Pass [s, s, s] for a uniform scale. Returns this graph, so moves chain.

set(h, key, value) method descriptor

Set entity h's component key (value is int|float|str).

key is a :class:molrs.keys.Key or str.

set_bead_members(bead, atoms) method descriptor

Record the atom handles a bead groups (its membership), replacing any previous set. An empty list clears the membership. Handles are opaque — they belong to the caller's source (all-atom) world.

set_frag_id(node, id) method descriptor

Record the unit instance node came from, under frag_id.

Raises:

Type Description
ValueError

If id exceeds the widest identifier a node column stores, or node is stale or unknown.

set_relation_prop(kind, rh, key, value) method descriptor

Set a property on relation rh of kind.

spawn() method descriptor

Spawn a new entity, returning its stable handle.

structural_hash() method descriptor

Isomorphism-invariant Weisfeiler–Lehman structural hash (int) of the bead graph (bead-type node labels, bond-order edge labels). Shares the same [MolGraph] primitive that serves the all-atom case.

to_frame(atom_fields=None) method descriptor

Export to a tabular :class:~molrs.Frame in the shared vocabulary.

One atoms row per bead and one bonds row per CG bond (atomi / atomj are the endpoint beads' atoms rows), plus a members block when any bead records membership: one row per bead–atom pair, ibead being the bead's row in atoms and atom the opaque atom handle. Coordinates stay in Å.

Every bead property is written, mol_id included, so a CoarseGrain whose beads carry two mol_id values does not round-trip through :meth:from_frame; select one molecule with Frame.subset first.

Returns:

Type Description
Frame

Raises:

Type Description
ValueError

If a bead or bond property contradicts the dtype the Frame schema declares for its key (a string under "x").

translate(delta) method descriptor

Translate every node that has coordinates by delta. Returns this graph, so moves chain.

validity(key) method descriptor

Validity mask (numpy bool array, copied) of component column key, aligned to row order. True where the entity at that row has the component set.

key is a :class:molrs.keys.Key or str.

Graph

Domain-agnostic ECS world, exposed to Python as molrs.Graph.

__doc__ = 'Domain-agnostic ECS world, exposed to Python as `molrs.Graph`.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

n_nodes property

Number of entities.

n_ports property

Number of ports (0 when the graph carries none).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

add_port(anchor, handle, kind, label='', order=1) method descriptor

Record a descriptor on the (anchor, handle) valence; the ports relation kind is registered on first use.

Parameters:

Name Type Description Default
anchor int

The node that keeps its place in the product.

required
handle int

A node bonded to anchor: the root of the leaving group. Endpoint order is load-bearing.

required
kind str

The notation glyph — one of "$", "<", ">", "!".

required
label str

Free-form descriptor label; "" (the default) means unnamed.

''
order int

Multiplicity of the bond this port will form, 1 to 4 (default 1).

1

Returns:

Type Description
int

The port's stable relation handle.

Raises:

Type Description
ValueError

If kind is not one of the four glyphs, handle is not bonded to anchor, order is not a definite bond number, the valence already carries a port, or a handle is stale or unknown.

add_relation(kind, nodes) method descriptor

Add a relation of kind over node handles, returning its handle.

adopt(other) method descriptor

Zero-copy adopt: move other's graph storage into self, leaving other empty. Handles in the adopted graph stay valid (the whole generational slotmap is moved, not reindexed). For taking ownership of a graph produced elsewhere without a per-node copy. Defined per leaf so it swaps the leaf's own backing store. Views of either graph taken before are stale afterwards.

column(key) method descriptor

The component column key, aligned to row order (length == n_nodes), as a numpy array of the column's own element type.

A f64 column is a zero-copy view that writes through to the world (col[i] = v updates the entity at row i); i32, bool and str columns are copied. The view borrows the world's storage; structural mutation (spawn/despawn) may reallocate or reorder the column and invalidate an outstanding view — re-fetch after such ops.

Every entity must carry the component: a column with a hole is a KeyError naming how many entities lack it, never a silently zero-filled array. Use :meth:validity to find the holes and :meth:get for entity-wise reads.

columns() method descriptor

Names of every component column registered on the node table (a component set on at least one entity), in no particular order.

delete(h, key) method descriptor

Clear entity h's component key (no-op if absent).

key is a :class:molrs.keys.Key or str.

delete_relation_prop(kind, rh, key) method descriptor

Clear property key on relation rh of kind (no-op if absent).

despawn(h) method descriptor

Remove an entity (cascades incident relations). Errors if stale.

entities() method descriptor

All live entity handles, in row order.

frag_id(node) method descriptor

The unit instance node came from, or None.

get(h, key) method descriptor

Read entity h's component key (None if absent).

key is a :class:molrs.keys.Key or str.

get_relation_prop(kind, rh, key) method descriptor

Read a property of relation rh of kind (None if absent).

has(h, key) method descriptor

Whether entity h has component key.

key is a :class:molrs.keys.Key or str.

has_entity(h) method descriptor

Whether h is a live entity handle.

incident_relations(nh, kind) method descriptor

Relations of kind incident to node nh, as (relation_handle, other_node_handle) pairs, via the adjacency index (O(degree)). Only arity-2 kinds are tracked in adjacency.

inherit_frag_ids() method descriptor

Propagate each frag_id to the unlabelled degree-1 nodes hanging off a labelled one (one pass); returns how many were labelled. The relabel step after a conformer added hydrogens.

kind_arity(kind) method descriptor

Fixed endpoint count for a registered relation kind.

kinds() method descriptor

Names of all registered relation kinds.

Join port a to port b with a new anchor–anchor bond.

Both leaving groups are removed, their partial charge (e) folds onto the anchors, and the anchors are bonded with the port order. No coordinate moves.

Returns:

Type Description
int

The new bond's relation handle.

Raises:

Type Description
ValueError

If a handle names no live port, a port is stale, the two ports do not accept each other, share an anchor, their anchors are already bonded, or the leaving groups overlap or reach an anchor; the graph is unchanged.

OverflowError

If a or b is negative.

n_relations(kind) method descriptor

Number of relations of kind.

node_keys(h) method descriptor

Component keys currently set on entity h, in column order.

register_kind(kind, arity) method descriptor

Register a relation kind (idempotent for a matching arity).

relation_ids(kind) method descriptor

Live relation handles of kind, in row order.

Authoritative enumeration — callers must not probe opaque handle ranges. Returns an empty list for a registered kind with no relations; errors only if kind is unregistered.

relation_keys(kind, rh) method descriptor

Property keys currently set on relation rh of kind.

relation_nodes(kind, rh) method descriptor

Endpoint node handles of relation rh of kind.

remove_relation(kind, rh) method descriptor

Remove relation rh of kind.

set(h, key, value) method descriptor

Set entity h's component key (value is int|float|str).

key is a :class:molrs.keys.Key or str.

set_frag_id(node, id) method descriptor

Record the unit instance node came from, under frag_id.

Raises:

Type Description
ValueError

If id exceeds the widest identifier a node column stores, or node is stale or unknown.

set_relation_prop(kind, rh, key, value) method descriptor

Set a property on relation rh of kind.

spawn() method descriptor

Spawn a new entity, returning its stable handle.

validity(key) method descriptor

Validity mask (numpy bool array, copied) of component column key, aligned to row order. True where the entity at that row has the component set.

key is a :class:molrs.keys.Key or str.

SmilesIR

Intermediate representation of a parsed SMILES or SMARTS string.

This is the raw syntax tree produced by the parser. Convert it to a molecular graph via :meth:to_atomistic.

Attributes:

Name Type Description
n_components int

Number of disconnected components (fragments separated by '.' in the SMILES string).

Examples:

>>> ir = molrs.io.SmilesIR("CCO")
>>> ir.n_components
1
>>> mol = ir.to_atomistic()
>>> mol.n_atoms
3

__doc__ = 'Intermediate representation of a parsed SMILES or SMARTS string.\n\nThis is the raw syntax tree produced by the parser. Convert it to a\nmolecular graph via :meth:`to_atomistic`.\n\nAttributes\n----------\nn_components : int\n Number of disconnected components (fragments separated by ``\'.\'``\n in the SMILES string).\n\nExamples\n--------\n>>> ir = molrs.io.SmilesIR("CCO")\n>>> ir.n_components\n1\n>>> mol = ir.to_atomistic()\n>>> mol.n_atoms\n3' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.io' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

n_components property

Number of disconnected molecular components.

Fragments separated by '.' in the SMILES string are counted as separate components.

Returns:

Type Description
int

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

components() method descriptor

One graph per disconnected component, in input order.

to_atomistic returns a single graph holding every component; this returns them separately. Splitting happens on the parsed components, not by cutting the string on '.' — a separator is only a separator once the parser says so.

Returns:

Type Description
list of Atomistic

Examples:

>>> len(molrs.io.SmilesIR("CCO.O").components())
2

from_atomistic(mol, *, canonical=True, root=None, aromatic='as_marked', hydrogens='organic_subset', include_stereo=False, multi_component='error_if_multiple', organic_subset=True) builtin

Build a concrete IR from an :class:~molrs.Atomistic graph.

All science/representation choices are keyword-only flags forwarded to molrs::io::smiles::SmilesEmitOptions. This is an io alternate constructor — it does not live on Atomistic (no dependency inversion into core).

Parameters:

Name Type Description Default
mol Atomistic

Molecular graph to serialise.

required
canonical bool
True
root int or None

Optional atom handle to use as the SMILES root.

None
aromatic (as_marked, kekule_only)
"as_marked"
hydrogens (organic_subset, explicit_all, as_stored)
"organic_subset"
include_stereo bool
False
multi_component (error_if_multiple, join_dot, first_only)
"error_if_multiple"
organic_subset bool
True

from_fragment(body) builtin

Parse a fragment body — SMILES plus bonding descriptors — into its IR.

The dialect a CGsmiles fragment table writes its bodies in: [<]OCC[>], [$]COC[$]. Where the plain constructor refuses a descriptor, this one keeps it, so the IR can become a ported unit through :meth:to_template.

Parameters:

Name Type Description Default
body str

Fragment body, e.g. "[<]OCC[>]".

required

Raises:

Type Description
SmilesError

(a ValueError) if the body is not valid fragment notation.

Examples:

>>> molrs.io.SmilesIR.from_fragment("[<]OCC[>]").to_template().n_ports
2

to_atomistic() method descriptor

Convert the SMILES intermediate representation to an all-atom molecular graph.

Hydrogen atoms that are implicit in the SMILES string are not added here; use :class:Conformer with add_hydrogens=True for that.

Returns:

Type Description
Atomistic

Molecular graph with atoms and bonds.

Raises:

Type Description
ValueError

If a ring-closure digit is never closed, if the IR holds SMARTS query atoms or query bonds (which have no single atomistic reading), or if any node carries a bonding descriptor — the mark a CGsmiles fragment body writes to say where it may be joined. This is the plain conversion and it will not drop a descriptor silently; build such a body's ported unit with :meth:to_template, or expand a whole string through :meth:CGSmilesIR.to_atomistic.

Examples:

>>> mol = molrs.io.SmilesIR("c1ccccc1").to_atomistic()
>>> mol.n_atoms
6

to_template() method descriptor

Build the ported :class:~molrs.Atomistic template of this body.

The one-unit form of :meth:CGSmilesIR.templates: the heavy atoms of the body, plus one capping hydrogen handle and one port per bonding descriptor (<, >, $, with its label and bond order). No coordinates, no frag_id; an IR without descriptors gives a template without ports.

Returns:

Type Description
Atomistic

Raises:

Type Description
SmilesError

(a ValueError) if the body does not convert.

Examples:

>>> eo = molrs.io.SmilesIR.from_fragment("[<]OCC[>]").to_template()
>>> eo.n_atoms, eo.n_ports
(5, 2)

write_smarts() method descriptor

Write this IR as a SMARTS string (queries allowed).

write_smiles() method descriptor

Write this IR as a SMILES string (concrete atoms only).

Raises:

Type Description
ValueError

If the IR contains SMARTS query atoms or SMARTS-only bond operators.

Chemistry Perception

Perceive

Chemical perception, as a builder — molrs.perceive.Perceive.

Exposed to Python as molrs.perceive.Perceive. Every find_* method is graph-in / graph-out and non-mutating.

Props written (atom / bond components on the returned clone):

=============================== ========================== ========================== Method Atom props Bond props =============================== ========================== ========================== find_rings is_in_ring, n_rings is_in_ring, n_rings find_aromaticity is_aromatic bond_type, bond_number find_hydrogens — (adds H atoms) — (adds H bonds) find_stereo stereo stereo find_rotatable — is_rotatable find_bond_types — bcc_bond_type find_kekule_orders — bond_number find_equivalence_classes equiv_class — =============================== ========================== ==========================

Examples:

>>> perceived = molrs.perceive.Perceive().find_rings(mol)
>>> perceived.get(atom, "is_in_ring")
1
>>> mol.has(atom, "is_in_ring")   # the input is untouched
False

__doc__ = 'Chemical perception, as a builder — `molrs.perceive.Perceive`.\n\nExposed to Python as `molrs.perceive.Perceive`. Every ``find_*`` method is graph-in /\ngraph-out and **non-mutating**.\n\nProps written (atom / bond components on the returned clone):\n\n=============================== ========================== ==========================\nMethod Atom props Bond props\n=============================== ========================== ==========================\n``find_rings`` ``is_in_ring``, ``n_rings`` ``is_in_ring``, ``n_rings``\n``find_aromaticity`` ``is_aromatic`` ``bond_type``, ``bond_number``\n``find_hydrogens`` — (adds H atoms) — (adds H bonds)\n``find_stereo`` ``stereo`` ``stereo``\n``find_rotatable`` — ``is_rotatable``\n``find_bond_types`` — ``bcc_bond_type``\n``find_kekule_orders`` — ``bond_number``\n``find_equivalence_classes`` ``equiv_class`` —\n=============================== ========================== ==========================\n\nExamples\n--------\n>>> perceived = molrs.perceive.Perceive().find_rings(mol)\n>>> perceived.get(atom, "is_in_ring")\n1\n>>> mol.has(atom, "is_in_ring") # the input is untouched\nFalse' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.perceive' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

find_aromaticity(mol) method descriptor

Bring a molecule to the standard aromatic representation.

On return every aromatic atom carries is_aromatic, every aromatic bond carries bond_type = 4, and every bond carries an integer bond_number — the localized Lewis structure. Nothing carries a fractional order: aromaticity is a bond type, not the number 1.5.

Two inputs get two treatments. An input that already declares its aromatic bonds (a lowercase SMILES) is kekulized — the notation answered which bonds are aromatic, and only the phase is missing. An input that does not is perceived from its integer bond numbers, rings, valences and electron counts, and any assignment it already stated is kept.

Hydrogens are neither added nor required: implicit hydrogens are read off each atom's valence, so :meth:find_hydrogens stays an independent operation and running it first changes no answer here.

Parameters:

Name Type Description Default
mol Atomistic

The molecule to standardize; left untouched.

required

Returns:

Type Description
Atomistic

A clone of mol carrying both facts about every bond.

find_bond_types(mol) method descriptor

Perceive antechamber bond types and project them onto the graph.

Every bond receives a bcc_bond_type prop in {1, 2, 3, 6, 7, 8, 9} — the alphabet AM1-BCC's atom-type rules and correction table are keyed on, which distinguishes aromatic bonds (⅞) and delocalized ones (9, e.g. a carboxylate's two equivalent C–O bonds) from plain orders. The bond's type — the caller's force-field label — is neither read nor written.

Parameters:

Name Type Description Default
mol Atomistic

The molecule to perceive; left untouched.

required

Returns:

Type Description
Atomistic

A clone of mol with bcc_bond_type on every bond.

find_equivalence_classes(mol) method descriptor

Perceive charge-equivalence classes and project them onto the graph.

antechamber's default -eq 1 — the path-score partition AM1-BCC averages its AM1 charges over. Perception stops at the classes: whether to average is a property of the charge model (BccModel declares it via :meth:BccModel.needs_equivalencing), not of the graph.

Parameters:

Name Type Description Default
mol Atomistic

The molecule to perceive; left untouched.

required

Returns:

Type Description
Atomistic

A clone of mol with an equiv_class id on every atom.

find_hydrogens(mol) method descriptor

Add the hydrogens implied by each heavy atom's open valence.

Parameters:

Name Type Description Default
mol Atomistic

The molecule to fill; left untouched.

required

Returns:

Type Description
Atomistic

A new graph: the heavy-atom skeleton of mol plus the perceived hydrogens and their bonds.

Raises:

Type Description
ValueError

If repletion reports a stale atom handle on the graph it built — an invariant no molecule built through this package can break.

find_kekule_orders(mol) method descriptor

Assign a localized (Kekulé) bond_number to every aromatic bond.

Kekulization and nothing else: a molecule whose aromatic bonds are not marked yet comes back unchanged, because deciding which bonds are aromatic belongs to :meth:find_aromaticity. Reach for this directly when the input already declares its aromatic subgraph and only the phase is missing.

An aromatic bond that already carries a legal number keeps it — a file that round-trips does not come back renumbered. A system with no legal assignment is left entirely unchanged rather than half-assigned.

Parameters:

Name Type Description Default
mol Atomistic

The molecule to kekulize; left untouched.

required

Returns:

Type Description
Atomistic

A clone of mol whose aromatic bonds carry a legal localized number.

find_rings(mol) method descriptor

Perceive rings (SSSR) and project them onto the graph.

Every atom and every bond receives is_in_ring (0/1) and n_rings — including the acyclic ones, which are explicitly flagged 0 rather than left unset.

Parameters:

Name Type Description Default
mol Atomistic

The molecule to perceive; left untouched.

required

Returns:

Type Description
Atomistic

A clone of mol carrying the ring props.

find_rotatable(mol, *, unknown_bond='not_rotatable') method descriptor

Perceive rotatable bonds and project them onto the graph.

A bond is rotatable when it is a single, acyclic bond with two non-terminal endpoints. Every bond is flagged — non-rotatable ones explicitly with 0.

Parameters:

Name Type Description Default
mol Atomistic

The molecule to perceive; left untouched.

required
unknown_bond (not_rotatable, single)

What a bond with no bond_type written counts as (a graph read from connectivity alone). "not_rotatable" never guesses; "single" lets it rotate under the degree and ring rules.

"not_rotatable"

Returns:

Type Description
Atomistic

A clone of mol with is_rotatable (0/1) on every bond.

Raises:

Type Description
ValueError

If unknown_bond is not one of the two policies.

find_stereo(mol) method descriptor

Perceive stereochemistry from 3-D coordinates and project it onto the graph.

A stereo prop appears only where a real descriptor was perceived: "CW" / "CCW" on atoms, "E" / "Z" / "either" on bonds.

Parameters:

Name Type Description Default
mol Atomistic

The molecule to perceive; left untouched.

required

Returns:

Type Description
Atomistic

A clone of mol carrying a stereo prop on each perceived stereocentre and stereo bond, and none elsewhere.

RingInfo

The ring facts of a molecule: SSSR rings and the systems they fuse into.

Perception runs once, in the constructor; every method reads the result.

Not to be confused with :meth:Perceive.find_rings, which answers a different question — it decorates a graph with ring flags and hands the graph back. This type reports, and never touches the molecule.

Examples:

>>> rings = molrs.perceive.RingInfo(molrs.io.SmilesIR("c1ccccc1").to_atomistic())
>>> rings.num_rings()
1
>>> rings.ring_sizes()
[6]

__doc__ = 'The ring facts of a molecule: SSSR rings and the systems they fuse into.\n\nPerception runs once, in the constructor; every method reads the result.\n\nNot to be confused with :meth:`Perceive.find_rings`, which answers a\ndifferent question — it *decorates* a graph with ring flags and hands the\ngraph back. This type *reports*, and never touches the molecule.\n\nExamples\n--------\n>>> rings = molrs.perceive.RingInfo(molrs.io.SmilesIR("c1ccccc1").to_atomistic())\n>>> rings.num_rings()\n1\n>>> rings.ring_sizes()\n[6]' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.perceive' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

is_atom_in_ring(atom) method descriptor

Whether atom belongs to any ring.

num_atom_rings(atom) method descriptor

Number of rings containing atom.

num_rings() method descriptor

Number of rings.

ring_sizes() method descriptor

Atom count of every ring, ascending.

ring_systems() method descriptor

Rings that share at least one atom, unioned: benzene → one system of 6, naphthalene → one of 10, biphenyl → two of 6.

rings() method descriptor

Every ring, as a list of atom handles forming a closed path.

smallest_ring_containing_atom(atom) method descriptor

Size of the smallest ring containing atom, or None.

GasteigerModel

Gasteiger / PEOE partial charges — molrs.GasteigerModel.

The model with no QM input: it is handed a molecule and nothing else, and still lands on antechamber's -c gas column. The qm argument exists so that a caller holding an unknown model can call every model the same way; this one ignores it.

The loop runs to convergence (antechamber's CONVERG 1e-5, GASMAXITER 500) — a sweep count is not a knob, because the damping is geometric and where the loop stops is the answer.

Examples:

>>> molrs.GasteigerModel().assign(mol)

__doc__ = "Gasteiger / PEOE partial charges — `molrs.GasteigerModel`.\n\nThe model with **no QM input**: it is handed a molecule and nothing else, and\nstill lands on antechamber's ``-c gas`` column. The ``qm`` argument exists so that\na caller holding an unknown model can call every model the same way; this one\nignores it.\n\nThe loop runs to convergence (antechamber's ``CONVERG`` 1e-5, ``GASMAXITER`` 500)\n— a sweep count is not a knob, because the damping is geometric and where the loop\nstops *is* the answer.\n\nExamples\n--------\n>>> molrs.GasteigerModel().assign(mol)" class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff.charge' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

assign(mol, qm=None) method descriptor

The Gasteiger/PEOE charges of every atom, hydrogens included.

Parameters:

Name Type Description Default
mol Atomistic

The molecule; left untouched.

required
qm ndarray of float64

Ignored — this model needs no QM base charges. The argument exists only so that every charge model answers the same call.

None

Returns:

Type Description
ndarray of float64, shape (n_atoms,)

Raises:

Type Description
ValueError

If ATOMTYPE_GAS.DEF cannot type an atom, or GASPARM.DAT has no row for the type it assigned. An atom with no χ curve has no charge — it is not defaulted to zero.

needs_equivalencing() method descriptor

False — the PEOE charges are already symmetric by construction.

Transforms

Rigid-body moves are methods of Atomistic and CoarseGrain, not module functions: translate(delta), rotate(axis, angle, about=None) and scale(factor, about=None). Each moves every node that has coordinates in place and returns the graph itself, so moves chain: mol.translate([1, 0, 0]).rotate([0, 0, 1], 0.5).scale([2, 2, 2]).

I/O

Reader and writer names pair: read_X / write_X for one frame, read_X_trajectory / write_X_trajectory for a sequence. molrs.io returns canonical field names; molrs.io.raw keeps the format-native ones and reads trajectories eagerly.

read_pdb(file)

Read a PDB file.

Returns a molrs Frame with canonical field names (element instead of symbol, res_id instead of resid).

write_pdb(path, frame) builtin

Write a Frame to a PDB file.

Parameters:

Name Type Description Default
path str

Output file path.

required
frame Frame

Frame to write.

required

read_pdb_trajectory(file)

Read every MODEL of a PDB file as a trajectory (one Frame per MODEL).

A single-model (or MODEL-less) PDB returns a one-element list. Each frame is canonicalized like :func:read_pdb.

write_pdb_trajectory(path, frames) builtin

Write a list of Frames to a multi-MODEL PDB trajectory.

Each frame becomes one MODEL/ENDMDL block; a shared CRYST1 is written once from the first frame. Inverse of :func:read_pdb_trajectory.

Parameters:

Name Type Description Default
path str

Output file path.

required
frames list[Frame]

Frames to write, in order.

required

read_xyz(file)

Read an XYZ file.

Returns a molrs Frame with canonical field names (element instead of symbol).

write_xyz(path, frame) builtin

Write a Frame to an XYZ file.

Parameters:

Name Type Description Default
path str

Output file path.

required
frame Frame

Frame to write.

required

read_xyz_trajectory(file)

Open one XYZ trajectory, or several whose frames are concatenated, as a lazy :class:TrajectoryReader (molrs.io.raw.read_xyz_trajectory is the eager list[Frame] form).

write_xyz_trajectory(path, frames) builtin

Write Frames as one multi-frame Extended XYZ trajectory, each as :func:write_xyz writes it. Inverse of :func:read_xyz_trajectory.

read_gro(file)

Read the first frame of a GROMACS GRO file.

Returns: A molrs Frame with canonical field names (res_id, res_name, name, element, id); coordinates in Å.

Raises: OSError: If the file cannot be opened or parsed, or holds no frame.

write_gro(file, frame)

Write a single Frame to a GROMACS GRO file.

Expects canonical columns (res_id, res_name, name, id); coordinates in Å, written as nm. frame is left as it was passed.

read_gro_trajectory(file)

Read every frame of a GROMACS GRO file, in file order.

Each frame is canonicalized like :func:read_gro; a single-frame file returns a one-element list. Inverse of :func:write_gro_trajectory.

write_gro_trajectory(file, frames)

Write Frames as one multi-frame GROMACS GRO trajectory.

Each frame as :func:write_gro writes it; inverse of :func:read_gro_trajectory.

read_lammps_data(file)

Read a LAMMPS data file.

The atom style is detected from the file (column count and the optional Atoms # <style> comment).

Returns: A molrs Frame with canonical field names.

write_lammps_data(path, frame) builtin

Write a Frame to a LAMMPS data file.

Parameters:

Name Type Description Default
path str

Output file path.

required
frame Frame

Frame to write.

required

read_lammps_trajectory(traj)

Open one LAMMPS dump file, or several whose frames are concatenated, as a lazy :class:TrajectoryReader with canonical field names.

write_lammps_trajectory(path, frames, columns=None) builtin

Write Frames to a LAMMPS dump trajectory file.

Parameters:

Name Type Description Default
path str

Output file path.

required
frames list[Frame]

Frames to write.

required
columns list[str]

The dump custom column line, e.g. ["id", "element", "mol", "x", "y", "z"]. Written in the order given; a name the frame's atoms block cannot supply raises. Default writes every column it holds.

None
Notes

The dump's type field is type_id when the block has it, otherwise the string type labels (which read back as type). With both, only type_id is written. Values are formatted from each column's stored dtype; a complex column, one with more than one value per row, or a string that is empty or contains whitespace raises.

write_lammps_dump_local(path, frames) builtin

Write Frames as LAMMPS dump local (OVITO Load Trajectory bonds).

Emits ITEM: NUMBER OF ENTRIES + ITEM: ENTRIES batom1 batom2 [btype]. Rows come from entries if present, otherwise from canonical bonds.

read_dcd_trajectory(file)

Open one DCD trajectory, or several whose frames are concatenated, as a lazy :class:TrajectoryReader.

write_dcd_trajectory(path, frames) builtin

Write Frames to a DCD trajectory file.

Produces a NAMD-compatible little-endian DCD. Every frame must have the same atom count and the same box presence as the first frame. The box, if any, is taken from each frame.box.

Parameters:

Name Type Description Default
path str

Output file path.

required
frames list[Frame]

Frames to write. Must be non-empty and homogeneous in atom count.

required

Raises:

Type Description
IOError

If the file cannot be written, or a frame uses an unsupported feature (e.g. 4D dynamics / fixed atoms).

read_trr_trajectory(file)

Open one GROMACS TRR trajectory, or several whose frames are concatenated, as a lazy :class:TrajectoryReader. Random access is O(1) after a one-time index scan.

write_trr_trajectory(path, frames) builtin

Write Frames to a GROMACS TRR trajectory file (single precision).

Each frame's "atoms" block must have x/y/z (nm); optional vx/vy/vz and fx/fy/fz are written when present. The box, if any, is taken from each frame.box.

Parameters:

Name Type Description Default
path str

Output file path.

required
frames list[Frame]
required

read_xtc_trajectory(file)

Open one GROMACS XTC (compressed) trajectory, or several whose frames are concatenated, as a lazy :class:TrajectoryReader. Random access is O(1) after a one-time index scan.

write_xtc_trajectory(path, frames) builtin

Write Frames to a GROMACS XTC trajectory file (lossy compression).

Each frame's "atoms" block must have x/y/z (nm). The quantization precision is taken from frame.meta["precision"] when present, else defaults to 1000 (i.e. 0.001 nm resolution). The box, if any, is taken from each frame.box.

Parameters:

Name Type Description Default
path str

Output file path.

required
frames list[Frame]
required

read_mrec(path) builtin

Read the frame section of a *.mrec store.

Only meta (for its version) and the frame section are decoded, so another section — a trajectory, observables, one this build does not know — cannot fail the read.

Parameters:

Name Type Description Default
path

Filesystem path of the record store.

required

Returns:

Type Description
Frame

The in-memory :class:~molrs.Frame.

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, meta carries an unsupported molrec_version, the store has no frame section, or that section fails to decode.

write_mrec(path, frame, system=None, meta=None, forcefield=None) builtin

Write a snapshot as a record whose only state section is frame.

Parameters:

Name Type Description Default
path

Destination filesystem path.

required
frame

In-memory :class:~molrs.Frame to persist.

required
system

Optional system-definition :class:~molrs.Frame written beside the snapshot as the system/ section.

None
meta

The record's identity document, written to meta/ with molrec_version stamped in: a dict, a :class:~molrs.MetaDocument, or any mapping (frame.meta included). Nested tuples and documents are JSON arrays and objects.

None
forcefield

Optional force field written beside them as the forcefield/ section: a :class:~molrs.io.mrec.ForceFieldSection as given, or a :class:~molrs.ff.ForceField through its :meth:~molrs.ff.ForceField.to_section.

None

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, a section fails to encode, or the force field is invalid or has no section form.

TypeError

If meta is not a mapping or holds a value JSON cannot, or forcefield is neither a ForceField nor a ForceFieldSection.

read_mrec_system(path) builtin

Read the system section of a *.mrec store.

Only meta (for its version) and the system section are decoded.

Parameters:

Name Type Description Default
path

Filesystem path of the record store.

required

Returns:

Type Description
Frame

The in-memory :class:~molrs.Frame.

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, meta carries an unsupported molrec_version, the store has no system section, or that section fails to decode.

write_mrec_system(path, system, meta=None, forcefield=None) builtin

Write a topology as a record whose only state section is system.

Parameters:

Name Type Description Default
path

Destination filesystem path.

required
system

In-memory :class:~molrs.Frame to persist as system/.

required
meta

The record's identity document, written to meta/ with molrec_version stamped in: a dict, a :class:~molrs.MetaDocument, or any mapping (frame.meta included). Nested tuples and documents are JSON arrays and objects.

None
forcefield

Optional force field the system's types link into, written as the forcefield/ section: a :class:~molrs.io.mrec.ForceFieldSection or a :class:~molrs.ff.ForceField.

None

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, a section fails to encode, or the force field is invalid or has no section form.

TypeError

If meta is not a mapping or holds a value JSON cannot, or forcefield is neither a ForceField nor a ForceFieldSection.

read_mrec_trajectory(path) builtin

Read the trajectory section of a *.mrec store.

Only meta (for its version) and the trajectory section are decoded. A store without one reads as an empty trajectory.

Parameters:

Name Type Description Default
path

Filesystem path of the record store.

required

Returns:

Type Description
Trajectory

The in-memory :class:~molrs.Trajectory.

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, meta carries an unsupported molrec_version, or the trajectory section fails to decode.

write_mrec_trajectory(path, traj, meta=None) builtin

Write a trajectory as a record whose only state section is trajectory.

Parameters:

Name Type Description Default
path

Destination filesystem path.

required
traj

In-memory :class:~molrs.Trajectory to persist.

required
meta

The record's identity document, written to meta/ with molrec_version stamped in: a dict, a :class:~molrs.MetaDocument, or any mapping (frame.meta included). Nested tuples and documents are JSON arrays and objects.

None

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, or a frame fails to encode.

TypeError

If meta is not a mapping or holds a value JSON cannot.

read_mrec_forcefield(path) builtin

Read the forcefield section of a *.mrec store.

Only meta (for its version) and the forcefield section are decoded. The section comes back whole — every document key, every table, units as stored; :meth:molrs.ff.ForceField.from_section turns it into a force field molrs can compile.

Parameters:

Name Type Description Default
path

Filesystem path of the record store.

required

Returns:

Type Description
ForceFieldSection or None

The :class:~molrs.io.mrec.ForceFieldSection, or None when the record carries no force field.

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, meta carries an unsupported molrec_version, or the section is malformed (the forcefield chapter's refusals).

write_mrec_forcefield(path, forcefield, meta=None) builtin

Write a force field as a record whose only state section is forcefield: a force-field package (meta + forcefield/).

Parameters:

Name Type Description Default
path

Destination filesystem path.

required
forcefield

A :class:~molrs.io.mrec.ForceFieldSection, written as given, or a :class:~molrs.ff.ForceField, written through its :meth:~molrs.ff.ForceField.to_section.

required
meta

The record's identity document (see :func:write_mrec).

None

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, or the force field is invalid or has no section form.

TypeError

If meta is not a mapping, or forcefield is neither a ForceField nor a ForceFieldSection.

mrec_sections(path) builtin

Child group names at the record root (meta, frame, system, …).

Parameters:

Name Type Description Default
path

Filesystem path of the record store.

required

Returns:

Type Description
frozenset[str]

The section names, as a frozenset. Callers ask which sections are present instead of probing read_mrec / read_mrec_system and catching a missing-section error.

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, or the store is not a readable record.

read_mrec_meta(path) builtin

Read the meta document of a *.mrec store (empty when the producer wrote none).

Parameters:

Name Type Description Default
path

Filesystem path of the record store.

required

Returns:

Type Description
dict

The record-level metadata mapping, including molrec_version when the writer stamped it.

Raises:

Type Description
ValueError

If path uses a retired .zarr suffix, or meta carries a molrec_version this reader does not support.

Record files (molrs.io.mrec)

The Record files guide shows these in use.

SequenceSchema

A frame-sequence schema pinned before a run's frames are written.

The schema fixes every block, column and dtype the run may carry; :class:TrajectoryWriter refuses a frame that steps outside it. Declare it column by column, or derive it from representative frames.

__doc__ = "A frame-sequence schema pinned before a run's frames are written.\n\nThe schema fixes every block, column and dtype the run may carry;\n:class:`TrajectoryWriter` refuses a frame that steps outside it.\nDeclare it column by column, or derive it from representative frames." class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.io.mrec' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

aligned_with(block) method descriptor

The block block is aligned with, or None.

block_names() method descriptor

The declared block names.

column_names(block) method descriptor

The declared column names of block, or None when undeclared.

declare_aligned(block, target) method descriptor

Declare block aligned with target: its rows are target's rows, one for one, at every frame after carry-forward. A frame whose target changes row count must restate block; one that keeps it may let block carry forward. The two blocks keep disjoint columns, alignments do not chain, and the aligned block declares no structural shape. A reader hands back the two blocks.

declare_block(name, rows=None) method descriptor

Declare a block, with the row count a typical frame of it carries.

rows sizes the block's frame-aligned inner chunk; None leaves the byte floor to decide.

declare_column(block, column, dtype, trailing=None) method descriptor

Declare a column of block by dtype tag ("f64", "u64", "string", …) and trailing shape ([3] for an xyz column).

declare_meta(key, dtype) method descriptor

Declare a per-step metadata key by dtype tag ("f64", "i64", "f64x3", "string", "json", …). A frame that omits it is an error unless a fill is declared.

declare_meta_with_fill(key, fill, dtype=None) method descriptor

Declare a per-step metadata key with the value written for steps that omit it. The dtype is dtype when given ("f64x3", "f64", …; the fill is read at that width), else the fill's own.

declare_precision(block, column, precision) method descriptor

Declare the precision of column of block: an absolute tolerance in the column's units (1e-3 keeps Å coordinates to a thousandth).

Every frame's values are rounded to the largest power of two not above it (ties to even) before the change check and before they land, so a change below half that step is no change, and the column is stored shuffled and compressed. Pinned with the schema. A schema derived with :meth:from_frames takes each column's :meth:Block.precision.

declare_structural_shape(block, shape) method descriptor

Declare the structural shape of block (a volumetric grid); every update then carries exactly prod(shape) rows.

declare_target(block, column, target) method descriptor

Declare that column of block (u64) holds row indices into target: "<block>" of the same resolved frame, or "/<section>/<block>". Pinned with the schema; the writer refuses a frame whose resolved blocks break it. :meth:from_frames takes each column's :meth:Block.target.

from_frame(frame) staticmethod

Derive a schema from one representative frame.

from_frames(frames) staticmethod

Derive a schema from the union of several frames' blocks and columns.

meta_keys() method descriptor

The declared per-step metadata keys with their dtype tags.

precision(block, column) method descriptor

The declared precision of column of block, or None.

target(block, column) method descriptor

The declared target of column of block, or None.

TrajectoryWriter

Append-first writer for a *.mrec trajectory store.

Wraps the Rust FrameSequenceWriter over the positional-write store. Frames are buffered and landed whole inner chunks at a time on a cadence derived from the frame size (or flush_every); flush() and close() commit whatever is buffered, durably unless durable=False.

Parameters:

Name Type Description Default
path

Destination filesystem path for the store.

required
schema

The :class:SequenceSchema every appended frame is checked against.

required
flush_every

Land every this many frames instead of the derived cadence.

required
compression

How floating-point columns are compressed: None, "gzip[:level]" or "zstd[:level]". Everything else always carries gzip level 1. A column with a declared precision is byte-shuffled and compressed whatever this says: None means zstd level 3, and a named compressor replaces it.

required
durable

Whether flush() / close() fsync the touched files.

required
meta

The record's identity document, written to meta/ with molrec_version stamped in: a dict, a :class:~molrs.MetaDocument, or any mapping (frame.meta included). Nested tuples and documents are JSON arrays and objects.

required

__doc__ = 'Append-first writer for a ``*.mrec`` trajectory store.\n\nWraps the Rust ``FrameSequenceWriter`` over the positional-write store.\nFrames are buffered and landed whole inner chunks at a time on a cadence\nderived from the frame size (or ``flush_every``); ``flush()`` and\n``close()`` commit whatever is buffered, durably unless ``durable=False``.\n\nParameters\n----------\npath\n Destination filesystem path for the store.\nschema\n The :class:`SequenceSchema` every appended frame is checked\n against.\nflush_every\n Land every this many frames instead of the derived cadence.\ncompression\n How floating-point columns are compressed: ``None``,\n ``"gzip[:level]"`` or ``"zstd[:level]"``. Everything else always\n carries gzip level 1. A column with a declared precision is\n byte-shuffled and compressed whatever this says: ``None`` means\n zstd level 3, and a named compressor replaces it.\ndurable\n Whether ``flush()`` / ``close()`` fsync the touched files.\nmeta\n The record\'s identity document, written to ``meta/`` with\n ``molrec_version`` stamped in: a ``dict``, a\n :class:`~molrs.MetaDocument`, or any mapping (``frame.meta``\n included). Nested tuples and documents are JSON arrays and objects.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.io.mrec' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

committed property

Frames committed so far.

flush_every property

The landing cadence in force, in frames.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

append(frame, step=None, time=None) method descriptor

Buffer a frame. With no step the writer numbers frames 0, 1, 2, …; pass step (and optionally time, in the producer's own unit — the record stores none) for real MD numbering, or time alone to keep the automatic numbering and still record times.

Raises:

Type Description
ValueError

If the writer is closed, the frame steps outside the pinned schema, or step does not strictly increase.

close() method descriptor

Commit and release the store. Idempotent; appends after close raise.

flush() method descriptor

Commit every buffered frame (durably, unless durable=False).

open(path, *, flush_every=None, durable=True) staticmethod

Reattach to an existing store and continue appending after its last committed frame. Anything a crash left past the commit marker is rolled back first.

TrajectoryReader

Lazy one-frame cursor over a *.mrec trajectory (directory or .zip).

Wraps the Rust FrameSequence store cursor: construction opens the index only, and each read decodes exactly the asked-for frame, keeping the last decoded chunk of every column so playback through consecutive frames is a slice rather than a decode. Supports len(reader), reader[i] (negative indices included), iteration, and the with statement.

Parameters:

Name Type Description Default
path

Filesystem path of the record store, or of a packed *.mrec.zip.

required

__doc__ = 'Lazy one-frame cursor over a ``*.mrec`` trajectory (directory or ``.zip``).\n\nWraps the Rust ``FrameSequence`` store cursor: construction opens the\nindex only, and each read decodes exactly the asked-for frame, keeping the\nlast decoded chunk of every column so playback through consecutive frames\nis a slice rather than a decode. Supports ``len(reader)``, ``reader[i]``\n(negative indices included), iteration, and the ``with`` statement.\n\nParameters\n----------\npath\n Filesystem path of the record store, or of a packed\n ``*.mrec.zip``.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.io.mrec' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

step property

Step numbers of the committed frames.

time property

Time of each committed frame, when the run wrote any. The record carries no unit for it; the producer's convention applies.

__getitem__(key) method descriptor

Return self[key].

__len__() method descriptor

Return len(self).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

block_names() method descriptor

Names of every block section present in the store.

block_update_at(name, index) method descriptor

The update of block name that frame index resolves to, or None when the block is absent there.

Two consecutive frames resolving to the same update carry the same rows, so a consumer can skip re-uploading a block whose update did not change without comparing a single value.

box_at(index) method descriptor

The cell at frame index, or None when no cell has been written at or before it.

has_block(name) method descriptor

Whether the store carries a block section of this name (e.g. "bonds") with at least one committed update.

read_columns(index, columns) method descriptor

Decode one frame carrying only the named (block, column) pairs.

A viewer that needs coordinates decodes ("atoms", "x"), ("atoms", "y"), ("atoms", "z") and nothing else. Blocks none of whose columns are named are left out; the cell and per-step metadata always come along.

read_frame(index) method descriptor

Decode one committed frame.

Parameters:

Name Type Description Default
index

Zero-based frame index; negative counts from the end.

required

Returns:

Type Description
Frame

The frame at index.

Raises:

Type Description
IndexError

If index is past the commit marker.

ValueError

If a section fails to decode.

ForceFieldSection

The forcefield section of a *.mrec record: the force-field document and one :class:~molrs.Block per style table (molrec docs/spec/forcefield.md).

It holds what a store holds, whole: the document keeps every key, the tables every block, and no number is converted to another unit. :meth:molrs.ff.ForceField.to_section builds one from a force field; :meth:molrs.ff.ForceField.from_section turns one into a force field molrs can compile. Nothing is checked on construction; :meth:validate checks the chapter's rules, and every writer runs it.

Parameters:

Name Type Description Default
document

The document (name, units, styles, …) — a dict or any mapping of JSON values.

required
tables

Block name → :class:~molrs.Block (the style tables, at :meth:block_name of their style, and any other block).

required

__doc__ = "The ``forcefield`` section of a ``*.mrec`` record: the force-field\ndocument and one :class:`~molrs.Block` per style table (molrec\n``docs/spec/forcefield.md``).\n\nIt holds what a store holds, whole: the document keeps every key, the\ntables every block, and no number is converted to another unit.\n:meth:`molrs.ff.ForceField.to_section` builds one from a force field;\n:meth:`molrs.ff.ForceField.from_section` turns one into a force field\nmolrs can compile. Nothing is checked on construction; :meth:`validate`\nchecks the chapter's rules, and every writer runs it.\n\nParameters\n----------\ndocument\n The document (``name``, ``units``, ``styles``, …) — a\n ``dict`` or any mapping of JSON values.\ntables\n Block name → :class:`~molrs.Block` (the style tables, at\n :meth:`block_name` of their style, and any other block)." class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.io.mrec' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

document property

The force-field document, as a fresh dict.

name property

The document's name, or None.

tables property

Block name → :class:~molrs.Block, in stored order. Each block is a copy: editing it does not change the section.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

block_name(category, style) staticmethod

The block name of a style's table: <category>.<style>, every byte of the style outside A-Z a-z 0-9 - _ written %XX (block_name("pair", "lj/cut") is "pair.lj%2Fcut").

table(category, style) method descriptor

The table of the (category, style) style (a copy), or None.

validate() method descriptor

Check the section against the forcefield chapter.

Raises:

Type Description
ValueError

Naming the first rule broken (units, a duplicate style, a missing table, a duplicate or null type name, the wrong endpoint columns, a parameter dtype, a pair / pair14 table pricing one unordered pair twice with different parameters, …).

pack(path) builtin

Pack a closed *.mrec directory into a sibling *.mrec.zip (every entry stored, byte-identical to the files it replaces) and remove the directory.

Returns:

Type Description
str

The path of the archive.

Other formats

read_chgcar(path) builtin

Read a VASP CHGCAR or CHGDIF file.

Returns a Frame containing:

  • "atoms" block with symbol, x, y, z (Cartesian Å)
  • box: triclinic periodic box
  • grid "chgcar": a :class:Grid with at least "total" (and "diff" for spin-polarised ISPIN=2 calculations)

The volumetric values are stored raw (ρ × V_cell, units e). Divide by simbox.volume() to get charge density in e/ų.

Parameters:

Name Type Description Default
path str

Path to a CHGCAR or CHGDIF file.

required

Returns:

Type Description
Frame

Raises:

Type Description
ValueError

On parse errors.

IOError

If the file cannot be opened.

Examples:

>>> frame = molrs.io.read_chgcar("CHGCAR")
>>> grid = frame["chgcar"]
>>> total = grid["total"]          # shape (nx, ny, nz)
>>> density = total / frame.box.volume()

read_cube(path) builtin

Read a Gaussian Cube file.

Returns a Frame containing:

  • "atoms" block with element, x, y, z, atomic_number, charge
  • grid "cube": a :class:Grid with "density" (scalar field) or "mo_<idx>" arrays (MO variant)

Values are stored as-is from the file (no unit conversion). The unit system is recorded in frame.meta["cube_units"] ("bohr" or "angstrom").

Parameters:

Name Type Description Default
path str

Path to a .cube file.

required

Returns:

Type Description
Frame

Raises:

Type Description
ValueError

On parse errors.

IOError

If the file cannot be opened.

Examples:

>>> frame = molrs.io.read_cube("density.cube")
>>> grid = frame["cube"]
>>> density = grid["density"]       # shape (nx, ny, nz)

write_cube(path, frame) builtin

Write a Frame to a Gaussian Cube file.

The Frame must contain a "cube" grid and an "atoms" block.

Parameters:

Name Type Description Default
path str

Output file path.

required
frame Frame

Frame to write.

required

LAMMPSTrajReader

Lazy, indexed reader for LAMMPS dump trajectory files.

Unlike :func:read_lammps_trajectory, this does not parse every frame upfront. The underlying file stays open and frames are parsed on demand via byte-offset seeks. Random access (reader[i], read_step(i)) triggers a one-time index scan for ITEM: TIMESTEP markers; subsequent accesses are O(1) seeks plus one frame parse.

Use this for long trajectories where you only need a subset of frames or want to walk lazily without holding all frames in memory.

Parameters:

Name Type Description Default
path str

Path to a LAMMPS dump file (.lammpstrj). Gzip files are auto-detected by extension and decompressed into memory.

required

Examples:

>>> reader = molrs.LAMMPSTrajReader("trajectory.lammpstrj")
>>> len(reader)
1000
>>> frame = reader[42]
>>> for frame in reader:
...     pass

__doc__ = 'Lazy, indexed reader for LAMMPS dump trajectory files.\n\nUnlike :func:`read_lammps_trajectory`, this does **not** parse every frame\nupfront. The underlying file stays open and frames are parsed on demand\nvia byte-offset seeks. Random access (``reader[i]``, ``read_step(i)``)\ntriggers a one-time index scan for ``ITEM: TIMESTEP`` markers; subsequent\naccesses are O(1) seeks plus one frame parse.\n\nUse this for long trajectories where you only need a subset of frames\nor want to walk lazily without holding all frames in memory.\n\nParameters\n----------\npath : str\n Path to a LAMMPS dump file (``.lammpstrj``). Gzip files are\n auto-detected by extension and decompressed into memory.\n\nExamples\n--------\n>>> reader = molrs.LAMMPSTrajReader("trajectory.lammpstrj")\n>>> len(reader)\n1000\n>>> frame = reader[42]\n>>> for frame in reader:\n... pass' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.io.raw' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

n_frames property

Number of frames in the trajectory (triggers index construction).

__getitem__(key) method descriptor

Return self[key].

__iter__() method descriptor

Implement iter(self).

__len__() method descriptor

Return len(self).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__next__() method descriptor

Implement next(self).

__repr__() method descriptor

Return repr(self).

build_index() method descriptor

Force the byte-offset index to be built now.

The index is built lazily on the first call to __len__, __getitem__, or read_step. Call this explicitly to amortize the cost upfront — useful when timing only the random-access path.

close() method descriptor

Release the underlying file handle. Further reads raise ValueError.

read_all() method descriptor

Eagerly read every frame into a list.

read_frame(index) method descriptor

Read a single frame by index (supports negative indexing).

Raises IndexError if out of range. molpy-aligned.

read_frames(indices) method descriptor

Read an explicit list of frame indices (each may be negative).

read_range(start=0, stop=None, step=1) method descriptor

Read a contiguous range of frames, Python-slice style.

DCDTrajReader

Lazy, indexed reader for DCD trajectory files.

Unlike :func:read_dcd_trajectory, this does not load every frame upfront. The underlying file stays open and frames are parsed on demand via byte-offset seeks computed from the DCD header. The header is parsed lazily on the first call to __len__, __getitem__, or read_step (or eagerly via build_index()); subsequent random access (reader[i], read_step(i)) is an O(1) seek plus one frame parse.

Use this for long trajectories where you only need a subset of frames or want to walk lazily without holding all frames in memory.

Parameters:

Name Type Description Default
path str

Path to a .dcd file.

required

Examples:

>>> reader = molrs.DCDTrajReader("trajectory.dcd")
>>> len(reader)
1000
>>> frame = reader[42]
>>> for frame in reader:
...     pass

__doc__ = 'Lazy, indexed reader for DCD trajectory files.\n\nUnlike :func:`read_dcd_trajectory`, this does **not** load every frame upfront. The\nunderlying file stays open and frames are parsed on demand via byte-offset\nseeks computed from the DCD header. The header is parsed lazily on the\nfirst call to ``__len__``, ``__getitem__``, or ``read_step`` (or eagerly\nvia ``build_index()``); subsequent random access (``reader[i]``,\n``read_step(i)``) is an O(1) seek plus one frame parse.\n\nUse this for long trajectories where you only need a subset of frames or\nwant to walk lazily without holding all frames in memory.\n\nParameters\n----------\npath : str\n Path to a ``.dcd`` file.\n\nExamples\n--------\n>>> reader = molrs.DCDTrajReader("trajectory.dcd")\n>>> len(reader)\n1000\n>>> frame = reader[42]\n>>> for frame in reader:\n... pass' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.io.raw' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

n_frames property

Number of frames in the trajectory (triggers header parsing).

__getitem__(key) method descriptor

Return self[key].

__iter__() method descriptor

Implement iter(self).

__len__() method descriptor

Return len(self).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__next__() method descriptor

Implement next(self).

__repr__() method descriptor

Return repr(self).

build_index() method descriptor

Force the DCD header to be parsed now.

The header is parsed lazily on the first call to __len__, __getitem__, or read_step. Call this explicitly to amortize the cost upfront — useful when timing only the random-access path.

close() method descriptor

Release the underlying file handle. Further reads raise ValueError.

read_all() method descriptor

Eagerly read every frame into a list.

read_frame(index) method descriptor

Read a single frame by index (supports negative indexing).

Raises IndexError if out of range. molpy-aligned.

read_frames(indices) method descriptor

Read an explicit list of frame indices (each may be negative).

read_range(start=0, stop=None, step=1) method descriptor

Read a contiguous range of frames, Python-slice style.

XYZTrajReader

Lazy, indexed reader for multi-frame XYZ trajectory files.

The molrs-native counterpart to :func:read_xyz_trajectory (which eagerly returns list[Frame]). Frames are parsed on demand; the frame-offset index is built lazily on first random access or eagerly via build_index().

Exposes the same molpy BaseTrajectoryReader surface as :class:DCDTrajReader and :class:LAMMPSTrajReader: read_frame, read_frames, read_range, read_all, n_frames, slicing, close(), and context-manager use.

Parameters:

Name Type Description Default
path str

Path to a multi-frame .xyz file.

required

Examples:

>>> reader = molrs.XYZTrajReader("traj.xyz")
>>> reader.n_frames
50
>>> reader[-1]["atoms"]["x"]

__doc__ = 'Lazy, indexed reader for multi-frame XYZ trajectory files.\n\nThe molrs-native counterpart to :func:`read_xyz_trajectory` (which eagerly\nreturns ``list[Frame]``). Frames are parsed on demand; the frame-offset\nindex is built lazily on first random access or eagerly via\n``build_index()``.\n\nExposes the same molpy ``BaseTrajectoryReader`` surface as\n:class:`DCDTrajReader` and :class:`LAMMPSTrajReader`: ``read_frame``,\n``read_frames``, ``read_range``, ``read_all``, ``n_frames``, slicing,\n``close()``, and context-manager use.\n\nParameters\n----------\npath : str\n Path to a multi-frame ``.xyz`` file.\n\nExamples\n--------\n>>> reader = molrs.XYZTrajReader("traj.xyz")\n>>> reader.n_frames\n50\n>>> reader[-1]["atoms"]["x"]' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.io.raw' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

n_frames property

Number of frames in the trajectory (triggers index construction).

__getitem__(key) method descriptor

Return self[key].

__iter__() method descriptor

Implement iter(self).

__len__() method descriptor

Return len(self).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__next__() method descriptor

Implement next(self).

__repr__() method descriptor

Return repr(self).

build_index() method descriptor

Force the frame-offset index to be built now.

close() method descriptor

Release the underlying file handle. Further reads raise ValueError.

read_all() method descriptor

Eagerly read every frame into a list.

read_frame(index) method descriptor

Read a single frame by index (supports negative indexing).

Raises IndexError if out of range. molpy-aligned.

read_frames(indices) method descriptor

Read an explicit list of frame indices (each may be negative).

read_range(start=0, stop=None, step=1) method descriptor

Read a contiguous range of frames, Python-slice style.

A region is a solid with a signed distance to its boundary: every class answers contains, distance (negative inside) and bounds, and composes with &, | and ~. Outside a shape is ~shape; a shell is outer & ~inner. TriMesh is the surface a Polyhedron is bounded by and what molrs.io.read_stl reads (the WASM binding reads the same file with readSTL into Mesh).

Sphere

Solid sphere region.

Exposed to Python as molrs.Sphere.

Parameters:

Name Type Description Default
center numpy.ndarray, shape (3,), dtype float

Center of the sphere.

required
radius float

Radius of the sphere.

required

Examples:

>>> s = Sphere(np.array([0, 0, 0]), 5.0)
>>> mask = s.contains(points)
>>> shell = s & ~Sphere(np.array([0, 0, 0]), 2.0)
>>> d = s.distance(points)  # negative inside

__doc__ = 'Solid sphere region.\n\nExposed to Python as `molrs.Sphere`.\n\nParameters\n----------\ncenter : numpy.ndarray, shape (3,), dtype float\n Center of the sphere.\nradius : float\n Radius of the sphere.\n\nExamples\n--------\n>>> s = Sphere(np.array([0, 0, 0]), 5.0)\n>>> mask = s.contains(points)\n>>> shell = s & ~Sphere(np.array([0, 0, 0]), 2.0)\n>>> d = s.distance(points) # negative inside' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__and__(value) method descriptor

Return self&value.

__invert__() method descriptor

~self

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__or__(value) method descriptor

Return self|value.

__rand__(value) method descriptor

Return value&self.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

bounds() method descriptor

Axis-aligned bounding box, shape (3, 2): [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

contains(points) method descriptor

Test which points are inside this region.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Test points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside (the boundary counts as inside).

Raises:

Type Description
ValueError

If points does not have 3 columns.

distance(points) method descriptor

Signed distance of each point to the boundary.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Query points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype float

Negative inside, positive outside, zero on the boundary; same unit as the coordinates.

Raises:

Type Description
ValueError

If points does not have 3 columns.

Cuboid

Axis-aligned cuboid (box) region, exposed to Python as molrs.Cuboid.

A point is inside when origin[d] <= p[d] <= origin[d] + lengths[d] on every axis.

__doc__ = 'Axis-aligned cuboid (box) region, exposed to Python as `molrs.Cuboid`.\n\nA point is inside when `origin[d] <= p[d] <= origin[d] + lengths[d]` on\nevery axis.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__and__(value) method descriptor

Return self&value.

__invert__() method descriptor

~self

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__or__(value) method descriptor

Return self|value.

__rand__(value) method descriptor

Return value&self.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

bounds() method descriptor

Axis-aligned bounding box, shape (3, 2): [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

contains(points) method descriptor

Test which points are inside this region.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Test points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside (the boundary counts as inside).

Raises:

Type Description
ValueError

If points does not have 3 columns.

distance(points) method descriptor

Signed distance of each point to the boundary.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Query points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype float

Negative inside, positive outside, zero on the boundary; same unit as the coordinates.

Raises:

Type Description
ValueError

If points does not have 3 columns.

Parallelepiped

General parallelepiped (oblique box) region, exposed as molrs.Parallelepiped.

Defined by an origin corner and a 3×3 edge matrix h whose columns are the three edge vectors. A point is inside when its fractional coordinates lie in the closed cell [0, 1]³; distance is measured perpendicular to the bounding planes, in the input length unit.

This is pure geometric containment — not a periodic simulation box. For PBC / MIC / wrap, use :class:molrs.Box.

__doc__ = 'General parallelepiped (oblique box) region, exposed as `molrs.Parallelepiped`.\n\nDefined by an origin corner and a 3×3 edge matrix ``h`` whose **columns**\nare the three edge vectors. A point is inside when its fractional\ncoordinates lie in the closed cell ``[0, 1]³``; ``distance`` is measured\nperpendicular to the bounding planes, in the input length unit.\n\nThis is pure geometric containment — **not** a periodic simulation box.\nFor PBC / MIC / wrap, use :class:`molrs.Box`.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__and__(value) method descriptor

Return self&value.

__invert__() method descriptor

~self

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__or__(value) method descriptor

Return self|value.

__rand__(value) method descriptor

Return value&self.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

bounds() method descriptor

Axis-aligned bounding box, shape (3, 2): [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

contains(points) method descriptor

Test which points are inside this region.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Test points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside (the boundary counts as inside).

Raises:

Type Description
ValueError

If points does not have 3 columns.

cube(a, origin) staticmethod

Cubic parallelepiped of edge a with the given origin.

Raises:

Type Description
ValueError

If a is not positive.

distance(points) method descriptor

Signed distance of each point to the boundary.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Query points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype float

Negative inside, positive outside, zero on the boundary; same unit as the coordinates.

Raises:

Type Description
ValueError

If points does not have 3 columns.

ortho(lengths, origin) staticmethod

Axis-aligned orthorhombic (or cubic) parallelepiped from edge lengths.

Raises:

Type Description
ValueError

If a length is not positive.

volume() method descriptor

Signed volume det(h).

HalfSpace

One side of a plane, exposed as molrs.HalfSpace.

Inside is the side the normal points away from (n · (x − p) <= 0); the other side is ~HalfSpace(...). distance is the exact distance to the plane.

Parameters:

Name Type Description Default
normal numpy.ndarray, shape (3,), dtype float

Outward normal (any non-zero length).

required
point numpy.ndarray, shape (3,), dtype float

A point on the plane.

required

__doc__ = 'One side of a plane, exposed as `molrs.HalfSpace`.\n\nInside is the side the ``normal`` points *away* from (``n · (x − p) <= 0``);\nthe other side is ``~HalfSpace(...)``. ``distance`` is the exact distance\nto the plane.\n\nParameters\n----------\nnormal : numpy.ndarray, shape (3,), dtype float\n Outward normal (any non-zero length).\npoint : numpy.ndarray, shape (3,), dtype float\n A point on the plane.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__and__(value) method descriptor

Return self&value.

__invert__() method descriptor

~self

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__or__(value) method descriptor

Return self|value.

__rand__(value) method descriptor

Return value&self.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

bounds() method descriptor

Axis-aligned bounding box, shape (3, 2): [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

contains(points) method descriptor

Test which points are inside this region.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Test points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside (the boundary counts as inside).

Raises:

Type Description
ValueError

If points does not have 3 columns.

distance(points) method descriptor

Signed distance of each point to the boundary.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Query points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype float

Negative inside, positive outside, zero on the boundary; same unit as the coordinates.

Raises:

Type Description
ValueError

If points does not have 3 columns.

normal() method descriptor

Unit outward normal, shape (3,).

Cylinder

Finite capped cylinder, exposed as molrs.Cylinder.

Parameters:

Name Type Description Default
base numpy.ndarray, shape (3,), dtype float

Centre of the first cap.

required
axis numpy.ndarray, shape (3,), dtype float

Direction from the first cap to the second (any non-zero length).

required
radius float
required
length float

Distance between the caps.

required

__doc__ = 'Finite capped cylinder, exposed as `molrs.Cylinder`.\n\nParameters\n----------\nbase : numpy.ndarray, shape (3,), dtype float\n Centre of the first cap.\naxis : numpy.ndarray, shape (3,), dtype float\n Direction from the first cap to the second (any non-zero length).\nradius : float\nlength : float\n Distance between the caps.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__and__(value) method descriptor

Return self&value.

__invert__() method descriptor

~self

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__or__(value) method descriptor

Return self|value.

__rand__(value) method descriptor

Return value&self.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

bounds() method descriptor

Axis-aligned bounding box, shape (3, 2): [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

contains(points) method descriptor

Test which points are inside this region.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Test points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside (the boundary counts as inside).

Raises:

Type Description
ValueError

If points does not have 3 columns.

distance(points) method descriptor

Signed distance of each point to the boundary.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Query points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype float

Negative inside, positive outside, zero on the boundary; same unit as the coordinates.

Raises:

Type Description
ValueError

If points does not have 3 columns.

Ellipsoid

Axis-aligned ellipsoid, exposed as molrs.Ellipsoid.

distance has the exact sign; its magnitude is a lower bound on the Euclidean distance (exact along the shortest semi-axis).

Parameters:

Name Type Description Default
center numpy.ndarray, shape (3,), dtype float
required
semi_axes numpy.ndarray, shape (3,), dtype float

Semi-axes along x, y, z.

required

__doc__ = 'Axis-aligned ellipsoid, exposed as `molrs.Ellipsoid`.\n\n``distance`` has the exact sign; its magnitude is a lower bound on the\nEuclidean distance (exact along the shortest semi-axis).\n\nParameters\n----------\ncenter : numpy.ndarray, shape (3,), dtype float\nsemi_axes : numpy.ndarray, shape (3,), dtype float\n Semi-axes along x, y, z.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__and__(value) method descriptor

Return self&value.

__invert__() method descriptor

~self

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__or__(value) method descriptor

Return self|value.

__rand__(value) method descriptor

Return value&self.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

bounds() method descriptor

Axis-aligned bounding box, shape (3, 2): [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

contains(points) method descriptor

Test which points are inside this region.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Test points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside (the boundary counts as inside).

Raises:

Type Description
ValueError

If points does not have 3 columns.

distance(points) method descriptor

Signed distance of each point to the boundary.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Query points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype float

Negative inside, positive outside, zero on the boundary; same unit as the coordinates.

Raises:

Type Description
ValueError

If points does not have 3 columns.

TriMesh

Triangle surface mesh: a vertex table plus faces indexing into it.

Exposed to Python as molrs.TriMesh. Lengths are whatever unit the vertices are in; :meth:scaled converts.

Examples:

>>> mesh = molrs.io.read_stl("cavity.stl").scaled(4.18)
>>> mesh.is_watertight()
True
>>> region = molrs.Polyhedron(mesh)

__doc__ = 'Triangle surface mesh: a vertex table plus faces indexing into it.\n\nExposed to Python as `molrs.TriMesh`. Lengths are whatever unit the\nvertices are in; :meth:`scaled` converts.\n\nExamples\n--------\n>>> mesh = molrs.io.read_stl("cavity.stl").scaled(4.18)\n>>> mesh.is_watertight()\nTrue\n>>> region = molrs.Polyhedron(mesh)' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

n_faces property

Number of faces.

n_vertices property

Number of vertices.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

bounds() method descriptor

Axis-aligned bounds, shape (3, 2): [[xmin, xmax], ...].

Raises:

Type Description
ValueError

If the mesh has no vertices.

faces() method descriptor

The face list, shape (F, 3), dtype uint32.

is_watertight() method descriptor

Whether every directed edge has exactly one opposite — a closed surface, the gate a :class:Polyhedron needs.

scaled(factor) method descriptor

The same mesh with every coordinate multiplied by factor.

vertices() method descriptor

The vertex table, shape (V, 3).

Polyhedron

Solid bounded by a watertight :class:TriMesh, exposed as molrs.Polyhedron.

Where the mesh came from is not the region's concern — an STL read with :func:molrs.io.read_stl, or a mesh built in memory. Scale the mesh first (mesh.scaled(s)) when the file is not in your working unit.

Examples:

>>> cavity = molrs.Polyhedron(molrs.io.read_stl("cavity.stl").scaled(4.18))
>>> inside = cavity.contains(points)

__doc__ = 'Solid bounded by a watertight :class:`TriMesh`, exposed as `molrs.Polyhedron`.\n\nWhere the mesh came from is not the region\'s concern — an STL read with\n:func:`molrs.io.read_stl`, or a mesh built in memory. Scale the mesh\nfirst (``mesh.scaled(s)``) when the file is not in your working unit.\n\nExamples\n--------\n>>> cavity = molrs.Polyhedron(molrs.io.read_stl("cavity.stl").scaled(4.18))\n>>> inside = cavity.contains(points)' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__and__(value) method descriptor

Return self&value.

__invert__() method descriptor

~self

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__or__(value) method descriptor

Return self|value.

__rand__(value) method descriptor

Return value&self.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

bounds() method descriptor

Axis-aligned bounding box, shape (3, 2): [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

contains(points) method descriptor

Test which points are inside this region.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Test points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside (the boundary counts as inside).

Raises:

Type Description
ValueError

If points does not have 3 columns.

distance(points) method descriptor

Signed distance of each point to the boundary.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Query points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype float

Negative inside, positive outside, zero on the boundary; same unit as the coordinates.

Raises:

Type Description
ValueError

If points does not have 3 columns.

mesh() method descriptor

The bounding surface (a copy).

SphereUnion

Union of spheres, exposed as molrs.SphereUnion — atoms as a region.

One sphere per row of centers with its own radius (a scalar is broadcast). With radii = r_vdw + r_probe the union is the solvent-accessible volume and ~SphereUnion(...) the space a probe centre can occupy. Pass box to make the union periodic on the box's periodic axes (minimum image); without it the spheres sit in open space.

Examples:

>>> polymer = molrs.SphereUnion(centers, 0.5 * sigma + 1.0, box=frame.box)
>>> void = ~polymer

__doc__ = "Union of spheres, exposed as `molrs.SphereUnion` — atoms as a region.\n\nOne sphere per row of ``centers`` with its own radius (a scalar is\nbroadcast). With ``radii = r_vdw + r_probe`` the union is the\nsolvent-accessible volume and ``~SphereUnion(...)`` the space a probe\ncentre can occupy. Pass ``box`` to make the union periodic on the box's\nperiodic axes (minimum image); without it the spheres sit in open space.\n\nExamples\n--------\n>>> polymer = molrs.SphereUnion(centers, 0.5 * sigma + 1.0, box=frame.box)\n>>> void = ~polymer" class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

box property

The box the union lives in (free when constructed without one).

n_spheres property

Number of spheres.

__and__(value) method descriptor

Return self&value.

__invert__() method descriptor

~self

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__or__(value) method descriptor

Return self|value.

__rand__(value) method descriptor

Return value&self.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

bounds() method descriptor

Axis-aligned bounding box, shape (3, 2): [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

centers() method descriptor

Sphere centres as stored (wrapped on periodic axes), shape (N, 3).

contains(points) method descriptor

Test which points are inside this region.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Test points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside (the boundary counts as inside).

Raises:

Type Description
ValueError

If points does not have 3 columns.

distance(points) method descriptor

Signed distance of each point to the boundary.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Query points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype float

Negative inside, positive outside, zero on the boundary; same unit as the coordinates.

Raises:

Type Description
ValueError

If points does not have 3 columns.

radii() method descriptor

Sphere radii, shape (N,).

Region

Composed region produced by &, |, or ~ operators.

Exposed to Python as molrs.Region. Region(source) clones any region object into this class; otherwise instances come from the operators.

Pickling records the composition as a tree of the operand objects, so a composed region round-trips through whatever its leaves pickle as.

Examples:

>>> shell = Sphere(c, 5.0) & ~Sphere(c, 3.0)
>>> shell.contains(points)

__doc__ = 'Composed region produced by ``&``, ``|``, or ``~`` operators.\n\nExposed to Python as `molrs.Region`. ``Region(source)`` clones any region\nobject into this class; otherwise instances come from the operators.\n\nPickling records the composition as a tree of the operand objects, so a\ncomposed region round-trips through whatever its leaves pickle as.\n\nExamples\n--------\n>>> shell = Sphere(c, 5.0) & ~Sphere(c, 3.0)\n>>> shell.contains(points)' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__and__(value) method descriptor

Return self&value.

__invert__() method descriptor

~self

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__or__(value) method descriptor

Return self|value.

__rand__(value) method descriptor

Return value&self.

__repr__() method descriptor

Return repr(self).

__ror__(value) method descriptor

Return value|self.

bounds() method descriptor

Axis-aligned bounding box, shape (3, 2): [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

contains(points) method descriptor

Test which points are inside this region.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Test points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype bool

True for points inside (the boundary counts as inside).

Raises:

Type Description
ValueError

If points does not have 3 columns.

distance(points) method descriptor

Signed distance of each point to the boundary.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float

Query points.

required

Returns:

Type Description
numpy.ndarray, shape (N,), dtype float

Negative inside, positive outside, zero on the boundary; same unit as the coordinates.

Raises:

Type Description
ValueError

If points does not have 3 columns.

read_stl(path) builtin

Read a LAMMPS data file and return a Frame.

Parameters:

Name Type Description Default
path str

Path to a LAMMPS data file on disk.

required

Returns:

Type Description
Frame

Parsed molecular data with atoms, bonds, and box metadata.

Raises:

Type Description
IOError

If the file cannot be opened or parsed.

Examples:

>>> frame = molrs.io.read_lammps_data("system.data")
>>> atoms = frame["atoms"]
Read an STL surface mesh (ASCII or binary) into a [`PyTriMesh`].

The file's numbers are taken as they are; convert with TriMesh.scaled when the file is not in the length unit you work in.

NeighborList

Neighbor search over one point set, exposed to Python as molrs.NeighborList.

The engine owns the cutoff, the backend that indexes space, and the box the index was built for, and keeps the two halves of the job apart: build / update index coordinates and enumerate nothing, neighbors turns the index into a :class:Neighbors table. The pairs are half-shell — each unordered pair once, with i < j. A directed search against a second point set is :class:NeighborQuery.

Parameters:

Name Type Description Default
cutoff float

Interaction radius in Å. Fixed at construction because it sets the cell width of the index.

required

Raises:

Type Description
ValueError

If cutoff is not positive.

Passing the engine into :class:`VerletSkin` **moves** it: the list is
consumed, and every later method call on it raises ``ValueError`` — build a
new ``NeighborList`` instead.

Examples:

>>> nl = molrs.NeighborList(3.0)          # O(N) cell-list backend
>>> nl.build(points, box)                 # index only — no pair table
>>> neigh = nl.neighbors()                # both columns (the default)
>>> lean = nl.neighbors(disp=False)       # indices + d² only
>>> nl.update(moved_points)               # re-index in the same box

__doc__ = 'Neighbor search over one point set, exposed to Python as\n`molrs.NeighborList`.\n\nThe engine owns the cutoff, the backend that indexes space, and the box the\nindex was built for, and keeps the two halves of the job apart: ``build`` /\n``update`` index coordinates and enumerate nothing, ``neighbors`` turns the\nindex into a :class:`Neighbors` table. The pairs are half-shell — each\nunordered pair once, with ``i < j``. A directed search against a *second*\npoint set is :class:`NeighborQuery`.\n\nParameters\n----------\ncutoff : float\n Interaction radius in Å. Fixed at construction because it sets the cell\n width of the index.\n\nRaises\n------\nValueError\n If ``cutoff`` is not positive.\n\nPassing the engine into :class:`VerletSkin` **moves** it: the list is\nconsumed, and every later method call on it raises ``ValueError`` — build a\nnew ``NeighborList`` instead.\n\nExamples\n--------\n>>> nl = molrs.NeighborList(3.0) # O(N) cell-list backend\n>>> nl.build(points, box) # index only — no pair table\n>>> neigh = nl.neighbors() # both columns (the default)\n>>> lean = nl.neighbors(disp=False) # indices + d² only\n>>> nl.update(moved_points) # re-index in the same box' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

cutoff property

The cutoff distance (Å) fixed at construction.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

brute_force(cutoff) staticmethod

Build an engine with the O(N²) all-pairs backend.

Same pairs as the cell list — that is what makes it useful as an oracle — at a cost that grows with the square of the particle count.

Returns:

Type Description
NeighborList

Raises:

Type Description
ValueError

If cutoff is not positive.

build(points, box) method descriptor

Index points in box — coordinates and box.

Builds the spatial index and nothing else: no pairs are enumerated and no table is allocated. box is retained, so a later :meth:update can re-index new coordinates in the same box; a run whose box changes every step (a barostat) must call build again rather than update.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float64

Cartesian coordinates in Å.

required
box Box

Simulation box supplying the periodicity used for minimum images.

required

Raises:

Type Description
ValueError

If points does not have shape (N, 3).

neighbors(dist_sq=True, disp=True) method descriptor

Materialize the pairs into a :class:Neighbors table.

Both physical columns are kept by default, so no downstream analysis is surprised by a missing one; pass False for a column this call site will not read. A dropped column cannot be added afterwards — rerun the search instead.

Row order is unspecified: the cell-list backend materializes in parallel, and the work split decides the order.

Parameters:

Name Type Description Default
dist_sq bool

Keep the squared minimum-image distance column (Ų), 8 B/pair.

True
disp bool

Keep the minimum-image displacement column (Å), 24 B/pair.

True

Returns:

Type Description
Neighbors

update(points) method descriptor

Re-index new coordinates in the box captured by the last :meth:build.

The natural per-step call at fixed volume: the positions move, the box does not. Index-only, like build. There is no skin — this re-indexes every time rather than deciding for you that the previous index was still good enough.

Parameters:

Name Type Description Default
points numpy.ndarray, shape (N, 3), dtype float64

New Cartesian coordinates in Å.

required

Raises:

Type Description
ValueError

If points does not have shape (N, 3), or if no build has run yet — the box is then unknown, and guessing one would fold minimum images against a box the caller never named.

Neighbors

Materialized neighbor pair table, exposed to Python as molrs.Neighbors.

A column store of every pair within the cutoff: two index columns that are always present, plus whichever physical columns the search was told to keep. Row k of every column describes the same pair.

A self search is half-shell — each unordered pair appears once, with i < j. A cross-query (:class:NeighborQuery) is directed and has no such rule.

Optional columns are methods returning None when the search did not store them; None is deliberately distinct from a column of zeros, which would mean coincident particles.

Methods:

Name Description
query_point_indices

Query-point index i per pair.

point_indices

Reference-point index j per pair.

dist_sq

Squared minimum-image distance in Ų. Take np.sqrt at the call site for a distance — nothing here hides a per-pair square root.

disp

Minimum-image displacement r_j - r_i in Å, unnormalized.

Attributes:

Name Type Description
n_pairs int

Number of pairs — the row count every column shares.

num_points int

Number of reference points.

num_query_points int

Number of query points (equal to num_points for a self search).

is_self_query bool

True when both index columns address the same point set.

Examples:

>>> neigh = nl.neighbors()
>>> i, j = neigh.query_point_indices(), neigh.point_indices()
>>> distances = np.sqrt(neigh.dist_sq())
>>> directions = neigh.disp() / distances[:, None]

__doc__ = 'Materialized neighbor pair table, exposed to Python as `molrs.Neighbors`.\n\nA column store of every pair within the cutoff: two index columns that are\nalways present, plus whichever physical columns the search was told to keep.\nRow ``k`` of every column describes the same pair.\n\nA self search is half-shell — each unordered pair appears once, with\n``i < j``. A cross-query (:class:`NeighborQuery`) is directed and has no\nsuch rule.\n\nOptional columns are methods returning ``None`` when the search did not\nstore them; ``None`` is deliberately distinct from a column of zeros, which\nwould mean coincident particles.\n\nMethods\n-------\nquery_point_indices() : numpy.ndarray[uint32], shape (n_pairs,)\n Query-point index ``i`` per pair.\npoint_indices() : numpy.ndarray[uint32], shape (n_pairs,)\n Reference-point index ``j`` per pair.\ndist_sq() : numpy.ndarray[float64], shape (n_pairs,), or None\n Squared minimum-image distance in Ų. Take ``np.sqrt`` at the call site\n for a distance — nothing here hides a per-pair square root.\ndisp() : numpy.ndarray[float64], shape (n_pairs, 3), or None\n Minimum-image displacement ``r_j - r_i`` in Å, **unnormalized**.\n\nAttributes\n----------\nn_pairs : int\n Number of pairs — the row count every column shares.\nnum_points : int\n Number of reference points.\nnum_query_points : int\n Number of query points (equal to ``num_points`` for a self search).\nis_self_query : bool\n ``True`` when both index columns address the same point set.\n\nExamples\n--------\n>>> neigh = nl.neighbors()\n>>> i, j = neigh.query_point_indices(), neigh.point_indices()\n>>> distances = np.sqrt(neigh.dist_sq())\n>>> directions = neigh.disp() / distances[:, None]' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

is_self_query property

Whether both index columns address the same point set (half-shell).

n_pairs property

Number of neighbor pairs — the row count every column shares.

num_points property

Number of reference points the search indexed.

num_query_points property

Number of query points; equal to num_points for a self search.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

disp() method descriptor

Minimum-image displacements r_j - r_i (Å) as an (n_pairs, 3) array.

Row k points from i to j and is not normalized — its length is the pair distance. Zero-copy view, or None when this table never stored the column (which is not the same as a zero vector: that would mean two coincident particles).

Returns:

Type Description
numpy.ndarray, shape (n_pairs, 3), dtype float64, or None

dist_sq() method descriptor

Squared minimum-image distances (Ų), one per pair.

Zero-copy view, or None when this table never stored the column. The square root is left to the caller: most consumers compare against a squared cutoff, and an accessor that hid a per-pair sqrt would make that cost invisible.

Returns:

Type Description
numpy.ndarray, shape (n_pairs,), dtype float64, or None

point_indices() method descriptor

Reference-point indices j, one per pair.

Zero-copy view; see query_point_indices.

Returns:

Type Description
numpy.ndarray, shape (n_pairs,), dtype uint32

query_point_indices() method descriptor

Query-point indices i, one per pair.

Zero-copy numpy view into the underlying Rust Vec<u32>, pinned alive through numpy's .base mechanism: the returned array keeps this table alive for as long as Python references it.

Returns:

Type Description
numpy.ndarray, shape (n_pairs,), dtype uint32

NeighborQuery

Cross-query neighbor search, exposed to Python as molrs.NeighborQuery.

Build a spatial index from reference points once, then answer repeated queries against it. This is the door for the cross question — "which reference points lie within the cutoff of these other points?" — and is the reason the class exists. A search of one point set against itself belongs to :class:NeighborList, which can additionally re-index moved coordinates and choose which columns a table keeps.

Every table returned here carries both physical columns.

Parameters:

Name Type Description Default
box Box

Simulation box describing geometry and periodic boundaries.

required
points numpy.ndarray, shape (N, 3), dtype float64

Reference point positions in Å.

required
cutoff float

Cutoff radius in Å.

required

Examples:

>>> nq = molrs.NeighborQuery(box, positions, cutoff=3.0)
>>> cross = nq.query(query_positions)   # directed, no ``i < j`` rule
>>> half = nq.query_self()              # half-shell over the reference set

__doc__ = 'Cross-query neighbor search, exposed to Python as `molrs.NeighborQuery`.\n\nBuild a spatial index from reference points once, then answer repeated\nqueries against it. This is the door for the *cross* question — "which\nreference points lie within the cutoff of **these other** points?" — and is\nthe reason the class exists. A search of one point set against itself\nbelongs to :class:`NeighborList`, which can additionally re-index moved\ncoordinates and choose which columns a table keeps.\n\nEvery table returned here carries both physical columns.\n\nParameters\n----------\nbox : Box\n Simulation box describing geometry and periodic boundaries.\npoints : numpy.ndarray, shape (N, 3), dtype float64\n Reference point positions in Å.\ncutoff : float\n Cutoff radius in Å.\n\nExamples\n--------\n>>> nq = molrs.NeighborQuery(box, positions, cutoff=3.0)\n>>> cross = nq.query(query_positions) # directed, no ``i < j`` rule\n>>> half = nq.query_self() # half-shell over the reference set' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

free(points, cutoff) staticmethod

Build a free-boundary spatial index from reference points.

The non-periodic bounding box is derived from the point cloud, so the caller does not need to manufacture a simulation box for selections or other isolated-coordinate queries.

Raises:

Type Description
ValueError

If points does not have shape (N, 3) or cutoff is not positive.

query(query_points) method descriptor

Find all pairs where i indexes query_points and j indexes the reference points.

Directed: every query point reports all of its reference neighbors, with no i < j constraint. Passing the reference coordinates back in means each point finds itself at distance zero and each pair appears twice — use :meth:query_self when each unordered pair should appear once.

Returns:

Type Description
Neighbors

Raises:

Type Description
ValueError

If query_points does not have shape (M, 3).

query_self() method descriptor

Find each unordered pair within the reference point set once (i < j).

Returns:

Type Description
Neighbors

3D Conformer Generation

Conformer

3D conformer generator for molecular graphs.

Exposed to Python as molrs.conformer.Conformer. Construct it with the desired generation parameters, then call :meth:generate to produce coordinates. The class is subclassable so downstream wrappers (e.g. molpy.conformer) can inherit it and refine the marshalling.

Parameters:

Name Type Description Default
speed str

Quality preset: "fast" (fewest iterations), "medium" (default), or "better" (most thorough search).

required
add_hydrogens bool

If True (default), add implicit hydrogens before generation.

required
seed int | None

Random seed for reproducibility. None uses an arbitrary seed.

required

Examples:

>>> gen = Conformer(speed="fast", add_hydrogens=True, seed=42)
>>> mol_3d, report = gen.generate(mol)

__doc__ = '3D conformer generator for molecular graphs.\n\nExposed to Python as `molrs.conformer.Conformer`. Construct it with the desired\ngeneration parameters, then call :meth:`generate` to produce coordinates.\nThe class is subclassable so downstream wrappers (e.g. ``molpy.conformer``)\ncan inherit it and refine the marshalling.\n\nParameters\n----------\nspeed : str, optional\n Quality preset: ``"fast"`` (fewest iterations), ``"medium"`` (default),\n or ``"better"`` (most thorough search).\nadd_hydrogens : bool, optional\n If ``True`` (default), add implicit hydrogens before generation.\nseed : int | None, optional\n Random seed for reproducibility. ``None`` uses an arbitrary seed.\n\nExamples\n--------\n>>> gen = Conformer(speed="fast", add_hydrogens=True, seed=42)\n>>> mol_3d, report = gen.generate(mol)' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.conformer' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

generate(mol) method descriptor

Generate 3D coordinates for a molecular graph.

Runs the full distance-geometry + optimization pipeline. The input molecule is not modified; the result is an :class:~molrs.Atomistic that keeps the input's ports and its frag_id labels.

Parameters:

Name Type Description Default
mol Atomistic

Input molecular graph (heavy atoms and bonds); its ports are carried across unchanged.

required

Returns:

Type Description
tuple[Atomistic, ConformerReport]

The molecule with generated 3D coordinates — positions in ångström (Å) — and a per-stage report.

Raises:

Type Description
TypeError

If mol is not an Atomistic.

ValueError

If the molecular graph is invalid (e.g. missing element symbols).

Examples:

>>> mol = molrs.io.SmilesIR("CCO").to_atomistic()
>>> mol_3d, report = Conformer(speed="fast", seed=42).generate(mol)
>>> mol_3d.n_atoms   # includes added hydrogens
9

Hydrogens this pipeline adds to a ported unit carry no frag_id; the caller relabels them, which is one call:

>>> unit = molrs.io.SmilesIR.from_fragment("[$]CO").to_template()
>>> unit_3d, _ = Conformer(speed="fast", seed=42).generate(unit)
>>> _ = unit_3d.inherit_frag_ids()

ConformerStageReport

Report for a single stage of conformer generation.

Exposed to Python as molrs.conformer.ConformerStageReport.

Attributes:

Name Type Description
stage str

Stage name (e.g. "build_initial", "final_optimize").

energy_before float | None

Energy in kcal/mol before this stage, or None if not applicable.

energy_after float | None

Energy in kcal/mol after this stage, or None if not applicable.

steps int

Number of optimizer steps executed.

converged bool

Whether the stage converged.

elapsed_ms int

Wall-clock time for this stage in milliseconds.

__doc__ = 'Report for a single stage of conformer generation.\n\nExposed to Python as `molrs.conformer.ConformerStageReport`.\n\nAttributes\n----------\nstage : str\n Stage name (e.g. ``"build_initial"``, ``"final_optimize"``).\nenergy_before : float | None\n Energy in kcal/mol before this stage, or ``None`` if not applicable.\nenergy_after : float | None\n Energy in kcal/mol after this stage, or ``None`` if not applicable.\nsteps : int\n Number of optimizer steps executed.\nconverged : bool\n Whether the stage converged.\nelapsed_ms : int\n Wall-clock time for this stage in milliseconds.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.conformer' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

converged property

elapsed_ms property

energy_after property

energy_before property

stage property

steps property

__repr__() method descriptor

Return repr(self).

ConformerReport

Aggregate report for a conformer generation run.

Exposed to Python as molrs.conformer.ConformerReport.

Attributes:

Name Type Description
final_energy float | None

Total energy in kcal/mol after all stages, or None on failure.

warnings list[str]

Diagnostic warnings generated during the run.

stages list[ConformerStageReport]

Per-stage execution reports.

Examples:

>>> mol_3d, report = Conformer().generate(mol)
>>> report.final_energy
-12.34
>>> for s in report.stages:
...     print(s.stage, s.converged)

__doc__ = 'Aggregate report for a conformer generation run.\n\nExposed to Python as `molrs.conformer.ConformerReport`.\n\nAttributes\n----------\nfinal_energy : float | None\n Total energy in kcal/mol after all stages, or ``None`` on failure.\nwarnings : list[str]\n Diagnostic warnings generated during the run.\nstages : list[ConformerStageReport]\n Per-stage execution reports.\n\nExamples\n--------\n>>> mol_3d, report = Conformer().generate(mol)\n>>> report.final_energy\n-12.34\n>>> for s in report.stages:\n... print(s.stage, s.converged)' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.conformer' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

final_energy property

stages property

Per-stage execution reports.

Returns:

Type Description
list[ConformerStageReport]

warnings property

__repr__() method descriptor

Return repr(self).

Force Fields

The native force-field model exposes a Style/Type handle hierarchy (BondStyle/BondType, PairStyle/PairType, …); a handle's params is a plain dict.

ForceField

Force-field definition metadata exposed to Python as molrs.ff.ForceField.

Subclassable, like every core data class (molnex's ForceField extends it). Styles and types are read and written through their handles (:mod:handles).

__doc__ = "Force-field definition metadata exposed to Python as `molrs.ff.ForceField`.\n\nSubclassable, like every core data class (molnex's `ForceField` extends it).\nStyles and types\nare read and written through their handles (:mod:`handles`)." class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs._lib' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

name property

special_bonds property

The special-bond triples (lj, coul), each [1-2, 1-3, 1-4] — what :meth:set_special_bonds declared, or the default [0, 0, 1].

styles property

Every style, in definition order.

units property

The unit system the parameters are expressed in (a LAMMPS units name); "real" when none is declared.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

def_style(category, name, params=None) method descriptor

Define the category style name with style-level params (numbers and strings, e.g. {"cutoff": 10.0, "mixing": "geometric"}) and return its handle (AtomStyle … PairStyle), whose typed def_type defines types. Re-defining it with equal params keeps the existing style.

Raises:

Type Description
ValueError

On different params for an existing style, or an unknown category.

from_section(section) staticmethod

The force field a forcefield section describes. Its units become the force field's declared units; nothing is converted.

Raises:

Type Description
ValueError

When the section is invalid, or molrs cannot hold it: a category outside atom/bond/angle/dihedral/improper/pair, units that are no preset, a smirks-keyed style.

get_style(category, name) method descriptor

The category style name, or None.

get_styles(category) method descriptor

The styles of a category — a name ("bond") or a style class (BondStyle; Style selects every category).

get_types(category) method descriptor

The types of a category — a name ("bond") or a type class (BondType; Type selects every category) — style by style.

merge(other) method descriptor

Merge other into this force field, in place, and return self.

The union of both definitions: other's styles and types are defined through the same primitives, so an identical re-definition is a no-op and a different one raises ValueError. Declared units and special_bonds are adopted when this force field declares none; two declared values that differ raise ValueError. On error nothing changes.

set_special_bonds(lj, coul) method descriptor

Declare both LJ and Coulomb special-bond triples (1-2, 1-3, 1-4).

Length-3 sequences required; a wrong length raises ValueError. Entries [0]/[1] are stored but not applied (1-2/1-3 exclusion is by omitting pairs from the neighbour list).

to_section() method descriptor

This force field as a record's forcefield section.

The units are the declared (or default real) preset, stated beside its quantities; each style's types become its table's rows.

Raises:

Type Description
ValueError

When the force field has no section form (units that are no preset, a param that is a number in one type and a string in another, …).

Style

Handle of one style of a :class:ForceField.

Made by ForceField.def_style / get_style / styles; its category's subclass (BondStyle, …) carries the typed def_type. Two handles are equal when they name the same category and style of the same force field.

__doc__ = "Handle of one style of a :class:`ForceField`.\n\nMade by ``ForceField.def_style`` / ``get_style`` / ``styles``; its\ncategory's subclass (``BondStyle``, …) carries the typed ``def_type``.\nTwo handles are equal when they name the same category and style of the\nsame force field." class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

category property

The category ("atom", "bond", …, "pair").

name property

The style name ("harmonic", "lj/cut", …).

params property

The style-level params (e.g. a pair style's cutoff, mixing), as a new dict.

types property

Every type of this style, in definition order.

__delitem__(key) method descriptor

Delete self[key].

__eq__(value) method descriptor

Return self==value.

__ge__(value) method descriptor

Return self>=value.

__getitem__(key) method descriptor

Return self[key].

__gt__(value) method descriptor

Return self>value.

__hash__() method descriptor

Return hash(self).

__le__(value) method descriptor

Return self<=value.

__lt__(value) method descriptor

Return self<value.

__ne__(value) method descriptor

Return self!=value.

__repr__() method descriptor

Return repr(self).

__setitem__(key, value) method descriptor

Set self[key] to value.

get_type_by_name(name) method descriptor

The type named name, or None.

get_types(type_cls=None) method descriptor

The types of this style that are instances of type_cls (every type when it is None).

AtomStyle

Bases: molrs.ff.Style

The atom style: def_type(name, **params).

__doc__ = 'The atom style: ``def_type(name, **params)``.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

def_type(name, **params) method descriptor

Define the atom type name with params (numbers and strings, e.g. mass=12.011, element="C") and return its handle — the endpoint the bonded and pair styles take.

Raises:

Type Description
ValueError

On a conflicting re-definition.

BondStyle

Bases: molrs.ff.Style

The bond style: def_type(name, itom, jtom, **params).

__doc__ = 'The bond style: ``def_type(name, itom, jtom, **params)``.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

def_type(name, itom, jtom, **params) method descriptor

Define the bond type name between the atom types itom and jtom with params and return its handle. The name is stored as given and never read for endpoints.

Raises:

Type Description
TypeError

If an endpoint is not an AtomType.

ValueError

On a conflicting re-definition.

AngleStyle

Bases: molrs.ff.Style

The angle style: def_type(name, itom, jtom, ktom, **params).

__doc__ = 'The angle style: ``def_type(name, itom, jtom, ktom, **params)``.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

def_type(name, itom, jtom, ktom, **params) method descriptor

Define the angle type name on itom–jtom–ktom (jtom the vertex) with params and return its handle.

Raises:

Type Description
TypeError

If an endpoint is not an AtomType.

ValueError

On a conflicting re-definition.

DihedralStyle

Bases: molrs.ff.Style

The dihedral style: def_type(name, itom, jtom, ktom, ltom, **params).

__doc__ = 'The dihedral style: ``def_type(name, itom, jtom, ktom, ltom, **params)``.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

def_type(name, itom, jtom, ktom, ltom, **params) method descriptor

Define the dihedral type name on itom–jtom–ktom–ltom with params and return its handle.

Raises:

Type Description
TypeError

If an endpoint is not an AtomType.

ValueError

On a conflicting re-definition.

ImproperStyle

Bases: molrs.ff.Style

The improper style: def_type(name, itom, jtom, ktom, ltom, **params).

__doc__ = 'The improper style: ``def_type(name, itom, jtom, ktom, ltom, **params)``.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

def_type(name, itom, jtom, ktom, ltom, **params) method descriptor

Define the improper type name on itom, jtom, ktom, ltom in the style's slot order with params and return its handle.

Raises:

Type Description
TypeError

If an endpoint is not an AtomType.

ValueError

On a conflicting re-definition.

PairStyle

Bases: molrs.ff.Style

The pair style: def_type(name, itom, jtom=None, **params).

__doc__ = 'The pair style: ``def_type(name, itom, jtom=None, **params)``.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

def_type(name, itom, jtom=None, **params) method descriptor

Define the pair type name between itom and jtom with params and return its handle; jtom=None is the self pair of itom.

A pair is its two atom types in either order, so a style holds one row per pair: restating a stored pair under any name with equal parameters (annotations such as desc aside) stores nothing and returns the stored row's handle.

Raises:

Type Description
TypeError

If an endpoint is not an AtomType.

ValueError

On a conflicting re-definition, or a restatement of a stored pair with different parameters.

Type

Handle of one type of a :class:ForceField.

Its params read as a mapping (t["k"], "k" in t, t.keys()) and write one at a time (t["k"] = 300.0, t["element"] = "C"). endpoints are the AtomType handles it is defined on. Two handles are equal when they name the same category, style and type of the same force field.

__doc__ = 'Handle of one type of a :class:`ForceField`.\n\nIts params read as a mapping (``t["k"]``, ``"k" in t``, ``t.keys()``) and\nwrite one at a time (``t["k"] = 300.0``, ``t["element"] = "C"``).\n``endpoints`` are the ``AtomType`` handles it is defined on. Two handles\nare equal when they name the same category, style and type of the same\nforce field.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

category property

The category ("atom", "bond", …, "pair").

endpoints property

The AtomType handles this type is defined on (none for an atom type; two for a pair type, a self pair naming one atom type twice).

name property

The type name — the label a Frame's type column carries.

params property

The type's params (numbers and strings), as a new dict.

__contains__(key) method descriptor

Return bool(key in self).

__delitem__(key) method descriptor

Delete self[key].

__eq__(value) method descriptor

Return self==value.

__ge__(value) method descriptor

Return self>=value.

__getitem__(key) method descriptor

Return self[key].

__gt__(value) method descriptor

Return self>value.

__hash__() method descriptor

Return hash(self).

__le__(value) method descriptor

Return self<=value.

__lt__(value) method descriptor

Return self<value.

__ne__(value) method descriptor

Return self!=value.

__repr__() method descriptor

Return repr(self).

__setitem__(key, value) method descriptor

Set self[key] to value.

get(key, default=None) method descriptor

One param, or default.

items() method descriptor

(name, value) param pairs.

keys() method descriptor

The param names.

AtomType

Bases: molrs.ff.Type

An atom type; the endpoint every other type is defined on.

__doc__ = 'An atom type; the endpoint every other type is defined on.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

BondType

Bases: molrs.ff.Type

A bond type.

__doc__ = 'A bond type.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

itom property

The first endpoint atom type.

jtom property

The second endpoint atom type.

AngleType

Bases: molrs.ff.Type

An angle type (jtom the vertex).

__doc__ = 'An angle type (``jtom`` the vertex).' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

itom property

The first endpoint atom type.

jtom property

The second endpoint atom type.

ktom property

The third endpoint atom type.

DihedralType

Bases: molrs.ff.Type

A dihedral type.

__doc__ = 'A dihedral type.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

itom property

The first endpoint atom type.

jtom property

The second endpoint atom type.

ktom property

The third endpoint atom type.

ltom property

The fourth endpoint atom type.

ImproperType

Bases: molrs.ff.Type

An improper type.

__doc__ = 'An improper type.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

itom property

The first endpoint atom type.

jtom property

The second endpoint atom type.

ktom property

The third endpoint atom type.

ltom property

The fourth endpoint atom type.

PairType

Bases: molrs.ff.Type

A pair type.

__doc__ = 'A pair type.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

itom property

The first endpoint atom type.

jtom property

The second endpoint atom type.

MMFF94Typifier

Bases: molrs.ff.typifier.Typifier

MMFF94 atom-type assigner.

Exposed to Python as molrs.ff.MMFF94Typifier.

Loads the embedded MMFF94 parameter tables at construction time. Use :meth:typify to label a molecular graph (atom types, partial charges, and the per-instance force constants the kernels read: koop (mdArad^-2) on the improper rows, v1/v2/v3 on the dihedral rows), then compile it through :meth:forcefield — the definitions typing assigned — the standard route, shared with every other force field in molrs. :meth:typify raises ValueError when atom types cannot be determined (e.g. unsupported elements).

See :class:MMFF94STypifier for the "static" variant used in energy minimization.

References

  • Halgren, T.A. (1996). J. Comput. Chem. 17, 490-519.

Examples:

>>> typifier = MMFF94Typifier()
>>> frame = typifier.typify(mol).to_frame()          # labels + charges
>>> frame["pairs"] = molrs.intramolecular_pairs(frame)
>>> pots = molrs.ff.PotentialCompiler(typifier.forcefield()).compile(frame)

__doc__ = 'MMFF94 atom-type assigner.\n\nExposed to Python as `molrs.ff.MMFF94Typifier`.\n\nLoads the embedded MMFF94 parameter tables at construction time. Use\n:meth:`typify` to label a molecular graph (atom types, partial charges, and\nthe per-instance force constants the kernels read: ``koop`` (md*A*rad^-2)\non the improper rows, ``v1``/``v2``/``v3`` on the dihedral rows), then\ncompile it through :meth:`forcefield` — the definitions typing assigned —\nthe standard route, shared with every other force field in molrs.\n:meth:`typify` raises ``ValueError`` when atom types cannot be determined\n(e.g. unsupported elements).\n\nSee :class:`MMFF94STypifier` for the "static" variant used in energy\nminimization.\n\n# References\n\n- Halgren, T.A. (1996). J. Comput. Chem. 17, 490-519.\n\nExamples\n--------\n>>> typifier = MMFF94Typifier()\n>>> frame = typifier.typify(mol).to_frame() # labels + charges\n>>> frame["pairs"] = molrs.intramolecular_pairs(frame)\n>>> pots = molrs.ff.PotentialCompiler(typifier.forcefield()).compile(frame)' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff.typifier' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

MMFF94STypifier

Bases: molrs.ff.typifier.Typifier

MMFF94s ("static") atom-type assigner and potential builder.

Exposed to Python as molrs.ff.MMFF94STypifier.

Identical to :class:MMFF94Typifier except on delocalised trivalent nitrogen (MMFF numeric types 10 NC=O and 40 NC=C), where MMFF94s re-parameterises 11 out-of-plane rows and 42 torsion rows so the nitrogen minimizes to a planar geometry — the one seen in crystal structures.

The mechanism is the out-of-plane force constant koop (mdArad^-2) that :meth:typify bakes onto the improper rows. The kernel evaluates E_oop = 0.5 * 143.9325 * koop * chi**2 with chi the Wilson out-of-plane angle in radians, so koop > 0 makes the planar centre an energy minimum. MMFF94s sets it to +0.015 (type 10) / +0.030 (type 40); MMFF94's values on those rows run from -0.033 to +0.004.

All 95 atom types, and every bond / angle / stretch-bend / vdW / charge parameter, are shared with MMFF94 — so a molecule with no such nitrogen gets bit-for-bit the same answer from both classes.

References

  • Halgren, T.A. (1999). J. Comput. Chem. 20, 720-729. (MMFF94s)

Examples:

>>> typifier = MMFF94STypifier()
>>> typifier.forcefield().name
'MMFF94s'

__doc__ = 'MMFF94s ("static") atom-type assigner and potential builder.\n\nExposed to Python as `molrs.ff.MMFF94STypifier`.\n\nIdentical to :class:`MMFF94Typifier` except on delocalised trivalent\nnitrogen (MMFF numeric types 10 ``NC=O`` and 40 ``NC=C``), where MMFF94s\nre-parameterises 11 out-of-plane rows and 42 torsion rows so the nitrogen\nminimizes to a **planar** geometry — the one seen in crystal structures.\n\nThe mechanism is the out-of-plane force constant ``koop`` (md*A*rad^-2) that\n:meth:`typify` bakes onto the improper rows. The kernel evaluates\n``E_oop = 0.5 * 143.9325 * koop * chi**2`` with ``chi`` the Wilson\nout-of-plane angle in radians, so ``koop > 0`` makes the planar centre an\nenergy minimum. MMFF94s sets it to ``+0.015`` (type 10) / ``+0.030``\n(type 40); MMFF94\'s values on those rows run from ``-0.033`` to ``+0.004``.\n\nAll 95 atom types, and every bond / angle / stretch-bend / vdW / charge\nparameter, are shared with MMFF94 — so a molecule with no such nitrogen gets\nbit-for-bit the same answer from both classes.\n\n# References\n\n- Halgren, T.A. (1999). J. Comput. Chem. 20, 720-729. (MMFF94s)\n\nExamples\n--------\n>>> typifier = MMFF94STypifier()\n>>> typifier.forcefield().name\n\'MMFF94s\'' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff.typifier' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

OPLSAATypifier

Bases: molrs.ff.typifier.Typifier

OPLS-AA atom-type assigner and potential builder.

Exposed to Python as molrs.ff.OPLSAATypifier. It loads the embedded canonical OPLS-AA parameter set by default, or reads one XML source at construction. :meth:typify returns a typed :class:Atomistic (ValueError when atom typing fails); :meth:forcefield holds the definitions it assigned.

Parameters:

Name Type Description Default
source str or path - like

OPLS-AA XML text or a path to an XML file. None uses the embedded canonical OPLS-AA table.

required
strict bool

When True, a bonded term with no force-field match is an error. When False, such terms are skipped (left unparametrized).

True

Examples:

>>> typifier = OPLSAATypifier()
>>> typed = typifier.typify(mol)        # typed Atomistic
>>> # compose: typify → to_frame → intramolecular_pairs → PotentialCompiler(forcefield()).compile

__doc__ = 'OPLS-AA atom-type assigner and potential builder.\n\nExposed to Python as `molrs.ff.OPLSAATypifier`. It loads the embedded canonical\nOPLS-AA parameter set by default, or reads one XML source at construction.\n:meth:`typify` returns a typed :class:`Atomistic` (``ValueError`` when atom\ntyping fails); :meth:`forcefield` holds the definitions it assigned.\n\nParameters\n----------\nsource : str or path-like, optional\n OPLS-AA XML text or a path to an XML file. ``None`` uses the embedded\n canonical OPLS-AA table.\nstrict : bool, default True\n When True, a bonded term with no force-field match is an error. When\n False, such terms are skipped (left unparametrized).\n\nExamples\n--------\n>>> typifier = OPLSAATypifier()\n>>> typed = typifier.typify(mol) # typed Atomistic\n>>> # compose: typify → to_frame → intramolecular_pairs → PotentialCompiler(forcefield()).compile' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff.typifier' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

Typifier

The base of every graph typifier: one match hook plus the output force field its typing accumulates.

Exposed to Python as molrs.ff.typifier.Typifier and subclassable. A subclass implements :meth:match (and optionally :meth:library) and nothing else; :meth:typify is the one execution path and the only writer of :meth:forcefield. Defining typify on a subclass raises TypeError at class creation.

The native typifier classes (MMFF94Typifier, MMFF94STypifier, OPLSAATypifier, AtdTypifier) extend this base and only construct: their match runs the Rust matcher and their typify the Rust Typing::typify.

__doc__ = 'The base of every graph typifier: one ``match`` hook plus the output force\nfield its typing accumulates.\n\nExposed to Python as ``molrs.ff.typifier.Typifier`` and subclassable. A\nsubclass implements :meth:`match` (and optionally :meth:`library`) and\nnothing else; :meth:`typify` is the one execution path and the only writer\nof :meth:`forcefield`. Defining ``typify`` on a subclass raises\n``TypeError`` at class creation.\n\nThe native typifier classes (``MMFF94Typifier``, ``MMFF94STypifier``,\n``OPLSAATypifier``, ``AtdTypifier``) extend this base and only construct:\ntheir ``match`` runs the Rust matcher and their ``typify`` the Rust\n``Typing::typify``.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff.typifier' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__init_subclass__(**kwargs) builtin

Reject a subclass that defines typify in its own body, and a subclass of a native typifier that defines match or library.

typify is the only writer of :meth:forcefield; an override would silently bypass the output. A native typifier (OPLSAATypifier, MMFF94Typifier, …) types in Rust and never calls a Python match or library, so overriding either on its subclass would be silently ignored. typing.final is only a static check.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

forcefield() method descriptor

The accumulated output — exactly the definitions :meth:typify has assigned — as an independent copy.

Edits to the returned force field do not reach the typifier; :meth:typify is the only writer. Before the first typify this is the seeded empty output (see :meth:library).

library() method descriptor

The force field this typifier matches against, as an independent copy.

The output starts as its empty likeness: the library's name and declared units and special_bonds, no styles or types. A Python subclass may override it; one that does not has no library (this raises NotImplementedError), and its output starts as an empty force field named after the class, with nothing declared.

match(graph) method descriptor

Match graph and return what it assigns, as a :class:Match.

The one hook a subclass implements. match may write intermediate results (generated topology, perceived bond types) onto the graph it is given; :meth:typify always gives it a private copy. On a native typifier this runs the Rust matcher on graph.

Raises:

Type Description
NotImplementedError

On the base, when a subclass does not implement match.

ValueError

If a native matcher cannot match the graph.

typify(mol) method descriptor

Type mol: do not override; the only writer of :meth:forcefield.

Copies mol (mol.copy()), calls :meth:match on the copy and writes the returned :class:Match onto the copy and the output force field — stamping every annotation and defining every type. mol is never touched.

Returns:

Type Description
Atomistic

The typed copy.

Raises:

Type Description
NotImplementedError

If the typifier has no match.

TypeError

If match returns something other than a :class:Match.

ValueError

If the match does not fit the graph or contradicts a definition the output already holds. The output is then unchanged.

Match

What a typifier's match assigns to one graph, exposed to Python as molrs.ff.typifier.Match (the Rust Match).

Parameters:

Name Type Description Default
nodes sequence of mapping

One mapping of key -> annotation per node, positional against graph.atoms. An empty mapping gives that node nothing.

required
links mapping

Relation class (Bond, Angle, Dihedral, Improper) to a sequence of mappings, positional against graph.links.exact_bucket(cls) — the kind's own rows, so an improper never shifts a dihedral position. Any other key raises TypeError.

required
styles sequence of (category, style, params)

Styles to declare, in order.

required
pairs sequence of (style, name, endpoints, params)

Pair rows to define.

required
Notes

An annotation is a str, bool, int or float (stamped, defines nothing), or a type: (style, name, endpoints, params), which stamps name and every param and defines the type name on endpoints (atom-type names; empty for an atom type) under the style. The name is never read for endpoints. Param values are numbers or strings.

__doc__ = "What a typifier's ``match`` assigns to one graph, exposed to Python as\n``molrs.ff.typifier.Match`` (the Rust `Match`).\n\nParameters\n----------\nnodes : sequence of mapping\n One mapping of ``key -> annotation`` per node, positional against\n ``graph.atoms``. An empty mapping gives that node nothing.\nlinks : mapping, optional\n Relation class (``Bond``, ``Angle``, ``Dihedral``, ``Improper``) to a\n sequence of mappings, positional against\n ``graph.links.exact_bucket(cls)`` — the kind's own rows, so an improper\n never shifts a dihedral position. Any other key raises ``TypeError``.\nstyles : sequence of (category, style, params), optional\n Styles to declare, in order.\npairs : sequence of (style, name, endpoints, params), optional\n Pair rows to define.\n\nNotes\n-----\nAn annotation is a ``str``, ``bool``, ``int`` or ``float`` (stamped, defines\nnothing), or a type: ``(style, name, endpoints, params)``, which stamps\n``name`` and every param and defines the type ``name`` on ``endpoints``\n(atom-type names; empty for an atom type) under the style. The name is\nnever read for endpoints. Param values are numbers or strings." class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff.typifier' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

PotentialCompiler

Compiles a :class:ForceField into evaluable kernels.

Exposed to Python as molrs.ff.PotentialCompiler. It owns a copy of the force field, taken at construction: later edits to that :class:ForceField do not reach a compiler that already exists — make a new one.

Three doors, each doing one thing:

  • :meth:compile — bind a typed :class:Frame now;
  • :meth:defer — a :class:Potentials that binds the topology of the :class:Frame it is evaluated on;
  • :meth:compile_typed — the kernels of a neighbour-driven evaluation, for MD.

Examples:

>>> compiler = molrs.ff.PotentialCompiler(typifier.forcefield())
>>> potentials = compiler.compile(frame)
>>> energy = potentials.calc_energy(frame)

__doc__ = 'Compiles a :class:`ForceField` into evaluable kernels.\n\nExposed to Python as ``molrs.ff.PotentialCompiler``. It owns a **copy** of\nthe force field, taken at construction: later edits to that\n:class:`ForceField` do not reach a compiler that already exists — make a\nnew one.\n\nThree doors, each doing one thing:\n\n* :meth:`compile` — bind a typed :class:`Frame` now;\n* :meth:`defer` — a :class:`Potentials` that binds the topology of the\n :class:`Frame` it is evaluated on;\n* :meth:`compile_typed` — the kernels of a neighbour-driven evaluation,\n for MD.\n\nExamples\n--------\n>>> compiler = molrs.ff.PotentialCompiler(typifier.forcefield())\n>>> potentials = compiler.compile(frame)\n>>> energy = potentials.calc_energy(frame)' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

compile(frame) method descriptor

Build evaluable :class:Potentials against a typed frame.

The frame must carry the topology + type columns each style resolves (atoms/bonds/angles/dihedrals/impropers/ pairs), as produced by a typifier or an external emitter. Every pair style is resolved against the frame's pairs block — a fixed list with no spatial cutoff, right for a molecule in free space.

Parameters:

Name Type Description Default
frame Frame

Typed molecular data. Required; for potentials that bind at evaluation time use :meth:defer.

required

Returns:

Type Description
Potentials

Raises:

Type Description
TypeError

If frame is not a :class:Frame (None included).

ValueError

If a style has no registered kernel, a type label is unknown, or the force field's 1-2 / 1-3 weights are not 0 or 1.

compile_typed(frame) method descriptor

Build the kernels for a neighbour-driven evaluation, with the special-bonds weights each one takes.

The counterpart of :meth:compile, and what periodic MD needs. That one resolves every pair style against the frame's pairs block — a fixed list with no spatial cutoff, right for a free-boundary molecule and wrong for a periodic system. This one resolves them against the atoms, reads no pairs block, and requires the style's declared cutoff.

The weights come from the force field's special_bonds walked over the frame's bond graph. Without them a neighbour table would count a bonded pair twice: once by the bond term and once at full non-bonded strength, at bond length.

Parameters:

Name Type Description Default
frame Frame

Typed molecular data.

required

Returns:

Type Description
TypedPotentials

Raises:

Type Description
ValueError

If a style cannot be built, or a pair style has no neighbour-driven form.

defer() method descriptor

A :class:Potentials that compiles when it is evaluated.

It holds this compiler's force field and binds the topology and coordinates of the :class:Frame passed to calc_energy(frame) / calc_forces(frame) (the molpy evaluation model). It has no members until then, so len is 0, and it cannot be evaluated on a bare coordinate array or moved into an integrator.

Returns:

Type Description
Potentials

Potentials

Compiled force-field potentials for energy and force evaluation.

Exposed to Python as molrs.ff.Potentials.

Operates on flat coordinate arrays in the layout [x0, y0, z0, x1, y1, z1, ...] (length 3N).

Examples:

>>> typifier = MMFF94Typifier()
>>> frame = typifier.typify(mol).to_frame()
>>> frame["pairs"] = molrs.intramolecular_pairs(frame)
>>> potentials = molrs.ff.PotentialCompiler(typifier.forcefield()).compile(frame)
>>> energy, forces = potentials.eval(coords)

__doc__ = 'Compiled force-field potentials for energy and force evaluation.\n\nExposed to Python as `molrs.ff.Potentials`.\n\nOperates on flat coordinate arrays in the layout\n``[x0, y0, z0, x1, y1, z1, ...]`` (length 3N).\n\nExamples\n--------\n>>> typifier = MMFF94Typifier()\n>>> frame = typifier.typify(mol).to_frame()\n>>> frame["pairs"] = molrs.intramolecular_pairs(frame)\n>>> potentials = molrs.ff.PotentialCompiler(typifier.forcefield()).compile(frame)\n>>> energy, forces = potentials.eval(coords)' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.ff' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__len__() method descriptor

Return len(self).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

calc_energy(arg) method descriptor

Evaluate total energy (kcal/mol) against a :class:Frame or coordinates.

calc_energy_forces(arg) method descriptor

Returns (energy, forces), forces shape (N, 3).

calc_forces(arg) method descriptor

Compute forces (= -gradient) in kcal/(mol·Å), shape (N, 3).

push(potential) method descriptor

Move one more member into the collection: an LJCut nonbond term, a callable Potential, or another Potentials.

LBFGS

L-BFGS geometry optimizer, exposed as molrs.LBFGS.

Construct with potentials + knobs on new, then run a :class:Frame (primary) or a coordinate array (single / batch by rank).

Examples:

>>> pots = molrs.ff.PotentialCompiler(molrs.MMFF94Typifier().forcefield()).compile(frame)
>>> opt = molrs.LBFGS(pots, fmax=0.05, max_steps=500)
>>> frame, report = opt.run(frame)
>>> coords, report = opt.run(coords)         # (N, 3)

__doc__ = 'L-BFGS geometry optimizer, exposed as `molrs.LBFGS`.\n\nConstruct with potentials + knobs on ``new``, then ``run`` a :class:`Frame`\n(primary) or a coordinate array (single / batch by rank).\n\nExamples\n--------\n>>> pots = molrs.ff.PotentialCompiler(molrs.MMFF94Typifier().forcefield()).compile(frame)\n>>> opt = molrs.LBFGS(pots, fmax=0.05, max_steps=500)\n>>> frame, report = opt.run(frame)\n>>> coords, report = opt.run(coords) # (N, 3)' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.optimize' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

run(arg) method descriptor

Relax a :class:Frame or coordinates by L-BFGS.

  • Frame → (Frame, OptReport) (frame coordinates updated; a new Python frame object is returned with the minimized coords).
  • (N, 3) / (3N,) → ((N, 3) array, OptReport)
  • (B, N, 3) → ((B, N, 3) array, list[OptReport])

OptReport

Outcome of a geometry optimization, exposed to Python as molrs.OptReport.

__doc__ = 'Outcome of a geometry optimization, exposed to Python as `molrs.OptReport`.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.optimize' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

converged property

Whether fmax convergence was reached within max_steps.

final_energy property

Potential energy at the returned geometry (kcal/mol).

final_fmax property

Maximum per-atom force magnitude at the returned geometry (kcal/mol/angstrom).

n_steps property

Number of outer L-BFGS iterations performed.

__repr__() method descriptor

Return repr(self).

read_forcefield_xml(path) builtin

Read a force-field definition from an XML file.

read_opls_xml(path) builtin

Read an OPLS-AA / GROMACS force-field XML file into a :class:ForceField.

Parses the OpenMM-style OPLS-AA XML (GROMACS units — nm, kJ/mol, Ryckaert-Bellemans torsions) and normalizes it to molrs units (Å, kcal/mol, radians, e): bond/angle/pair conversions plus the RB → OPLS 4-cosine (f1..f4) inversion happen in the reader, so the returned force field is pure molrs units. Distinct from :func:read_forcefield_xml, which reads molrs's own native schema.

Parameters:

Name Type Description Default
path str or PathLike

Path to an oplsaa.xml (OpenMM/GROMACS layout).

required

Returns:

Type Description
ForceField

Raises:

Type Description
ValueError

On a malformed document, an unknown section, or a missing/non-numeric required attribute (reading is total — never a silent skip).

Trajectory

Trajectory

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

frames property

step property

time property

__getitem__(key) method descriptor

Return self[key].

__len__() method descriptor

Return len(self).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

count_frames() method descriptor

Number of frames in the trajectory.

ScalarObservable

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

axes property

data property

description property

domain property

kind property

The contract spelling of the observable's kind.

name property

sampling property

target property

time_dependent property

unit property

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

VectorObservable

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

axes property

data property

description property

domain property

kind property

The contract spelling of the observable's kind.

name property

sampling property

target property

time_dependent property

unit property

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

Analysis

Analysis classes live under the molrs.compute subpackage, organized by domain. The layout mirrors freud and the underlying Rust crate (molrs_compute::{density, order, environment, …}).

molrs.compute.density

RDF

Radial distribution function calculator.

Accepts either a single (frame, nlist) pair or a list of each. Results accumulate across frames and are ideal-gas normalized on return.

__doc__ = 'Radial distribution function calculator.\n\nAccepts either a single `(frame, nlist)` pair or a list of each. Results\naccumulate across frames and are ideal-gas normalized on return.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.density' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

compute(frames, nlists) method descriptor

Compute g® from a batch of frames + neighbor lists.

Parameters:

Name Type Description Default
frames Frame | list[Frame]
required
nlists Neighbors | list[Neighbors]

One neighbor list per frame.

required

Returns:

Type Description
RDFResult

RDFResult

Radial distribution function g® result.

rdf is already normalized (RDF.compute finalizes eagerly).

__doc__ = 'Radial distribution function g(r) result.\n\n`rdf` is already normalized (RDF.compute finalizes eagerly).' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.density' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

bin_centers property

bin_edges property

n_frames property

n_points property

n_r property

r_min property

rdf property

volume property

__repr__() method descriptor

Return repr(self).

GaussianDensity

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.density' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

compute(frames) method descriptor

Returns a list of 3-D density grids (nx, ny, nz), one per frame.

LocalDensity

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.density' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

compute(frames, nlists) method descriptor

Returns (num_neighbors, density) ndarrays per frame.

molrs.compute.order

Steinhardt

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.order' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

Nematic

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.order' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

compute(frames) method descriptor

Per-particle orientation directors are the unit head − tail vectors of the "orientations" topology block, read from the first frame (one (head, tail) atom pair per row). No external director array is passed.

Returns (order: float, eigenvalues: ndarray[3], director: ndarray[3], q_tensor: ndarray[3,3]).

Hexatic

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.order' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

compute(frames, nlists) method descriptor

Returns one numpy array per frame: complex64 per-particle ψ_k (interleaved real/imag pairs in an (N, 2) float64 array).

SolidLiquid

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.order' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

compute(frames, nlists) method descriptor

Returns (n_solid_bonds[i] : u32 ndarray, is_solid[i] : bool list) per frame.

molrs.compute.environment

BondOrder

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.environment' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

compute(frames, nlists) method descriptor

Returns per-frame (raw_counts, bond_order, theta_edges, phi_edges).

molrs.compute.pmft

PMFTXY

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.pmft' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

compute(frames, nlists) method descriptor

Returns per-frame (raw_counts, density, pmf). If the first frame carries an "orientations" topology block (one (head, tail) atom pair per query particle), every bond is rotated into that particle's local frame — the per-particle 2-D angle is atan2 of its head − tail axis, recomputed per frame from that frame's positions. Without the block the analyzer works in the lab frame.

molrs.compute.diffraction

StaticStructureFactorDebye

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.diffraction' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

compute(frames) method descriptor

Returns per-frame (k_values, S(k), n_particles).

molrs.compute.cluster

Cluster

Distance-based cluster analysis.

__doc__ = 'Distance-based cluster analysis.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

compute(frames, nlists=None, keys=None) method descriptor

Compute one cluster result per input frame.

Two modes (mirroring freud's Cluster.compute): * spatial — pass nlists (a Neighbors table per frame); particles within the cutoff and transitively connected form a cluster. * by key — pass keys (one non-negative integer per atom, e.g. a molecule id); all atoms sharing a key form one cluster, independent of geometry. Robust for per-molecule properties (e.g. per-chain Rg) even when molecules overlap or a bond exceeds any spatial cutoff. nlists is then ignored.

Returns a single ClusterResult when a single frame is passed, or a list[ClusterResult] when a list is passed.

ClusterResult

Per-frame cluster assignment.

__doc__ = 'Per-frame cluster assignment.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

cluster_idx property

cluster_keys property

The membership keys present in each cluster (freud's cluster_keys). Empty for spatial clustering; one key per cluster for keys=-based grouping.

cluster_sizes property

num_clusters property

__repr__() method descriptor

Return repr(self).

ClusterCenters

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

ClusterCentersResult

Geometric cluster centers for a single frame.

__doc__ = 'Geometric cluster centers for a single frame.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

centers property

__len__() method descriptor

Return len(self).

__repr__() method descriptor

Return repr(self).

ClusterProperties

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

compute(frames, clusters) method descriptor

Returns a dict per frame with keys sizes, centers, centers_of_mass, cluster_masses, gyration_tensors, radii_of_gyration.

CenterOfMass

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

CenterOfMassResult

Per-frame mass-weighted cluster centers and total cluster masses.

__doc__ = 'Per-frame mass-weighted cluster centers and total cluster masses.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

centers_of_mass property

cluster_masses property

__repr__() method descriptor

Return repr(self).

GyrationTensor

Gyration tensor per cluster.

compute(frames, clusters, centers): - single frame → shape (num_clusters, 3, 3) but wrapped as a list of length 1 when a list of frames is passed. For a single frame you get a (num_clusters, 3, 3) ndarray. - list of frames → ndarray of shape (n_frames, num_clusters, 3, 3) only if all frames have identical cluster counts; otherwise a Python list of per-frame ndarrays.

__doc__ = 'Gyration tensor per cluster.\n\n``compute(frames, clusters, centers)``:\n- single frame → shape `(num_clusters, 3, 3)` **but wrapped as a list of length 1**\n when a list of frames is passed. For a single frame you get a `(num_clusters, 3, 3)` ndarray.\n- list of frames → ndarray of shape `(n_frames, num_clusters, 3, 3)` only if all frames\n have identical cluster counts; otherwise a Python list of per-frame ndarrays.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

InertiaTensor

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

RadiusOfGyration

__doc__ = '' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.cluster' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

compute(frames, clusters, com) method descriptor

Compute Rg per cluster.

Returns a (num_clusters,) ndarray for a single frame, or a (n_frames, num_clusters) ndarray for a batch (clusters per frame must be identical; otherwise a Python list is returned).

molrs.compute.msd

MSD

Mean squared displacement.

Two estimators of the same quantity, chosen by method; they are not interchangeable and there is no default that suits both:

  • "direct" (default) — MSD(t) = ⟨|r(t) − r(0)|²⟩, frame 0 as the one time origin.
  • "window" — MSD(t) = ⟨|r(τ+t) − r(τ)|²⟩ averaged over every time origin τ. Far better statistics at long lag, which is what a diffusion coefficient needs, and O(T log T) via the Wiener–Khinchin identity rather than the O(T²) nested loop. Conventions match freud.msd.

compute(frames) returns an MSDTimeSeries as long as frames either way.

Parameters:

Name Type Description Default
method (direct, window)
"direct"

Examples:

>>> molrs.MSD(method="window").compute(frames).mean

__doc__ = 'Mean squared displacement.\n\nTwo estimators of the same quantity, chosen by ``method``; they are not\ninterchangeable and there is no default that suits both:\n\n- ``"direct"`` (default) — ``MSD(t) = ⟨|r(t) − r(0)|²⟩``, frame 0 as the one\n time origin.\n- ``"window"`` — ``MSD(t) = ⟨|r(τ+t) − r(τ)|²⟩`` averaged over **every** time\n origin τ. Far better statistics at long lag, which is what a diffusion\n coefficient needs, and O(T log T) via the Wiener–Khinchin identity rather\n than the O(T²) nested loop. Conventions match ``freud.msd``.\n\n``compute(frames)`` returns an ``MSDTimeSeries`` as long as ``frames``\neither way.\n\nParameters\n----------\nmethod : {"direct", "window"}, optional\n\nExamples\n--------\n>>> molrs.MSD(method="window").compute(frames).mean' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.msd' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

method property

The estimator this analyzer uses: "direct" or "window".

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

compute(frames) method descriptor

Compute the MSD time series.

MSDResult

Per-frame MSD result (from a single time point).

__doc__ = 'Per-frame MSD result (from a single time point).' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.msd' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

mean property

per_particle property

__repr__() method descriptor

Return repr(self).

MSDTimeSeries

MSD time series aligned with the input frame list.

series.data[0] is the reference frame (mean = 0); series.data[i] compares frame i against frame 0.

__doc__ = 'MSD time series aligned with the input frame list.\n\n`series.data[0]` is the reference frame (mean = 0); `series.data[i]`\ncompares frame `i` against frame `0`.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.msd' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

mean property

per_particle property

__getitem__(key) method descriptor

Return self[key].

__len__() method descriptor

Return len(self).

__repr__() method descriptor

Return repr(self).

molrs.compute.ml

DescriptorRow

Row-based descriptor wrapper for PCA/KMeans input.

Wrap each row (a 1-D float array) with DescriptorRow(row); then pass a Python list of them to Pca2.compute / KMeans.compute.

__doc__ = 'Row-based descriptor wrapper for PCA/KMeans input.\n\nWrap each row (a 1-D float array) with `DescriptorRow(row)`; then pass a\nPython list of them to ``Pca2.compute`` / ``KMeans.compute``.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.ml' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__len__() method descriptor

Return len(self).

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

Pca2

Two-component PCA calculator.

__doc__ = 'Two-component PCA calculator.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.ml' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

compute(rows) method descriptor

Compute PCA over a list of DescriptorRow objects.

PcaResult

Two-component PCA result.

__doc__ = 'Two-component PCA result.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.ml' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

coords property

Row-major (n_rows, 2) projected coordinates.

variance property

[var_pc1, var_pc2] — explained variance per component.

__repr__() method descriptor

Return repr(self).

KMeans

k-means clustering over a PCA projection (2-D).

__doc__ = 'k-means clustering over a PCA projection (2-D).' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.ml' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__new__(*args, **kwargs) builtin

Create and return a new object. See help(type) for accurate signature.

__repr__() method descriptor

Return repr(self).

compute(pca) method descriptor

Cluster a PcaResult.

KMeansResult

k-means cluster labels.

__doc__ = 'k-means cluster labels.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.ml' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

labels property

__len__() method descriptor

Return len(self).

__repr__() method descriptor

Return repr(self).

Transport

Electrolyte transport kernels (ports of the tame recipes). Worked examples, units, and signatures are in the molpy documentation.

molrs.compute.transport

Onsager

Onsager collective mean-displacement cross-correlation.

__doc__ = 'Onsager collective mean-displacement cross-correlation.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.transport' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

Persist

Pair-survival (persistence) time-correlation functions.

__doc__ = 'Pair-survival (persistence) time-correlation functions.' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ = 'molrs.compute.transport' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.