Input and Output#

The public tmol.io API converts common structure representations to and from tmol.pose.PoseStack. The direct AtomWorks adapter uses its protein-only unified Atom37 representation. For differentiable Atom37 coordinates with general Biotite topology, including nucleic acids and ligands, use tmol.io.pose_stack_from_atom37_and_biotite(). Repeated diffusion, guidance, and search workloads should bind their fixed topology once with tmol.io.prepare_pose_stack_from_atom37(); its returned callable accepts each coordinate batch and optimizes hydrogens by default.

Structure conversion between external formats and TMol poses.

exception tmol.io.Atom37MappingError[source]#

Bases: ValueError

An AtomArray cannot be routed unambiguously into an Atom37 tensor.

class tmol.io.CanonicalForm(chain_id: Tensor[slice(None, None, None), slice(None, None, None)], res_types: Tensor[slice(None, None, None), slice(None, None, None)], coords: Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None), 3], res_labels: NDArray[slice(None, None, None), slice(None, None, None)], residue_insertion_codes: NDArray[slice(None, None, None), slice(None, None, None)], chain_labels: NDArray[slice(None, None, None), slice(None, None, None)], atom_occupancy: NDArray[slice(None, None, None), slice(None, None, None), slice(None, None, None)] | None, atom_b_factor: NDArray[slice(None, None, None), slice(None, None, None), slice(None, None, None)] | None, disulfides: Tensor[slice(None, None, None), 3] | None, res_not_connected: Tensor[slice(None, None, None), slice(None, None, None), 2] | None)[source]#

Bases: object

This class holds the data that describe a (stack of) structure(s) in a poised, ready-to-use state.

This datastructure holds the information necessary to determine the chemical identities of the residues in the structure(s), which may be under-determined from tmol’s perspective by the source of the structure (e.g. OpenFold does not explicitly model termini). The atoms that are present are represented with non-NaN coordinates in the coords array; the order in which those atoms appear is given by a particular CanonicalOrdering object.

The datastructure also holds convenience information such as author-provided residue labels (ints), chain labels (strings) & insertion codes (strings) as well as the occupancy and B-factor of each atom. These are not strictly necessary but are often useful when processing structures.

class tmol.io.CanonicalOrdering(max_n_canonical_atoms: int, restype_io_equiv_classes: Tuple[str, ...], restypes_ordered_atom_names: Mapping[str, Tuple[str, ...]], restypes_atom_index_mapping: Mapping[str, Mapping[str, int]], restypes_mainchain_atoms: Mapping[str, Tuple[str, ...] | None], restypes_required_mainchain_atoms: Mapping[str, Tuple[str, ...] | None], restypes_default_termini_mapping: Mapping[str, Tuple[str, str]], down_termini_patches: Tuple[str, ...], up_termini_patches: Tuple[str, ...], termini_patch_added_atoms: Mapping[str, Tuple[str, ...]], cys_inds: CysSpecialCaseIndices, his_inds: HisSpecialCaseIndices)[source]#

Bases: object

The canonical ordering class describes the integer ordering of residue types and for atoms within those residue types for the collection of available residue types defined by a PatchedChemicalDatabase.

The canonical ordering class’s purpose is to enable creation of a “canonical form” dictionary that describes a molecular system in the way that tmol expects in order to construct a PoseStack.

There is no “canonical form” dictionary is simply a dictionary holding the at-least-three-but-as-many-as-eight arguments to tmol.io._pose_stack_construction.pose_stack_from_canonical_form after the first two. That is, it must contain “chain_id”, “res_types” and “coords” entries.

When constructing a PoseStack, there are multiple residue types for each “equivalence class” (think 3-letter code); e.g. for “CYS” there’s the standard middle-of-a-polypeptide-chain CYS, the standard middle-of-a-polypeptide-chain disulfide-forming CYS, and then for those two, four variants for the N-, C-, and both-N- and-C terminal forms; eight total options for a single “CYS” three-letter code. tmol collects all of the various forms of a single equivalence class and creates a list of all atom names across all the residue types for it. You can then provide tmol the set of atoms that are present at a given position by giving a non-NaN coordinate for that entry in an [n-poses x max-n-res x max-ats-per-res x 3] tensor of coordinates. Atoms with NaN coordinates are taken as possibly present in the residue type; tmol will decide the best fit for which residue type to use at each position. If an atom is provided to tmol and it is not present for a given residue type, then that residue type will be disqualified from consideration. Thus an important part of telling tmol which atoms are present is mapping from an atom name to an index for that atom. The CanonicalOrdering object is where that mapping is encoded. It also handles the mapping from alternate-atom-name to canonical-form-atom index; e.g. in PDBv2, glycine’s two hydrogens were named “HA1” and “HA2”, but in PDBv3, they are named “1HA” and “2HA.” So that we can parse PDB files written in PDBv2 and PDBv3, we have an idea of an “alias” for an atom; see the restypes_atom_index_mapping data member.

