Input and Output#
The public tmol.io API converts common structure representations to and
from tmol.PoseStack.
Once the residue types are resolved, tmol.io.pose_stack_from_atom37()
builds a pose from tensors alone, for canonical and noncanonical chemistry
alike: residue identity comes from res_types and any further covalent
chemistry from covalent_bonds. Its slot layout is built by
tmol.io.atom37_slot_map_for_ordering(). The direct AtomWorks adapter is
the canonical-amino-acid special case of that path. To read chemistry from a
structure instead, tmol.io.pose_stack_from_atom37_and_topology() derives
the same information from general Biotite topology, including nucleic acids and
ligands. Repeated diffusion,
guidance, and search workloads should bind their fixed topology once with
tmol.io.prepare_atom37_pose_builder(); its returned callable accepts
each coordinate batch and preserves ordinary finite authored protein hydrogens
by default. Generated ligand types rebuild their hydrogen coordinates.
Use tmol.atom_array_from_file() or
tmol.pose_stack_from_file() for PDB, CIF, compressed CIF and binary CIF.
The reader options are model and assembly_id. Reading preserves
supplied names, coordinates, hydrogens and covalent bonds; declared unresolved
heavy atoms carry NaN coordinates. Chemistry the file leaves out is completed
from the component dictionary. Missing chemistry is allowed at this stage.
Known residues need only names and coordinates. Pass an existing param_db or
load prepared ligand_params_files to reuse ligand parameters with a coordinate-only
PDB/CIF. With prepare_ligands=True, pose preparation generates only missing
parameters and reports the residue name when required bond orders are absent.
Use return_context=True to retain the resulting parameter database for scoring
and repeated construction. Direct AtomArray inputs follow the same contract.
# Reuse known chemistry; the PDB needs only matching names and coordinates.
pose = pose_stack_from_file(
"complex.pdb", device, ligand_params_files=["ligand.tmol"],
)
# Prepare missing chemistry once, then reuse context.parameter_database.
pose, context = pose_stack_from_file(
"complex.cif", device, prepare_ligands=True, return_context=True,
)
tmol.pose_stack_from_file() also accepts MOL2 and SDF, file text and
streams. File and AtomArray inputs preserve matching supplied heavy-atom
coordinates for ordinary protein residues and build missing hydrogens. By
default, hydrogens are packed with OptH; pass no_optH=True to preserve finite
authored protein hydrogen coordinates instead. ligand_hydrogens controls the
hydrogens of generated ligand types: "input" keeps the input names and the
coordinates of hydrogens that sit at bond length from the parent their name
gives them, "names" (the default) keeps the names but rebuilds coordinates,
and "rebuild" generates names and rebuilds coordinates.
Write with tmol.file_from_pose_stack() or
tmol.file_from_atom_array(), which produce PDB or CIF and return the
text when no path is given.
Structure conversion between external formats and TMol poses.
- tmol.io.atom37_slot_map_for_ordering(canonical_ordering: CanonicalOrdering, atom_names_by_slot: Mapping[str, Sequence[str]], device: device) Tensor[source]#
Map each residue type’s Atom37 slots to canonical atom indices.
The mapping is a property of the residue-type table and the slot layout, not of any structure, so it is built once per (ordering, layout) pair.
Atoms that a terminus patch adds are deliberately left unmapped. They exist only on terminal residue variants, and offering one on an interior residue would disqualify that residue’s block types; tmol applies termini itself from the chain boundaries. Which atoms those are is read from the chemical database rather than named here.
- Parameters:
canonical_ordering – Residue and atom ordering the
res_typesindex into.atom_names_by_slot – Atom name occupying each slot, per residue name3. An empty name marks an unused slot.
device – Device for the returned tensor.
- Returns:
[n_residue_types, n_slots]canonical atom index per slot,-1where the slot is unused or the atom is not part of that residue type.
Examples
>>> slot_map = atom37_slot_map_for_ordering(co, layout, torch.device("cpu")) >>> slot_map.shape[1] 37
- tmol.io.atomworks_from_pose_stack(pose_stack: PoseStack) tuple[source]#
Convert a PoseStack back to atomworks UNIFIED_ATOM37_ENCODING tensors.
- Parameters:
pose_stack (PoseStack) – The PoseStack to convert. Must contain only standard amino acids.
- Returns:
coords (Tensor, shape [n_poses, max_n_res, 37, 3]) – Atom coordinates in the atomworks atom37 layout. Absent atoms are 0.
residue_type (Tensor[int64], shape [n_poses, max_n_res]) – Atomworks token indices (1..20 for real residues, 0 for padding).
chain_iid (Tensor[int64], shape [n_poses, max_n_res]) – Chain identifiers.
- tmol.io.build_context_from_atom_array(biotite_structure: AtomArray | AtomArrayStack, torch_device: device, param_db: ParameterDatabase | None = None, prepare_ligands: bool = False, ligand_ph: float = 7.4, strict_atom_types: bool = False, strict_ligands: bool = True, ligand_params_files: list[str] | None = None, chem_comp_types: dict | None = None, ligand_seed: int | None = None, ligand_hydrogens: str = 'names') PoseBuildContext[source]#
Build the structure-independent construction context.
The returned context holds only database/ligand-derived pieces (canonical ordering, residue-type set, packed block types, parameter database); it does not depend on the input structure’s coordinates and can be reused across structures sharing the same ligand(s).
biotite_structureis used only to detect and prepare ligands (whenprepare_ligands=True).- Parameters:
biotite_structure – Input AtomArray or AtomArrayStack. Used only for ligand detection/preparation when
prepare_ligands=True.torch_device – Target torch device.
param_db – Optional parameter database. When provided, canonical ordering, residue types, and packed block types are built from this database. If prepare_ligands=True, it is extended with ligand data. If None, defaults are used.
prepare_ligands – If True, detect and prepare non-standard residues (via
tmol.ligand, which uses RDKit for atom typing and residue-type construction).ligand_ph – pH AtomWorks protonates residues lacking hydrogens at before ligands are prepared (default 7.4, only used when prepare_ligands=True).
strict_atom_types – If True, unknown ligand atom types raise errors instead of using a fallback element heuristic.
strict_ligands – If True (default), raise when a detected ligand cannot be prepared and registered (instead of silently dropping it during pose construction). Pass False to fall back to warn-and-skip. Only used when prepare_ligands=True.
ligand_params_files – Optional list of tmol YAML params file paths. Residues defined in these files skip the RDKit/OB pipeline.
chem_comp_types –
{comp_id: type}from the input file’s_chem_comptable (seetmol.ligand._detect._chem_comp_types_from_cif), which says whether a residue belongs to a polymer where the file does not number it along a sequence. Only used when prepare_ligands=True.ligand_seed – Fixed RNG seed for the conformer each prepared residue is built from, making preparation reproducible. Only used when prepare_ligands=True.
ligand_hydrogens – “rebuild” names prepared ligands’ hydrogens by parent; “input” and “names” take the input’s names where its hydrogens pair up parent by parent. Only used when prepare_ligands=True.
- Returns:
PoseBuildContext containing canonical ordering, packed block types, parameter database, and residue type set.
- tmol.io.canonical_form_from_biotite(biotite_structure: AtomArray | AtomArrayStack, torch_device: device, co: CanonicalOrdering | None = None, missing_density_distance_threshold: float = 2.4, atom37_coords: Tensor | None = None, _filter_missing_mainchain: bool = True, _cut_covalent_partners: frozenset[str] = frozenset({})) CanonicalForm[source]#
Convert a Biotite AtomArray or AtomArrayStack to a CanonicalForm.
This function bridges between Biotite’s data structures and tmol’s internal representation by converting atom and residue information from string-based identifiers to tmol’s canonical integer-based indexing system.
- Parameters:
biotite_structure – A Biotite AtomArray (single structure) or AtomArrayStack (multiple structures) containing the molecular data. Must contain atom coordinates, residue names, atom names, chain IDs, and optionally B-factors and occupancy values.
torch_device – PyTorch device (e.g., torch.device(‘cuda’) or torch.device(‘cpu’)) where the resulting tensors should be allocated.
co – A CanonicalForm in case you want to use a non-default database (and thus may need a different mapping)
missing_density_distance_threshold – Maximum distance in angstroms for treating a polymer gap as missing density rather than a chain break.
atom37_coords – Optional autograd-tracked coordinate tensor of shape [n_poses, n_tokens, 37, 3]. When provided, coordinates are sourced from this tensor (routed by the
token_idandatom37_slotannotations onbiotite_structure); all-NaN mapped triplets are treated as missing while unmapped finite reference atoms remain context. The geometry-based missing-density check is skipped so the topology stays fixed and gradients flow. Seepose_stack_from_atom37_and_topology().
- Returns:
- A data structure containing:
chain_id: Tensor mapping residues to chain indices
res_types: Tensor mapping residues to tmol residue type indices
coords: 4D tensor of atomic coordinates (poses x residues x atoms x 3)
res_labels: Original residue sequence numbers from the structure
residue_insertion_codes: PDB insertion codes for residues
chain_labels: Original chain identifiers from the structure
atom_occupancy: Optional tensor of atom occupancy values
atom_b_factor: Optional tensor of atom B-factor values
disulfides: Explicit cysteine sulfur bonds, including unresolved SG
res_not_connected: Tensor describing whether two consecutive residues should be treated as chemically bonded.
- Return type:
CanonicalForm
- tmol.io.pose_stack_from_atom37(atom37_coords: Tensor, res_types: Tensor, chain_id: Tensor, context: PoseBuildContext, *, slot_map: Tensor | None = None, disulfides: Tensor | None = None, cyclic_bonds: Tensor | None = None, covalent_bonds: Tensor | None = None, res_not_connected: Tensor | None = None, no_optH: bool = False, backprop_compatible_rebuild: bool = True, **kwargs: object) PoseStack[source]#
Build a differentiable PoseStack from Atom37 tensors alone.
One path for canonical and noncanonical poses. Residue identity comes from
res_typesindexed into the context’s canonical ordering, and any covalent chemistry the polymer connections do not already describe comes fromcovalent_bonds; noAtomArrayis consulted.- Parameters:
atom37_coords –
[n_poses, n_tokens, n_slots, 3], autograd-tracked.res_types –
[n_poses, n_tokens]index intocontext.canonical_ordering;-1marks padding.chain_id –
[n_poses, n_tokens]chain index per token.context – Chemistry resolved once, from any of the
build_context_from_*helpers.slot_map – Atom37 slot layout; see
atom37_slot_map_for_ordering().disulfides – Explicit
(pose, res1, res2)rows.cyclic_bonds – Explicit head-to-tail closures.
covalent_bonds – Explicit
(pose, res1, atom1, res2, atom2)links.res_not_connected – Suppressed polymer connections.
no_optH – True keeps input hydrogens at their input positions and builds missing ones from ideal geometry. By default the missing ones are then optimized (no ASN/GLN/HIS flips); input hydrogens keep their coordinates either way. Pass
optH_minimize=Trueto also minimize the optimized proton chis.backprop_compatible_rebuild – Optimize hydrogens differentiably, and raise
ValueErrorif a residue is missing heavy atoms, which only the packer can build, without gradients (default). False packs instead, without gradients for the atoms it places, and builds missing heavy atoms.
- Returns:
A pose whose coordinates carry gradients back to
atom37_coords.
Examples
>>> context = build_context_from_atom_array(array, device) >>> pose = pose_stack_from_atom37(coords, res_types, chain_id, context) >>> pose.coords.requires_grad True
- tmol.io.pose_stack_from_atom37_and_topology(atom37_coords: Tensor, biotite_structure: AtomArray | AtomArrayStack, context: PoseBuildContext, no_optH: bool = False, backprop_compatible_rebuild: bool = True, **kwargs) PoseStack | tuple[PoseStack, dict] | tuple[PoseStack, PoseBuildContext][source]#
Build a differentiable PoseStack from atom37 coordinates and a topology.
This is the topology-supplied Atom37 entry point. Unlike
pose_stack_from_canonical_aa_atom37(), which reads residue identity from a 1..20 token tensor and so covers only canonical amino acids, this supports any chemistry shared by AtomWorks and the supplied TMol context (including ordinary ligands and nucleic acids): the chemical topology is taken frombiotite_structurewhile mapped coordinates come from the autograd-trackedatom37_coordstensor.The topology is only read to derive residue identity and the Atom37 slot map. Once derived, construction is pure tensor work in the shared
_pose_stack_from_canonical_form_and_context. When the same topology is scored repeatedly, useprepare_atom37_pose_builder()to pay that derivation once; the returned builder never touches theAtomArrayagain. Unmapped finite reference atoms remain context. This is the entry point for differentiable scoring/guidance over atomized inputs, where the same fixed topology is scored repeatedly as coordinates move.Build
contextonce withbuild_context_from_atom_array()(withprepare_ligands=Truewhen ligands are present). For repeated diffusion or search steps, bind the topology once withprepare_atom37_pose_builder()and call the returned builder with each coordinate batch. Mapped reference coordinates are ignored, so one reference topology can be reused as those coordinates change. It must carry two integer annotations that map each atom into the atom37 tensor:token_id(the token axis) andatom37_slot(the 0..36 slot).Topology is derived from chemical identity alone –
missing_densitybreaks and automatic disulfide detection (both coordinate-dependent) are disabled – so the block types, termini, and atom count stay fixed as coordinates change. This adapter does not classify or allowlist residue types or elements: newly supported PTMs, ions, and metals work through the same API once they are represented by the supplied context and canonical ordering.- Parameters:
atom37_coords (Tensor, shape [n_poses, n_tokens, 37, 3]) – Autograd-tracked coordinates in the atomworks atom37 layout.
biotite_structure (biotite AtomArray) – Reference topology carrying
token_idandatom37_slotannotations.context (PoseBuildContext) – Structure-independent context from
build_context_from_atom_array().no_optH (bool) – True keeps input hydrogens at their input positions and builds missing ones from ideal geometry. By default (False) the missing ones are then optimized, without ASN/GLN/HIS flips; finite input hydrogens keep their coordinates either way. Pass
optH_minimize=Trueto also minimize the optimized proton chis.backprop_compatible_rebuild (bool) – Optimize hydrogens differentiably, and raise
ValueErrorif a residue is missing heavy atoms, which only the packer can build, without gradients (default). False packs instead, without gradients for the atoms it places, and builds missing heavy atoms.**kwargs – Additional arguments forwarded to
pose_stack_from_atom_array.
- Returns:
Whose
coordscarry gradients back toatom37_coords.- Return type:
- tmol.io.pose_stack_from_canonical_aa_atom37(coords: Tensor, residue_type: Tensor, chain_iid: Tensor, no_optH: bool = False, backprop_compatible_rebuild: bool = True, **kwargs) PoseStack[source]#
Build a PoseStack from atomworks UNIFIED_ATOM37_ENCODING tensors.
This is the tensor-only Atom37 entry point. Residue identity comes from
residue_typealone, so nothing but tensors is required – but for the same reason it is limited to the canonical amino acids with the canonical n- and c-termini patches.For anything else – noncanonical residues, ligands, nucleic acids, or covalent links – residue identity cannot be read off a 1..20 token, and
pose_stack_from_atom37_and_topology()is the entry point; it takes the chemistry from a supplied topology instead.Both build a
CanonicalFormand finish in the same constructor, so the choice here is only about how residue identity is supplied, not about how the pose is built.- Parameters:
coords (Tensor, shape [batch, n_res, 37, 3]) – Atom coordinates in the atomworks atom37 layout.
residue_type (Tensor[int64], shape [batch, n_res]) – Atomworks token indices in 1..20 (standard protein only), or 0 for padding.
chain_iid (Tensor[int64], shape [batch, n_res]) – Chain identifiers (integer IDs, not string labels).
no_optH (bool) – True keeps input hydrogens at their input positions and builds missing ones from ideal geometry. By default (False) the missing ones are then optimized, differentiably and without ASN/GLN/HIS flips; finite input coordinates are kept either way.
backprop_compatible_rebuild (bool) – Optimize hydrogens differentiably, and raise
ValueErrorif a residue is missing heavy atoms, which only the packer can build, without gradients (default). False packs instead, without gradients for the atoms it places, and builds missing heavy atoms.**kwargs – Additional arguments passed to
_pose_stack_from_canonical_form_and_context, such asoptH_minimizeandpacker_seed.
- Return type:
- Raises:
ValueError – If any
residue_typevalue is outside 1..20 (protein-only) and not 0 (padding).
- tmol.io.prepare_atom37_pose_builder(biotite_structure: AtomArray | AtomArrayStack, context: PoseBuildContext) PreparedAtom37PoseBuilder[source]#
Prepare a callable for repeatedly binding Atom37 coordinates to topology.
This is the campaign-oriented counterpart to
pose_stack_from_atom37_and_topology(): immutable residue identity, connectivity, fragmentation, and Atom37 routing are resolved once. Calling the returned builder with a coordinate tensor constructs a differentiable pose while retaining TMol’s usual missing-atom behavior. The returned builder preserves finite input hydrogens by default; passopt_h=Trueto optimize them after construction.