molforge.core¶
core ¶
Core data model: hierarchical and linear views of protein structure.
The :class:AtomArray is the canonical representation — a flat,
NumPy-backed array of all atoms. The hierarchical classes
(:class:Protein, :class:Chain, :class:Residue, :class:Atom) are
lightweight views that read and write through to the array.
Typical usage:
>>> from molforge.core import Protein, AtomArray
>>> protein = Protein(atom_array=AtomArray(0), name="example")
>>> protein.n_atoms
0
RDKitNotInstalledError ¶
Bases: ImportError
Raised when a chemistry operation needs RDKit but it isn't installed.
Atom ¶
View of a single atom in an :class:AtomArray.
Attributes are read/written through to the underlying array, so
mutating an Atom mutates the source-of-truth representation.
AtomArray ¶
Flat, NumPy-backed array of atoms.
This is the canonical representation; hierarchical views read from
these arrays. All per-atom fields have shape (N,) except
coords which has shape (N, 3).
Example
aa = AtomArray.empty(3) aa.element[:] = ["C", "N", "O"] aa.coords[0] = [1.0, 2.0, 3.0] len(aa) 3
Create an empty array of n atoms, all fields at default values.
chain_starts
property
¶
Indices of the first atom of each chain, in order.
A chain boundary is any change in chain_id or model_id.
residue_starts
property
¶
Indices of the first atom of each residue, in order.
A residue boundary is any change in
(chain_id, residue_id, insertion_code, model_id).
empty
classmethod
¶
Alias for AtomArray(n) — more readable at call sites.
from_dict
classmethod
¶
Construct from a dict of equal-length arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, NDArray[Any]]
|
Mapping field-name -> array. Must include |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If array lengths disagree. |
append ¶
Return a new array with other concatenated after this one.
select ¶
Return a new AtomArray containing only atoms where mask is True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
BoolArray
|
Boolean array of length |
required |
where ¶
Build a boolean mask from equality filters on any field.
Example
mask = aa.where(chain_id="A", atom_name="CA") ca_atoms = aa.select(mask)
iter_residue_slices ¶
Yield a slice for each residue's atoms (in array order).
iter_chain_slices ¶
Yield a slice for each chain's atoms (in array order).
Chain ¶
View over a chain's atoms inside an :class:AtomArray.
sequence
property
¶
One-letter sequence for this chain (standard AAs + non-canonical mappings).
Non-amino-acid residues (ligands, water, ions) are skipped.
Unknown residues become "X".
ProteinMetadata ¶
Bases: TypedDict
Typed view of the documented :attr:Protein.metadata keys.
Every key is optional (total=False). This is a typing aid only —
Protein.metadata remains a plain dict[str, Any] at runtime,
and keys outside this set are still permitted (without stability
guarantees). Annotate a local variable as ProteinMetadata to get
editor / mypy support for the documented vocabulary.
Molecule ¶
A small molecule — a ligand, cofactor, or any organic compound.
Where :class:~molforge.core.Protein (and the flat
:class:~molforge.core.AtomArray) captures coordinates and atom names,
a molecule's value is its chemistry: bonds and their orders, formal
charges, aromaticity, and stereochemistry. Those are exactly what the
coordinate-only path drops, so Molecule wraps an RDKit Mol and
lets molforge reason about ligands as chemistry rather than as bond-less
point clouds.
RDKit is a lazy dependency: constructing a molecule that needs it (e.g.
:meth:from_smiles) or reading a chemistry property raises
:class:~molforge.core._rdkit.RDKitNotInstalledError if RDKit is
absent, but importing :mod:molforge.core never pulls it in.
The wrapped Mol is shared, not copied — :meth:to_rdkit hands back
the same object, so RDKit's full API is one call away and mutations are
visible both ways.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
A human-readable label (e.g. an SDF title); may be empty. |
|
metadata |
dict[str, object]
|
Free-form provenance/annotation, e.g. source file or ID. |
Wrap an RDKit Mol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol
|
Any
|
An RDKit |
required |
name
|
str
|
Optional label. |
''
|
metadata
|
Mapping[str, object] | None
|
Optional annotation dict. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
inchikey
property
¶
Standard InChIKey — a stable structural identifier, handy for deduplicating a set of molecules.
lipinski_violations
property
¶
Number of Lipinski rule-of-five violations (0-4).
Counts the classic drug-likeness rules that fail: molecular weight
500, logP > 5, hydrogen-bond donors > 5, hydrogen-bond acceptors 10. A compound with 0-1 violations is considered drug-like.
from_rdkit
classmethod
¶
from_rdkit(
mol: Any,
*,
name: str = "",
metadata: Mapping[str, object] | None = None,
) -> Molecule
Wrap an existing RDKit Mol (shared, not copied).
from_smiles
classmethod
¶
from_smiles(
smiles: str,
*,
name: str = "",
sanitize: bool = True,
metadata: Mapping[str, object] | None = None,
) -> Molecule
Build a molecule from a SMILES string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
The SMILES to parse. |
required |
name
|
str
|
Optional label. |
''
|
sanitize
|
bool
|
Run RDKit sanitization (valence, aromaticity). Turn off only if you intend to sanitize yourself. |
True
|
metadata
|
Mapping[str, object] | None
|
Optional annotation dict. |
None
|
Raises:
| Type | Description |
|---|---|
RDKitNotInstalledError
|
If RDKit isn't installed. |
ValueError
|
If RDKit can't parse |
from_atom_array
classmethod
¶
from_atom_array(
atom_array: AtomArray,
*,
charge: int = 0,
perceive_bond_orders: bool = True,
name: str = "",
metadata: Mapping[str, object] | None = None,
) -> Molecule
Build a molecule from an :class:~molforge.core.AtomArray, perceiving
bonds from geometry.
The reverse of :meth:to_atom_array: it takes the array's element
symbols and 3D coordinates and infers connectivity — and, by default,
bond orders — with RDKit's geometry-based perception, recovering the
chemistry the flat coordinate representation doesn't carry.
Perception is designed for small molecules: pass a ligand you've
sliced out of a structure, not a whole protein (perceiving bonds over
thousands of atoms is slow and unreliable). Formal charges aren't
stored on the array, so give the net charge if the molecule isn't
neutral — perception needs it to assign bond orders correctly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom_array
|
AtomArray
|
The atoms to build from; its |
required |
charge
|
int
|
Net formal charge of the molecule (for bond-order perception). |
0
|
perceive_bond_orders
|
bool
|
Infer bond orders (single/double/aromatic); when False, only connectivity is perceived (all bonds single). |
True
|
name
|
str
|
Optional label. |
''
|
metadata
|
Mapping[str, object] | None
|
Optional annotation dict. |
None
|
Returns:
| Type | Description |
|---|---|
Molecule
|
A new :class: |
Raises:
| Type | Description |
|---|---|
RDKitNotInstalledError
|
If RDKit isn't installed. |
ValueError
|
If RDKit can't perceive bonds from the geometry. |
to_atom_array ¶
to_atom_array(
*,
embed: bool = False,
add_hydrogens: bool = False,
seed: int = 61453,
) -> AtomArray
Flatten to an :class:~molforge.core.AtomArray of 3D coordinates.
This is the bridge from chemistry (bonds, charges) to the flat,
coordinate-first world of :class:~molforge.core.AtomArray and the
structure/ML tooling built on it.
If the molecule already carries a conformer, its coordinates are used
as-is. If it has none — as a molecule parsed from SMILES does —
embed=True generates one on demand with RDKit's ETKDG, while
embed=False (the default) raises rather than inventing geometry.
The atoms come back as a single HETATM / ligand residue, with
per-element atom names (C1, C2, N1, ...) and formal
charges carried across.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embed
|
bool
|
Generate a 3D conformer when the molecule has none. Has no effect when the molecule already carries coordinates. |
False
|
add_hydrogens
|
bool
|
When embedding, add explicit hydrogens first for more realistic geometry (they appear in the output). |
False
|
seed
|
int
|
Random seed for embedding, so the geometry is reproducible. |
61453
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
AtomArray
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the molecule has no conformer and |
RDKitNotInstalledError
|
If RDKit isn't installed. |
Protein ¶
Protein(
atom_array: AtomArray | None = None,
*,
name: str = "",
metadata: dict[str, Any] | None = None,
)
A protein (or protein complex) structure.
Protein owns a single :class:AtomArray (atom_array) which is
the canonical data store. Hierarchical accessors (chains,
residues, etc.) read from it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom_array
|
AtomArray | None
|
The flat array of atoms backing this protein. If omitted, an empty array is used. |
None
|
name
|
str
|
Optional identifier (e.g. PDB ID). |
''
|
metadata
|
dict[str, Any] | None
|
Free-form key/value metadata (resolution, header,
engine confidence, ...). The dict accepts any keys, but the
names molforge's own parsers and engine wrappers use form a
stable, documented vocabulary — see
:mod: |
None
|
sequence
property
¶
Concatenated one-letter sequence across all protein/nucleic chains.
Chains are joined with "/" to make boundaries visible.
Non-polymer chains (ligand, water, ion) are skipped.
get_chain ¶
Look up a chain by (chain_id, model_id).
select ¶
Return a new Protein containing only atoms matching the filters.
Filters are forwarded to :meth:AtomArray.where.
Example
Keep only chain A, protein atoms¶
sub = protein.select(chain_id="A", entity_type="protein")
protein_only ¶
Return a new Protein containing only polymer protein atoms.
Drops ligands, waters, ions, and nucleic acids.
Provenance
dataclass
¶
Provenance(
engine: str,
operation: str = "",
engine_version: str = "",
molforge_version: str = "",
timestamp: str = "",
parameters: dict[str, Any] = dict(),
inputs: dict[str, Any] = dict(),
parent: Provenance | None = None,
)
A record of what produced this output.
Attributes:
| Name | Type | Description |
|---|---|---|
engine |
str
|
Name of the producer — typically an engine name
( |
operation |
str
|
The engine method that produced the output
( |
engine_version |
str
|
Version string of the engine itself. |
molforge_version |
str
|
The molforge version that ran this step.
Auto-filled by :meth: |
timestamp |
str
|
ISO-8601 UTC timestamp of when the step ran.
Auto-filled by :meth: |
parameters |
dict[str, Any]
|
Engine-specific arguments that drove this step
( |
inputs |
dict[str, Any]
|
Identifiers for the input data. For folding:
|
parent |
Provenance | None
|
The provenance of the input that this step consumed,
forming a chain back to the original input. |
The dataclass is frozen — once attached to an output, the audit
trail can't be mutated. Use :meth:replace for derived copies.
depth
property
¶
Number of steps in the chain (this step + ancestors).
Useful for assertions ("we expected a 3-step pipeline"). A terminal Provenance has depth 1.
from_engine
classmethod
¶
from_engine(
engine: str,
*,
operation: str = "",
engine_version: str = "",
parameters: dict[str, Any] | None = None,
inputs: dict[str, Any] | None = None,
parent: Provenance | None = None,
) -> Provenance
Build a :class:Provenance with auto-filled metadata.
Auto-fills :attr:molforge_version from molforge.__version__
and :attr:timestamp from the current UTC time. Wrappers should
prefer this over the bare constructor so those two fields are
consistent across the package.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine
|
str
|
Producer name (engine name or function path). |
required |
operation
|
str
|
The engine method that produced the output
( |
''
|
engine_version
|
str
|
Producer version. Pass |
''
|
parameters
|
dict[str, Any] | None
|
Engine-specific arguments. Must be JSON-serialisable; copied into a fresh dict so the caller's mutations don't affect the stored value. |
None
|
inputs
|
dict[str, Any] | None
|
Input identifiers. Same JSON constraint. |
None
|
parent
|
Provenance | None
|
Provenance of the input this step consumed. |
None
|
Returns:
| Type | Description |
|---|---|
Provenance
|
A frozen :class: |
Provenance
|
of |
Provenance
|
value fails here rather than at later serialisation time. |
replace ¶
Return a copy with the given fields replaced.
Frozen dataclasses don't support attribute assignment;
replace is the supported way to derive a modified copy.
Useful for tools that need to amend a provenance entry
(e.g. injecting a parent that wasn't known at construction
time)::
prov2 = prov.replace(parent=upstream_prov)
walk ¶
Yield this step then each ancestor, newest first.
walk() is the "stack" view: the current step, then what it
consumed, then what that consumed. Use :meth:chain for the
oldest-first view that reads naturally as "fold -> dock -> md".
chain ¶
Return the provenance chain oldest-first.
The first element is the originating step (the deepest
ancestor with parent=None); the last element is self.
Suitable for printing as a left-to-right pipeline::
for step in prov.chain():
print(step.engine)
# -> ESMFold
# -> Vina
# -> OpenMM
to_dict ¶
Convert to a JSON-serialisable plain dict.
The shape is::
{
"engine": str,
"operation": str,
"engine_version": str,
"molforge_version": str,
"timestamp": str, # ISO-8601 UTC
"parameters": dict,
"inputs": dict,
"parent": dict | None, # recursively
}
This is the on-disk format — when provenance gets serialised
(sidecar JSON, database row, etc.) this dict is the source of
truth. :meth:from_dict is the inverse.
from_dict
classmethod
¶
Reconstruct a :class:Provenance from :meth:to_dict output.
Tolerant of missing keys (treats them as defaults) so an older on-disk shape continues to load after fields are added.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
A dict shaped like :meth: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
A |
Provenance
|
class: |
Provenance
|
key, if present and non- |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
to_json ¶
Serialise to JSON text. Convenience wrapper around
:meth:to_dict and :func:json.dumps. Values are guaranteed
JSON-native because :meth:from_engine validated them at
construction time, so no default= coercion is needed.
from_json
classmethod
¶
Deserialise from JSON text. Inverse of :meth:to_json.
Residue ¶
is_standard_amino_acid ¶
Return True for the 20 canonical amino acids.
three_to_one ¶
Convert a 3-letter residue name to one-letter code.
Falls back to unknown for residues outside the canonical and known
non-canonical tables. Nucleotides are handled too.
Metadata vocabulary¶
The documented key vocabulary for Protein.metadata — string
constants and the ProteinMetadata TypedDict.
metadata_keys ¶
Documented key vocabulary for :attr:molforge.core.Protein.metadata.
Protein.metadata is a free-form dict[str, Any] by design — it
carries whatever a parser or engine wants to attach, including
open-ended things like PDB REMARK records. Keeping it a plain dict
means no breaking change for code that writes arbitrary keys.
But "free-form" shouldn't mean "undocumented". The keys below are the ones molforge's own parsers and engine wrappers produce, and they form the contract: downstream code can rely on these names and value types being stable across the 1.x series. Keys outside this list are still permitted but carry no stability guarantee.
Two things to use here:
- String constants (
PDB_ID,MEAN_CONFIDENCE, ...). Prefer these over bare string literals when reading or writing metadata, so a typo is aNameErrorat import time rather than a silently missing key at runtime. - :class:
ProteinMetadata— aTypedDict(total=False, every key optional) that documents the value type of each key. It's a typing aid only:Protein.metadatais still a plaindictat runtime, but annotating a local asProteinMetadatagives editors andmypythe key/type information.
Key groups:
- Structural-IO header keys — set by :func:
molforge.io.read_pdband :func:molforge.io.read_ciffrom file header records. - Uniform folding-engine keys — set by every folding-engine
wrapper (ESMFold, AlphaFold, Boltz, RoseTTAFold) so downstream code
can read prediction confidence without knowing which engine ran.
:func:
molforge.io.load_alphafoldalso populates these. - Engine-specific folding keys — set by some folding wrappers but not all; presence depends on the engine.
TITLE
module-attribute
¶
Free-text structure title from the PDB TITLE / mmCIF _struct.title (str).
CLASSIFICATION
module-attribute
¶
PDB HEADER classification field, e.g. "HYDROLASE" (str).
DEPOSITION_DATE
module-attribute
¶
Deposition date string as it appears in the PDB HEADER (str).
EXPERIMENTAL_METHOD
module-attribute
¶
Experimental method, e.g. "X-RAY DIFFRACTION" (str).
RESOLUTION
module-attribute
¶
Resolution in Angstrom (float). Absent for non-diffraction structures.
PROVENANCE
module-attribute
¶
First-class provenance record (:class:molforge.core.Provenance).
The canonical key for "what produced this output." Carries engine
name, version, parameters, inputs, and a recursive parent pointer to
the upstream step's provenance. See :mod:molforge.core.provenance
for construction helpers and the data shape.
This is the documented replacement for the older ad-hoc
metadata["engine"] / metadata["source_args"] keys. Both
continue to work for backwards compatibility; new code should write a
:class:Provenance to this key instead.
ENGINE
module-attribute
¶
Name of the folding engine that produced the structure (str), e.g.
"ESMFold", "AlphaFold", "Boltz", "RoseTTAFold".
SOURCE_SEQUENCE
module-attribute
¶
The one-letter input sequence the engine folded (str).
CONFIDENCE_PER_RESIDUE
module-attribute
¶
(L,) float32 array of per-residue pLDDT-style confidence (0-100).
CONFIDENCE_PER_ATOM
module-attribute
¶
(N_atoms,) float32 array of per-atom confidence (0-100).
MEAN_CONFIDENCE
module-attribute
¶
Scalar mean per-residue confidence (float, 0-100).
SOURCE
module-attribute
¶
Provenance tag (str). Set to "alphafold" by
:func:molforge.io.load_alphafold.
MODEL_NAME
module-attribute
¶
Engine-internal model identifier (str). Set by ESMFold.
MODEL_TYPE
module-attribute
¶
Model-type identifier (str). Set by AlphaFold, e.g. "monomer".
MODEL_VERSION
module-attribute
¶
Model-version identifier (str). Set by Boltz, e.g. "boltz2".
JOB_NAME
module-attribute
¶
Job name used for engine output files (str). Set by RoseTTAFold.
USE_MSA_SERVER
module-attribute
¶
Whether an MSA server was used (bool). Set by Boltz.
PTM
module-attribute
¶
Predicted TM-score for the whole structure (float). Set by Boltz.
IPTM
module-attribute
¶
Interface predicted TM-score (float). Set by Boltz; meaningful for complexes.
CONFIDENCE_SCORE
module-attribute
¶
Composite confidence score (float). Set by Boltz.
AFFINITY_VALUE
module-attribute
¶
Predicted binding affinity (float). Set by Boltz-2's affinity prediction —
its affinity_pred_value, a log-scale IC50-like value where lower means
stronger predicted binding.
AFFINITY_PROBABILITY
module-attribute
¶
Probability that the ligand is a binder (float, 0-1). Set by Boltz-2 from
affinity_probability_binary.
PAE
module-attribute
¶
(L, L) predicted aligned error matrix (float array). Set by RoseTTAFold.
PDE
module-attribute
¶
(L, L) predicted distance error matrix (float array). Set by RoseTTAFold.
PAE_INTER
module-attribute
¶
Scalar mean inter-chain PAE (float). RoseTTAFold's headline interface metric; values below ~10 indicate a high-quality interface.
PAE_PROT
module-attribute
¶
Scalar mean PAE over protein residues only (float). Set by RoseTTAFold.
MEAN_PAE
module-attribute
¶
Scalar mean of the full PAE matrix (float). Set by RoseTTAFold.
MEAN_PLDDT
module-attribute
¶
Scalar mean pLDDT (float). Set by RoseTTAFold and
:func:molforge.io.load_alphafold. Equivalent to :data:MEAN_CONFIDENCE;
the latter is the cross-engine-uniform name and should be preferred.
PLDDT
module-attribute
¶
(N_atoms,) float32 per-atom pLDDT. Legacy key set by
:func:molforge.io.load_alphafold; :data:CONFIDENCE_PER_ATOM is the
cross-engine-uniform name and should be preferred.
PLDDT_PER_RESIDUE
module-attribute
¶
(L,) float32 per-residue pLDDT. Legacy key set by
:func:molforge.io.load_alphafold; :data:CONFIDENCE_PER_RESIDUE is the
cross-engine-uniform name and should be preferred.
ProteinMetadata ¶
Bases: TypedDict
Typed view of the documented :attr:Protein.metadata keys.
Every key is optional (total=False). This is a typing aid only —
Protein.metadata remains a plain dict[str, Any] at runtime,
and keys outside this set are still permitted (without stability
guarantees). Annotate a local variable as ProteinMetadata to get
editor / mypy support for the documented vocabulary.