Four data members are especially useful:

  • max_n_canonical_atoms

  • restype_io_equiv_classes

  • restypes_ordered_atom_names

  • restypes_atom_index_mapping

The remaining data members are primarily for internal tmol functionality.

max_n_canonical_atoms: the largest number of distinct atom names among all

variants of a single residue type (equivalence class) across all residue types

restype_io_equiv_classes:

essentially the list of 3-letter codes for the residue types that are readable; use the index function (e.g. co.restype_io_equiv_classes.index(“TRP”)) to obtain the integer meant to represent each restype

restypes_ordered_atom_names:

the ordered list of the names of each atom for every allowed residue type; does not include the alternate names for atoms. Atoms should be given to tmol in this order; e.g. by putting the coordinate of the ith atom in the ith entry of the coordinate tensor (e.g. coords[p, r, i] for pose p, residue r)

restypes_atom_index_mapping:

mapping for each name3 from atom name and atom name alias to the index of that atom for every allowed residue type in the restypes_ordered_atom_names list; this is probably more useful than the restypes_ordered_atom_names list, especially if you are using the PDBv2 naming convention (as Rosetta3 does) instead of the PDBv3 convention.

class tmol.io.PoseBuildContext(canonical_ordering: CanonicalOrdering, packed_block_types: PackedBlockTypes, parameter_database: ParameterDatabase, restype_set: ResidueTypeSet, fragment_definitions: tuple[LigandFragmentDefinition, ...] = (), ligand_names: dict[str, str] = <factory>)[source]#

Bases: object

Immutable, structure-independent construction context.

Holds only the pieces that depend on the parameter database / ligand set (not on any particular input), so it can be built once and reused across many inputs that share the same ligand(s).

class tmol.io.PreparedAtom37PoseBuilder(context: PoseBuildContext, canonical_template: CanonicalForm, mapped_token_id: Tensor, mapped_slot: Tensor, mapped_residue: Tensor, mapped_atom: Tensor, max_token_id: int, fragment_mapping: FragmentedLigandPoseMapping | None = None, topology_cache_safe: bool = True, pose_topologies: dict[int, _PreparedAtom37PoseTopology] = NOTHING)[source]#

Bases: object

Bind immutable Biotite topology for repeated Atom37 pose construction.

tmol.io.atom_records_from_coords(pbt: PackedBlockTypes, chain_ind_for_block: Tensor[slice(None, None, None), slice(None, None, None)], block_types64: Tensor[slice(None, None, None), slice(None, None, None)], pose_like_coords: Tensor[slice(None, None, None), slice(None, None, None), 3], block_coord_offset: Tensor[slice(None, None, None), slice(None, None, None)], residue_labels: NDArray[slice(None, None, None), slice(None, None, None)] | None, residue_insertion_codes: NDArray[slice(None, None, None), slice(None, None, None)] | None, chain_labels: NDArray[slice(None, None, None), slice(None, None, None)] | None, atom_occupancy: NDArray[slice(None, None, None), slice(None, None, None)], atom_b_factor: NDArray[slice(None, None, None), slice(None, None, None)]) NDArray[source]#

Create a numpy array holding the atom records needed to write a PDB file from the coordinates and block types of a stack of structures, laid out in pose-stack form.

tmol.io.atom_records_from_pose_stack(pose_stack: PoseStack, merge_fragments: bool = True) NDArray[source]#

Create a numpy array holding the atom records needed to write a PDB file from a PoseStack.

Fragmented ligands use their original residue identity by default. Pass merge_fragments=False to retain the separate fragment residue numbers.

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.biotite_from_canonical_form(cf: CanonicalForm, co: CanonicalOrdering | None = None) AtomArray | AtomArrayStack[source]#

Convert canonical TMol tensors to a Biotite atom array.

Parameters:
  • cf – Canonical coordinates, residue identities, and metadata.

  • co – Canonical atom ordering. Defaults to the Biotite ordering.

Returns:

One atom array, or an atom-array stack for multiple coordinate sets.

Raises:

ValueError – If poses in a multi-pose input have different metadata.

tmol.io.biotite_from_pose_stack(pose_stack: PoseStack, co: CanonicalOrdering | None = None, merge_fragments: bool = True) AtomArray | AtomArrayStack[source]#

Convert PoseStack back to Biotite structure.

Parameters:
  • pose_stack – Pose stack to convert.

  • co – Canonical ordering used for conversion. Provide the ordering that was used when ligands or custom residue types are present.

  • merge_fragments – Restore fragmented ligands to their original residue identity. Set to False to keep fragment residues separate.

Returns:

Biotite AtomArray for single-pose or AtomArrayStack for multi-pose.

tmol.io.build_context_from_biotite(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, sample_proton_chi: bool = True) 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_structure is used only to detect and prepare ligands (when prepare_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 – Target pH for ligand protonation (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.

  • sample_proton_chi – If True, prepared ligands emit PROTON_CHI chi_samples for polar-hydrogen rotations (driving OptHSampler). Enabled by default; pass False to suppress proton-chi samples. 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_atomworks(coords: Tensor, residue_type: Tensor, chain_iid: Tensor) CanonicalForm[source]#

Build a CanonicalForm from atomworks UNIFIED_ATOM37_ENCODING tensors.

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. Must be in 1..20 (standard protein only).

  • chain_iid (Tensor[int64], shape [batch, n_res]) – Chain identifiers.

Return type:

CanonicalForm

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) 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_id and atom37_slot annotations on biotite_structure) instead of the static biotite coordinates, and the geometry-based missing-density check is skipped so the topology stays fixed and gradients flow. See pose_stack_from_atom37_and_biotite().

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: None (not handled in this conversion)

  • res_not_connected: Tensor describing whether two consecutive residues should be treated as chemically bonded.

Return type:

CanonicalForm

tmol.io.canonical_form_from_pdb(canonical_ordering: CanonicalOrdering, pdb_lines_or_fname: str | List, device: device, *, residue_start: int | None = None, residue_end: int | None = None, res_not_connected: Tensor[slice(None, None, None), slice(None, None, None), 2] | None = None) CanonicalForm[source]#

Create a canonical form from either the contents of a PDB file as one long string or a list of individual lines from the file or by providing the name/path of a PDB file

pdb_lines_or_fname must either be a list of the lines in a PDB file or a string representing a file

tmol.io.canonical_form_from_pose_stack(canonical_ordering: CanonicalOrdering, pose_stack: PoseStack, chain_id=None)[source]#

Convert a pose stack to canonical residue and atom tensors.

Parameters:
  • canonical_ordering – Residue and atom ordering for the output tensors.

  • pose_stack – Poses to deconstruct.

  • chain_id – Optional integer chain identifiers shaped [pose, residue].

Returns:

Canonical form containing coordinates, residue metadata, and connectivity.

tmol.io.canonical_ordering_for_atomworks() CanonicalOrdering#

Construct the CanonicalOrdering for the protein subset used by the atomworks UNIFIED_ATOM37_ENCODING.

tmol.io.canonical_ordering_for_biotite() CanonicalOrdering#

Construct the CanonicalOrdering object to use for Biotite. This wont be used as a typical CanonicalOrdering object, since we aren’t mapping from int-to-int, and instead are going from string-to-int.

tmol.io.canonical_ordering_for_openfold() CanonicalOrdering#

Construct the CanonicalOrdering object that will be used for the subset of residue types that are used by OpenFold; this will be stable so that the entries in “coords” tensor member of the canonical form dictionary will be interpretable indefinitely and thus a canonical form dictionary can be serialized to disk and read again after an arbitrary amount of time

tmol.io.canonical_ordering_for_rosettafold2() CanonicalOrdering#

Construct the CanonicalOrdering object that will be used for the subset of residue types that are used by RoseTTAFold2; this will be stable so that the entries in “coords” tensor member of the canonical form dictionary will be interpretable indefinitely and thus a canonical form dictionary can be serialized to disk and read again after an arbitrary amount of time

tmol.io.create_pose_stack_from_sequences(seqs, packed_block_types: PackedBlockTypes | None = None, device: device | None = None, param_db=None, termini: bool = True, context: PoseBuildContext | None = None, return_context: bool = False)[source]#

Construct a PoseStack with zero coordinates from sequence strings.

See tmol.pose._sequence for the grammar. Returns (PoseStack, PoseBuildContext) when return_context is set; the context carries the database extended with any ligands the sequence names.

tmol.io.default_canonical_ordering() CanonicalOrdering#

Create a CanonicalOrdering object from the default set of residue types

tmol.io.default_packed_block_types(device: device) PackedBlockTypes[source]#

Create a PackedBlockTypes object from the default set of residue types

tmol.io.extended_pose_stack_from_sequences(seqs, device: device | None = None, param_db=None, termini: bool = True, context=None, return_context: bool = False)[source]#

Build a PoseStack from sequences with ideal geometry and extended backbone torsions.

See tmol.pose._sequence for the grammar. Returns (PoseStack, PoseBuildContext) when return_context is set.

tmol.io.fetch_pdb(pdbid)[source]#

Download a PDB-format structure from the RCSB Protein Data Bank.

tmol.io.packed_block_types_for_atomworks(device: device) PackedBlockTypes#

Construct the PackedBlockTypes for the protein subset used by the atomworks UNIFIED_ATOM37_ENCODING.

tmol.io.packed_block_types_for_biotite(device: device) PackedBlockTypes#

Construct the PackedBlockTypes (PBT) object that will used for Biotite. We’ll use the defaults since anything might show up in a Biotite AtomArray. Some things may show up in the AtomArrays that are not handled by this PBT, but that is work for the future.

tmol.io.packed_block_types_for_openfold(device: device) PackedBlockTypes[source]#

Construct the PackedBlockTypes (PBT) object that will be used for the subset of residue types that are used by OpenFold. For efficiency we use the same PBT in the creation of multiple PoseStacks. Thus we memoize this function. The user will only interact with this function if they are constructing PoseStacks from deserialized canonical form objects. See canonical_form_from_openfold for details.

tmol.io.packed_block_types_for_rosettafold2(device: device) PackedBlockTypes[source]#

Construct the PackedBlockTypes (PBT) object that will be used for the subset of residue types that are used by RoseTTAFold2. For efficiency we use the same PBT in the creation of multiple PoseStacks. Thus we memoize this function. The user will only interact with this function if they are constructing PoseStacks from deserialized canonical form objects. See canonical_form_from_rosettafold2 for details.

tmol.io.pose_stack_from_atomworks(coords: Tensor, residue_type: Tensor, chain_iid: Tensor, **kwargs) PoseStack[source]#

Build a PoseStack from atomworks UNIFIED_ATOM37_ENCODING tensors.

This function will build a PoseStack using a limited set of residue types: only the canonical amino acids with the canonical n- and c-termini patches. It begins by constructing a “canonical form” and then passes that canonical form to the pose_stack_from_canonical_form function.

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. Must be in 1..20 (standard protein only).

  • chain_iid (Tensor[int64], shape [batch, n_res]) – Chain identifiers (integer IDs, not string labels).

  • **kwargs – Additional arguments passed to pose_stack_from_canonical_form.

Return type:

PoseStack

Raises:

ValueError – If any residue_type value is outside 1..20 (protein-only).

tmol.io.prepare_pose_stack_from_atom37(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_biotite(): 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 optimizes hydrogens by default; pass opt_h=False to disable it.

tmol.io.pose_stack_from_atom37_and_biotite(atom37_coords: Tensor, biotite_structure: AtomArray | AtomArrayStack, context: PoseBuildContext, no_optH: bool = False, **kwargs) PoseStack | tuple[PoseStack, dict] | tuple[PoseStack, PoseBuildContext][source]#

Build a differentiable PoseStack from atom37 coordinates and a topology.

Unlike pose_stack_from_atomworks(), this supports any chemistry shared by AtomWorks and the supplied TMol context (including ordinary ligands and nucleic acids): the chemical topology is taken from biotite_structure while the coordinates come from the autograd-tracked atom37_coords tensor. This is the entry point for differentiable scoring/guidance over atomized inputs, where the same fixed topology is scored repeatedly as coordinates move.

Build context once with build_context_from_biotite() (with prepare_ligands=True when ligands are present). For repeated diffusion or search steps, bind the topology once with prepare_pose_stack_from_atom37() and call the returned builder with each coordinate batch. biotite_structure is used only for its chemical identity, so a single reference structure can be reused regardless of its coordinates. It must carry two integer annotations that map each atom into the atom37 tensor: token_id (the token axis) and atom37_slot (the 0..36 slot).

Topology is derived from chemical identity alone – missing_density breaks 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_id and atom37_slot annotations.

  • context (PoseBuildContext) – Structure-independent context from build_context_from_biotite().

  • no_optH (bool) – Run TMol’s hydrogen optimization pipeline when False (default). Pass True to leave newly built hydrogens at ideal positions.

  • **kwargs – Additional arguments forwarded to pose_stack_from_biotite.

Returns:

Whose coords carry gradients back to atom37_coords.

Return type:

PoseStack

tmol.io.pose_stack_from_biotite(biotite_structure: AtomArray | AtomArrayStack, torch_device: device, param_db: ParameterDatabase | None = None, missing_density_distance_threshold: float = 2.4, no_optH: bool = False, 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, sample_proton_chi: bool = True, return_context: bool = False, context: PoseBuildContext | None = None, atom37_coords: Tensor | None = None, **kwargs: object) PoseStack | tuple[PoseStack, dict] | tuple[PoseStack, PoseBuildContext][source]#

Build a PoseStack from the output generated by Biotite.

To score many structures that share the same ligand(s) efficiently, build the (expensive, structure-independent) context once and reuse it:

context = build_context_from_biotite(struct0, dev, prepare_ligands=True)
for struct in structures:
    pose_stack = pose_stack_from_biotite(struct, dev, context=context)

Reusing a context skips rebuilding the parameter database, canonical ordering, residue-type set, and packed block types; only the per-structure canonical form is recomputed (see the context arg).

Parameters:
  • biotite_structure – A Biotite AtomArray or AtomArrayStack.

  • torch_device – Target PyTorch device.

  • param_db – Optional ParameterDatabase. When provided, conversion and pose construction use this database. If prepare_ligands=True, it is extended with ligand data. Mutually exclusive with context.

  • missing_density_distance_threshold – Distance threshold in Angstroms. Adjacent residues whose closest inter-atom distance exceeds this value are treated as disconnected (upper/lower connects broken). Set to 0 to disable. Default is 2.4.

  • no_optH – When False (default), all residues with complete heavy atoms are packed with OptHSampler to place and optimize hydrogen positions and NHQ flips, while residues with missing heavy atoms are rebuilt with DunbrackChiSampler. When True, only missing heavy-atom sidechains are rebuilt with Dunbrack; hydrogens are left at the kinematically ideal positions produced during pose construction.

  • prepare_ligands – If True, detect and prepare non-standard residues (see build_context_from_biotite for details).

  • ligand_ph – Target pH for ligand protonation (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. Pass False to warn-and-skip. Only used when prepare_ligands=True.

  • ligand_params_files – Optional list of tmol YAML params file paths.

  • sample_proton_chi – If True, prepared ligands emit PROTON_CHI chi_samples so OptHSampler samples ligand polar-H rotamers (enabled by default; pass False to disable). Only used when prepare_ligands=True.

  • return_context – If True, return (pose_stack, PoseBuildContext).

  • context – Reusable context from build_context_from_biotite. It must be on torch_device and is mutually exclusive with param_db and prepare_ligands=True.

  • atom37_coords – Optional coordinates shaped [pose, token, 37, xyz]. When supplied, mapped finite coordinates are read from this tensor using the input structure’s integer token_id and atom37_slot annotations. Unmapped atoms and non-finite entries retain the Biotite coordinates, allowing TMol to build absent leaf atoms normally. The resulting pose coordinates remain connected to this tensor for autograd. Geometry-based missing-density and additional-disulfide detection are disabled so topology is fixed.

  • **kwargs – Additional arguments passed to pose_stack_from_canonical_form.

Returns:

PoseStack when no optional values requested and return_context is False. (PoseStack, PoseBuildContext) when return_context is True. (PoseStack, dict) when optional return values were requested via kwargs. Fragmented poses expose their block mapping as pose_stack.split_block_mapping.

tmol.io.pose_stack_from_openfold(openfold_result_dictionary, **kwargs) PoseStack[source]#

Build a PoseStack from the output generated by openfold

This function will build a PoseStack using a limited set of residue type: only the canonical amino acids with the canonical n- and c-termini patches. It begins by constructing a “canonical form” and then passes that canonical form to the pose_stack_from_canonical_form function. See canonical_form_from_openfold (below) for details on this intermediate representation and how it might be useful to you.

Additional arguments to pose_stack_from_canonical_form may be passed through this function using the kwargs.

tmol.io.pose_stack_from_pdb(pdb_lines_or_fname: str | list, device: device, *, residue_start: int | None = None, residue_end: int | None = None, res_not_connected: Tensor[slice(None, None, None), slice(None, None, None), 2] | None = None, **kwargs) PoseStack[source]#

Construct a PoseStack given the contents of a PDB file or the name of a PDB file, using the full set of residue types contained in tmol’s chemical.yaml file.

Optionally, a subset of the residues in the range from residue_start to residue_end-1 can be requested. Any additional keyword arguments will be passed to pose_stack_from_canonical_form

tmol.io.pose_stack_from_rosettafold2(seq: Tensor, xyz: Tensor[slice(None, None, None), slice(None, None, None), 3], chainlens: List, **kwargs) PoseStack[source]#

Build a PoseStack from the output generated by RoseTTAFold2

This function will build a PoseStack using a limited set of residue type: only the canonical amino acids with the canonical n- and c-termini patches. It begins by constructing a “canonical form” and then passes that canonical form to the pose_stack_from_canonical_form function. See canonical_form_from_openfold (below) for details on this intermediate representation and how it might be useful to you.

Additional arguments to pose_stack_from_canonical_form may be passed through this function using the kwargs.

tmol.io.pose_stack_to_pdb_string(pose_stack: Any) str[source]#

Convert a PoseStack into PDB text suitable for molecular viewers.

Return one interactive viewer for several labeled AtomArray selections.

Selection values may be boolean atom masks. Query strings are also accepted when the supplied AtomArray provides a callable aa.mask(query) method. Selection results are resolved in Python and exact PDB atom serials are baked into the HTML. This avoids viewer-side query-language differences and remains exact when atom names or residue identifiers are duplicated. Clicking a label restyles the same model and animates the camera to the selected atoms, following the AtomWorks selection-gallery interaction.

Parameters:
  • atom_array – Structure displayed by the shared viewer.

  • selections – Display labels mapped to boolean atom masks or query strings.

  • notes – Optional explanatory text keyed by selection label.

  • width – Viewer width in pixels.

  • height – Viewer height in pixels.

  • highlight_color – Color used for the active selection.

tmol.io.switchable_view(structures: Mapping[str, Any], *, notes: Mapping[str, str] | None = None, width: int = 720, height: int = 420)[source]#

Return HTML that switches one 3Dmol viewer among labeled structures.

Parameters:
  • structures – Ordered mapping of display labels to structures accepted by view().

  • notes – Optional mapping of structure labels to short explanatory text.

  • width – Viewer width in pixels.

  • height – Viewer height in pixels.

tmol.io.to_atom_lines(atom_records)[source]#

Convert atom records into ATOM lines.

tmol.io.to_pdb(atom_records)[source]#

Atom record DataFrame as pdb text.

tmol.io.to_pdb_lines(atom_records)[source]#

Yields atom record DataFrame as pdb lines.

tmol.io.view(model: Any, *, width: int = 720, height: int = 420, style: Literal['cartoon', 'stick'] = 'cartoon', background_color: str = 'white', cartoon_color: str = 'spectrum', show_sidechains: bool = True, show_heteroatoms: bool = True, show_hover: bool = True, zoom_to: dict | None = None, highlighted: object | None = None, highlight_color: str = '#e83e8c')[source]#

Create a draggable py3Dmol viewer for a molecular structure.

model may be a PoseStack, a Biotite AtomArray or AtomArrayStack, PDB text, or a PDB path. highlighted is an optional boolean mask over the atoms in the first model; highlighted atoms are shown as thicker sticks and spheres. The return value remains a real py3Dmol.view object for compatibility with existing notebooks.

tmol.io.write_pose_stack_pdb(pose_stack: PoseStack, fname_out: str, merge_fragments: bool = True, **kwargs)[source]#

Write a PDB-formatted file to disk given an input PoseStack. Optionally, additional arguments may be passed to the inner function “atom_records_from_pose_stack.” Fragmented ligands use their original residue identity by default; pass merge_fragments=False to keep fragment residues separate.