Top-level API#
The most common TMol objects and workflows are imported directly from the
top-level package, for example from tmol import PoseStack. They are
documented in full on this page. More specialized functionality is exported by
the sub-packages documented in the other API pages, such as tmol.io,
tmol.pose, and tmol.score.
Core objects#
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. |
|
Move map for Cartesian-space minimization. |
|
FastRelax minimization of atom coordinates. |
|
Immutable batched coordinate constraints and their tensor storage. |
|
Kinds of directed connections represented in a fold forest. |
|
The fold forest will define the fold trees for the poses in a PoseStack. |
|
FastRelax minimization of kinematic DOFs (torsions and jumps). |
|
Structure-independent definition of one fragmented ligand type. |
|
Hierarchical internal-coordinate degrees of freedom for a pose stack. |
|
Holds other information about a structure as it's read in from a file. |
|
A class to aggregate the properties for a collection of residue types. |
|
Define which residue types may replace each original residue type. |
|
Configure residue identities, conformers, and movable sites for packing. |
|
Immutable chemical and scoring parameter container used by tmol. |
|
Chemical database containing residue types after variant application. |
|
Batch of molecular systems with shared residue-type definitions. |
|
Build heterogeneous pose stacks while preserving chemical-database identity. |
|
Weighted collection of energy terms rendered for a pose topology. |
|
Stable indices for energy terms in score-function weight tensors. |
Structure input, output, and visualization#
Read a PDB, CIF, MOL2 or SDF structure into an AtomArray. |
|
Convert a PoseStack to an AtomArray or AtomArrayStack. |
|
Build a PoseStack from sequences with ideal geometry and extended backbone torsions. |
|
Write an AtomArray as PDB or CIF; return the text when path is None. |
|
Write a PoseStack as PDB or CIF; return the text when path is None. |
|
Compare two or more structures, with the option to overlay them all. |
|
Build a PoseStack from an AtomArray or AtomArrayStack. |
|
Build a PoseStack from a PDB, CIF, MOL2 or SDF structure. |
|
Return one interactive viewer for several labeled AtomArray selections. |
|
Return HTML that switches one 3Dmol viewer among labeled structures. |
|
Create a draggable py3Dmol viewer for a molecular structure. |
Pose queries and editing#
Block index of one (chain, author residue label). |
|
Boolean mask shaped |
|
One-letter sequence of one pose's real (non-padding) blocks. |
|
Names of the torsions defined on a block's type, in database order. |
|
Change one block's residue identity via the packer. |
|
Mutate every real block of one pose whose identity doesn't match |
|
Restore original residue identities on exported ligand fragments. |
Scoring, packing, and optimization#
Return a ScoreFunction implementing the beta_nov2016_cart score function of Rosetta3. |
|
Return each ligand fragment's interaction with |
|
Relax poses through repeated side-chain packing and minimization. |
|
Optimize side-chain conformers for a pose stack. |
|
Run minimization on a PoseStack in Cartesian coordinate space. |
|
Run minimization on a PoseStack in internal DOF space. |
Environment#
Whether the TMol backend in use includes CUDA kernels (independent of GPU availability). |
Reference#
TMol: GPU-accelerated molecular modeling with PyTorch.
- class tmol.CanonicalOrdering(max_n_canonical_atoms: int, restype_io_equiv_classes: Tuple[str, ...], restypes_ordered_atom_names: Mapping[str, Tuple[str, ...]], restypes_atom_elements: Mapping[str, Mapping[str, 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 | None, str | None]], down_termini_patches: Tuple[str, ...], up_termini_patches: Tuple[str, ...], termini_patch_added_atoms: Mapping[Tuple[str, str], Tuple[str, ...]], termini_only_atoms: Mapping[Tuple[str, str], Tuple[str, ...]], termini_only_atoms_by_class: Mapping[str, Tuple[str, ...]], cys_inds: CysSpecialCaseIndices, his_inds: HisSpecialCaseIndices, polymer_conn_inds: PolymerConnectionIndices, name3_aliases: Mapping[str, str] = NOTHING, restypes_virtual_atoms: Mapping[str, FrozenSet[str]] = NOTHING)[source]#
Bases:
objectThe 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_atomsrestype_io_equiv_classesrestypes_ordered_atom_namesrestypes_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.CartesianMoveMap(coord_mask: Tensor | None = None)[source]#
Bases:
objectMove map for Cartesian-space minimization.
A lightweight wrapper around a coordinate mask, passed to
CartesianRelaxMinimizerto choose the atoms thatfast_relax()minimizes.Unlike the full
MoveMap, which describes freedom in internal (torsion/jump) DOF space,CartesianMoveMapworks directly in atomic Cartesian space.- Parameters:
coord_mask – Boolean tensor of shape
[n_poses, max_n_atoms]indicating which atoms are free to move.Nonemeans all atoms are free to move (the default behaviour ofCartesianSfxnNetwork).
- class tmol.CartesianRelaxMinimizer(move_map: CartesianMoveMap | None = None, *, cuda_graph: bool | None = None)[source]#
Bases:
objectFastRelax minimization of atom coordinates.
Reuses the rendered scorer while the pose topology is unchanged.
- Parameters:
move_map – Atoms free to move; None frees every atom.
cuda_graph – Capture and replay the CUDA forward/backward scoring path. None turns it on for CUDA poses and off on CPU.
- class tmol.ConstraintSet(device: device, n_poses: int, constraint_function_inds: Tensor, constraint_atoms: Tensor[slice(None, None, None), 4, 3], constraint_params: Tensor[slice(None, None, None), slice(None, None, None)], constraint_num_unique_blocks: Tensor, constraint_unique_blocks: Tensor[slice(None, None, None), 3], constraint_functions: tuple[Callable[[Tensor[slice(None, None, None), slice(None, None, None), 3], Tensor[slice(None, None, None), slice(None, None, None)]], Tensor], ...])[source]#
Bases:
objectImmutable batched coordinate constraints and their tensor storage.
- classmethod create_empty(device: device, n_poses: int) ConstraintSet[source]#
Create an empty constraint set on a concrete device.
- classmethod concatenate(constraint_sets: Sequence[ConstraintSet | None], from_multiple_pose_stacks: bool = True, n_poses: int | None = None, ps_offset: Tensor | None = None) ConstraintSet | None[source]#
Combine constraint sets while deduplicating their scoring functions.
- Parameters:
constraint_sets – Constraint sets to combine;
Noneentries are retained when calculating pose offsets.from_multiple_pose_stacks – Shift pose indices between inputs when true. When false, all inputs describe the same pose batch.
n_poses – Pose count for the result, inferred when omitted.
ps_offset – Per-input pose offsets, inferred when omitted.
- Returns:
The combined constraint set, or
Nonewhen every input isNone.
- clone() ConstraintSet[source]#
Return a copy with independent tensor storage.
- to(device: device) ConstraintSet[source]#
Return a copy whose tensors and metadata use
device.
- split(index: int) ConstraintSet[source]#
Split out a single pose’s worth of constraints from a batch.
- static count_unique_blocks(atom_indices: Tensor[slice(None, None, None), slice(None, None, None), 3]) Tensor[source]#
Count distinct consecutive blocks referenced by each constraint.
- add_constraints_to_all_poses(fn: Callable[[Tensor[slice(None, None, None), slice(None, None, None), 3], Tensor[slice(None, None, None), slice(None, None, None)]], Tensor], atom_indices: Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None)], params: Tensor[slice(None, None, None), slice(None, None, None)] | None = None) ConstraintSet[source]#
Add the same constraints to every pose in the batch.
- Parameters:
fn – Function that scores coordinates and per-constraint parameters.
atom_indices – Integer
[constraint, atom, block/atom]indices, or full[constraint, atom, pose/block/atom]indices.params – Optional float
[constraint, parameter]values.
- Returns:
A new constraint set containing the replicated constraints.
- add_constraints(fn: Callable[[Tensor[slice(None, None, None), slice(None, None, None), 3], Tensor[slice(None, None, None), slice(None, None, None)]], Tensor], atom_indices: Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None)], params: Tensor[slice(None, None, None), slice(None, None, None)] | None = None) ConstraintSet[source]#
Return a constraint set containing the existing and new constraints.
- Parameters:
fn – Function that scores coordinates and per-constraint parameters.
atom_indices – Integer
[constraint, atom, pose/block/atom]indices. Omitting the pose column applies each constraint to every pose.params – Optional float
[constraint, parameter]values.
- Returns:
A new constraint set containing the added constraints.
- static replicate_constraints(n_poses: int, c_atms: Tensor[slice(None, None, None), slice(None, None, None), 3], c_params: Tensor[slice(None, None, None), slice(None, None, None)] | None) tuple[Tensor[slice(None, None, None), slice(None, None, None), 3], Tensor[slice(None, None, None), slice(None, None, None)] | None][source]#
Replicate pose-independent constraints and optional parameters.
- class tmol.EdgeType(*values)[source]#
Bases:
IntEnumKinds of directed connections represented in a fold forest.
- class tmol.FoldForest(max_n_edges: int, n_edges: NDArray, edges: NDArray[slice(None, None, None), slice(None, None, None), 4])[source]#
Bases:
objectThe fold forest will define the fold trees for the poses in a PoseStack. Each tensor in the class has its first dimension over the number of poses.
The primary definition of a FoldTree is the Edge. The Edge defines a connection between two parts of a Pose. The four types of edges are 1. polymer edges (analgous to the previously named “peptide edges” from Rosetta++ and Rosetta3), 2. jump edges which connect any pair of residues in the Pose, 3. root-jump edges, which originate at the explicit virtual root and connect to a particular residue, and 4. chemical edges, which join two residues through a single non-polymeric bond (Rosetta’s Edge::CHEMICAL). A polymer edge spans a contiguous range of polymeric block types where the “up” connection of residue i is connected to the “down” connection of residue i+1 for all i in the range between the “start” and “end” blocks.
Each edge is described by a 4-tuple of integers (type, start, end, jump-index); where type is one of the EdgeType enum values, start is the index of the upstream residue of the edge, end is the index of the downstream residue of the edge, and jump-index is used to assign an id to any particular jump edge; jump-edge indices must be unique and ascending from 0 to n_jumps-1. A chemical edge stores in that fourth slot the index of the connection on its start residue that leads to its end residue; the connection on the end residue follows from the PoseStack’s inter-residue connections. “Root jump” edges take their “identity” from the downstream residue of the edge, so they do not need an index.
The FoldForest in tmol differs from the FoldTree in Rosetta3 in that there is always a virtual root at the origin and any residue (block) may be connected to this root by a “root jump”. Such root-jump residues are defined by listing the residue that the root is connected to as the “end” residue; the “start” residue field should be left as -1. An example FoldForest for a ten-residue protein might be:
(polymer, 0, 4) (jump , 0, 7) (polymer, 7, 9) (polymer, 7, 6) (root-jump, -1, 0) (root-jump, -1, 5)
where both residues are 0 and 5 are connected to the root.
Note that in the MoveMap, the root-jumps are distinct from the non-root-jumps.
- classmethod reasonable_fold_forest(pose_stack: PoseStack)[source]#
Create a fold forest for each pose using only backbone (up/down) polymer connectivity.
Each biological chain (same chain_id) is rooted with a single root-jump to its first residue. Polymer gaps within that chain (chain breaks) become ordinary jump edges connecting the last residue before the gap to the first residue after it. Gaps between different biological chains produce separate root-jumps. Cyclic polymers (C→N cyclisation) are broken at the bond entering the lowest-index residue; that bond is dropped to keep the forest a valid tree. Every remaining kinematic connection – a glycan on a serine, a ligand on a lysine – becomes a chemical edge, so torsions across it propagate downstream; a chemical bond that would close a cycle is the one dropped.
- classmethod from_edges(edges: NDArray[slice(None, None, None), slice(None, None, None), 4]) FoldForest[source]#
Construct a fold forest from a padded edge array.
- Parameters:
edges – Edge records shaped
[pose, edge, 4]. Unused entries have-1in their edge-type column.- Returns:
A fold forest with per-pose edge counts inferred from
edges.
- class tmol.KinematicRelaxMinimizer(move_map: MoveMap | None = None, fold_forest: FoldForest | None = None, *, cuda_graph: bool | None = None)[source]#
Bases:
objectFastRelax minimization of kinematic DOFs (torsions and jumps).
Reuses the rendered scorer while the pose topology is unchanged.
- Parameters:
move_map – Torsions and jumps free to move; None frees every mainchain and sidechain torsion and every jump of each minimized pose stack.
fold_forest – Kinematic tree; None uses FoldForest.reasonable_fold_forest of each minimized pose stack.
cuda_graph – Capture and replay the CUDA forward/backward scoring path. None turns it on for CUDA poses and off on CPU.
- class tmol.LigandFragmentDefinition(ligand_name: str, atom_to_fragment: Mapping[str, int], fragment_ids: tuple[int, ...], fragment_preparations: tuple[LigandPreparation, ...], connections: tuple[FragmentConnection, ...])[source]#
Bases:
objectStructure-independent definition of one fragmented ligand type.
- class tmol.MoveMap(n_poses: int, max_n_blocks: int, max_n_named_torsions: int, max_n_atoms_per_block: int, device: device | None = None)[source]#
Bases:
objectHierarchical internal-coordinate degrees of freedom for a pose stack.
- classmethod from_pose_stack(ps: PoseStack) MoveMap[source]#
Construct a move map sized for
pswith all movement disabled.
- set_move_all_jump_dofs_for_jump(pose_selection: Tensor | int, jump_selection: Tensor | int | None = None, value: bool = True) None[source]#
Enable or disable all jump dofs for a particular set of jumps on particular poses.
If jump_selection is None, then the two dimensional settings tensor will be indexed by the pose_selection tensor only; if both are not None, then the settings tensor will be indexed by both the pose_selection tensor and the jump_selection tensor.
- set_move_all_jump_dofs_for_root_jump(pose_selection: Tensor | int, root_jump_selection: Tensor | int | None = None, value: bool = True) None[source]#
Enable or disable all jump dofs for a particular set of root-jumps on particular poses.
If root_jump_selection is None, then the two dimensional settings tensor will be indexed by the pose_selection tensor only; if both are not None, then the settings tensor will be indexed by both the pose_selection tensor and the jump_selection tensor.
- set_move_all_mc_tors_for_blocks(pose_selection: Tensor | int, block_selection: Tensor | int | None = None, value: bool = True) None[source]#
Enable or disable all DOFs for a partiular set of blocks on particular poses.
If block_selection is None, then the two dimensional settings tensor will be indexed by the pose_selection tensor only; if both are not None, then the tensor will be indexed by the pose_selection tensor and the block_selection tensor.
- Valid combinations of pose_selection and block_selection are, e.g.:
pose_selection: int, block_selection: int == a particular block on a particular pose
pose_selection: int, block_selection: None == all blocks on a particular pose
pose_selection: Tensor[bool][n_poses, max_n_blocks], block_selection: None == pose/block pairs encoded in “pose_selection” tensor
pose_selection: Tensor[int][N], block_selection: Tensor[int][N] == different blocks on different poses, selected by index
- set_move_mc_tor_for_blocks(pose_selection: Tensor | int, block_selection: Tensor | int | None = None, tor_selection: Tensor | int | None = None, value: bool = True) None[source]#
Enable or disable partiular main-chain torsions for a particular set of blocks on particular poses.
- Valid combinations of block_selection and tor_selection are:
pose_selection: int, block_selection: int, tor_selection: int == a single DOF
pose_selection: Tensor[bool][n_poses, max_n_blocks, max_n_dofs], block_selection: None, tor_selection: None == pose/block/tor triples encoded in “pose_selection” tensor
pose_selection: Tensor[int][N], block_selection: Tensor[int][N], dof_selection: Tensor[int][N] == different torsions on different blocks on different poses, selected by index
- set_move_sc_tor_for_blocks(pose_selection: Tensor | int, block_selection: Tensor | int | None = None, dof_selection: Tensor | int | None = None, value: bool = True) None[source]#
Enable or disable partiular side-chain torsions for a particular set of blocks on particular poses.
- set_move_named_torsion_for_blocks(pose_selection: Tensor | int, block_selection: Tensor | int | None = None, tor_selection: Tensor | int | None = None, value: bool = True) None[source]#
Enable or disable partiular named-torsions for a particular set of blocks on particular poses.
- set_move_jump_dof_for_jumps(pose_selection: Tensor | int, jump_selection: Tensor | int | None = None, dof_selection: Tensor | int | None = None, value: bool = True) None[source]#
Enable or disable all jump dofs for a particular set of jumps on particular poses.
If jump_selection is None, then the two dimensional settings tensor will be indexed by the pose_selection tensor only; if both are not None, then the settings tensor will be indexed by both the pose_selection tensor and the jump_selection tensor.
- set_move_jump_dof_for_root_jumps(pose_selection: Tensor | int, root_jump_selection: Tensor | int | None = None, dof_selection: Tensor | int | None = None, value: bool = True) None[source]#
Enable or disable all jump dofs for a particular set of root-jumps on particular poses.
If root_jump_selection is None, then the two dimensional settings tensor will be indexed by the pose_selection tensor only; if both are not None, then the settings tensor will be indexed by both the pose_selection tensor and the root_jump_selection tensor.
- set_move_atom_dof_for_blocks(pose_selection: Tensor | int, block_selection: Tensor | int | None = None, atom_selection: Tensor | int | None = None, dof_selection: Tensor | int | None = None, value: bool = True) None[source]#
Enable or disable partiular atom dofs for a particular set of blocks on particular poses.
Either only “pose_selection” should be not None or all four “selection” variables should be not None; in the former case, the settings tensor, self.move_atom_dof, will be indexed solely by the pose_selection tensor; in the latter case, the settings tensor will be indexed by all four selection tensors.
This function offers the finest grain control over which dofs should be minimized and settings made using this function will override any settings made using the other settings tensors.
- class tmol.PDBInfo(residue_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)], atom_b_factor: NDArray[slice(None, None, None), slice(None, None, None)], metal_origins: NDArray[slice(None, None, None), slice(None, None, None)] | None = None, residue_annotations: ndarray | None = None)[source]#
Bases:
objectHolds other information about a structure as it’s read in from a file.
The data held in this class has no impact on structure calculations, e.g. the energy of a conformation, but it is useful for preserving information about input structures for later output. If the information starts to diverge from the actual conformation held in a PoseStack, e.g. if residues are added or deleted, then it is the responsibility of the code that makes those changes to also update the PDBInfo object accordingly.
Datamembers:
- residue_labels: numpy array of strings giving residue ids for each residue.
shape: [n_poses x max_n_residues]
- residue_insertion_codes: numpy array of strings giving insertion codes
for each residue. shape: [n_poses x max_n_residues]
- chain_labels: numpy array of strings giving chain labels for each residue.
shape: [n_poses x max_n_residues]
- atom_occupancy: numpy array of floats giving occupancy for each atom.
shape: [n_poses x max_n_atoms_per_pose]
- atom_b_factor: numpy array of floats giving B-factors for each atom.
shape: [n_poses x max_n_atoms_per_pose]
- class tmol.PackedBlockTypes(chem_db: PatchedChemicalDatabase, restype_set: ResidueTypeSet, active_block_types: Sequence[RefinedResidueType], restype_index: Index, max_n_atoms: int, n_atoms: Tensor, atom_is_real: Tensor[slice(None, None, None), slice(None, None, None)], atom_is_hydrogen: Tensor[slice(None, None, None), slice(None, None, None)], atom_downstream_of_conn: Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None)], atom_paths_from_conn: Tensor[slice(None, None, None), slice(None, None, None), 13, 3], max_n_torsions: int, n_torsions: Tensor, torsion_is_real: Tensor[slice(None, None, None), slice(None, None, None)], torsion_uaids: Tensor[slice(None, None, None), slice(None, None, None), 3], is_torsion_mc: Tensor[slice(None, None, None), slice(None, None, None)], n_mc_torsions: Tensor, mc_torsion_is_real: Tensor[slice(None, None, None), slice(None, None, None)], mc_torsions: Tensor[slice(None, None, None), slice(None, None, None)], n_sc_torsions: Tensor, sc_torsion_is_real: Tensor[slice(None, None, None), slice(None, None, None)], sc_torsions: Tensor[slice(None, None, None), slice(None, None, None)], which_mcsc_torsions: Tensor[slice(None, None, None), slice(None, None, None)], max_n_bonds: int, n_bonds: Tensor, bond_is_real: Tensor[slice(None, None, None), slice(None, None, None)], bond_indices: Tensor[slice(None, None, None), slice(None, None, None), 2], max_n_conn: int, n_conn: Tensor, conn_is_real: Tensor[slice(None, None, None), slice(None, None, None)], conn_atom: Tensor[slice(None, None, None), slice(None, None, None)], down_conn_inds: Tensor, up_conn_inds: Tensor, polymeric_conn_inds: Tensor[slice(None, None, None), 2], default_jump_connection_atom_inds: Tensor, device: device)[source]#
Bases:
objectA class to aggregate the properties for a collection of residue types.
The PackedBlockTypes object holds an ordered set of residue types (specifically, RefinedResidueTypes); once constructed, this order will not change, so residue types may be referred to by index within this object.
Score terms cache derived tensors on this object to share annotation work across poses with the same ordered residue types. Topology annotations can be reused for the object’s lifetime. Parameter-dependent annotations must also identify their chemical/scoring sources, settings and tensor device; the presence of an attribute alone does not establish a valid cache hit. Keep historical configurations bounded, and let rendered scoring modules capture their requested annotation tensors instead of reading whichever configuration happens to be stored here during a later forward call.
Annotation process: There are three steps to the annotation process. 1) Terms annotate individual block types, 2) terms aggregate (concattenate) annotations of the individual block types for the packed_block_type, and 3) terms retrieve their annotations. 1) Typically, score terms will create one annotation for each of the RefinedResidueType objects that the PackedBlockTypes object holds in their method named “setup_block_type,” and cache these annotations on each RefinedResiduetype. The idiom we use is for these residue-type annotations to be held in numpy arrays (on the CPU). 2) The terms will then aggregate the annotations for each of the individual residue types into a single torch Tensor, one tensor for each property (or property group) the term needs, in their method named “setup_packed_block_types”; the idiom is for these annotations to be moved to the PackedBlockType’s device in this step. 3) Finally, each term will retrieve the cached annotations from the PackedBlockType in their “render_whole_pose_scoring_module” method.
- classmethod from_restype_list(chem_db: PatchedChemicalDatabase, restype_set: ResidueTypeSet, active_block_types: Sequence[RefinedResidueType], device: device) PackedBlockTypes[source]#
Pack residue-type metadata onto a concrete torch device.
- Parameters:
chem_db – Chemical database shared by the residue types.
restype_set – Source residue-type collection.
active_block_types – Ordered residue types to pack.
device – Target device. An unindexed CUDA device resolves to the current CUDA device.
- Returns:
Packed residue-type tensors and their concrete device metadata.
- Raises:
ValueError – If a residue type has more than
MAX_N_CONNconnections.
- class tmol.PackerPalette(noncanonical_design: bool = False)[source]#
Bases:
objectDefine which residue types may replace each original residue type.
- Parameters:
noncanonical_design – Also offer noncanonical residue types (such as AIB) and opposite-chirality amino acids (L <-> D) as replacements for other residues. Off by default, so a noncanonical type is considered only where the input already has it.
- block_types_from_original(pbt: PackedBlockTypes, orig: Tensor[slice(None, None, None), slice(None, None, None)]) tuple[Tensor[slice(None, None, None), slice(None, None, None)], Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None)], Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None)]][source]#
Return residue-type choices allowed by the default palette.
- Parameters:
pbt – Packed residue-type collection shared by the poses.
orig – Original residue-type index for each pose and block.
- Returns:
The number of choices, padded choice indices, and a mask marking each original residue type.
- create_restrict_to_repacking_mask(pbt: PackedBlockTypes, orig: Tensor[slice(None, None, None), slice(None, None, None)]) Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None)][source]#
Return choices that preserve each block’s original residue name.
- default_conformer_samplers()[source]#
All positions must build one rotamer, even if they are not being optimized.
Each block must have coordinates represented in the tensor with the other rotamers, and the easiest way to do that is to create a rotamer with the DOFs of the input conformation. The FallbackSampler copies these DOFs from the inverse-folded coordinates of the starting Pose’s blocks, but only for positions where no other sampler provides rotamers (e.g. residue types not covered by DunbrackChiSampler). Positions with at least one other sampler are left to that sampler exclusively. Future versions of PackerPalette have the option to override this method.
- class tmol.PackerTask(systems: PoseStack, palette: PackerPalette)[source]#
Bases:
objectConfigure residue identities, conformers, and movable sites for packing.
- set_chi_sample_budget(expanded_limit: int, limit: int)[source]#
Set expansion/fallback budgets without mutating reusable samplers.
Groups count one rotamer per member per conformer, including current. A required library that cannot fit is rejected before the group product is allocated. Sampler-specific defaults apply until this setter is used. The combined count across samplers and allowed types at each physical residue must also fit the larger limit before rows/coordinates merge.
- restrict_to_repacking(block_mask: Tensor[slice(None, None, None), slice(None, None, None)] | None = None)[source]#
Restrict selected blocks to the original residue name.
If
block_maskis omitted, restrict every block for backward compatibility. Otherwise, onlyTruepose/block entries are changed.
- restrict_absent_name3s(name3s: Collection[str], block_mask: Tensor[slice(None, None, None), slice(None, None, None)] | None = None)[source]#
Restrict selected blocks to block types with the given name3s.
If
block_maskis omitted, restrict every block for backward compatibility. This operation only disables choices and may therefore be composed safely with other task restrictions.- Raises:
ValueError – A block selected by
block_maskhad allowed block types and none of them has one ofname3s(for example, a residue bonded to a metal, which only its own variant can replace).
- add_conformer_sampler(sampler) None[source]#
Enable this sampler everywhere, registering its identity once.
A sampler bundle – anything exposing
expand_into_task– registers the samplers it is composed of instead, so callers can declare what they want sampled without composing it themselves.
- add_conformer_sampler_by_block_mask(sampler: ConformerSampler, block_type_mask: Tensor[torch.bool][:, :]) None[source]#
Enable this sampler in the mask, extending any existing selection.
- or_expand_chi(chi_ind: int) None[source]#
Request one extra standard-deviation sample for a chi torsion.
- or_expand_chi_to(chi_ind: int, sample_level: int) None[source]#
Raise a chi torsion’s expansion level without lowering it.
- disable_sampler_by_block_mask(sampler, block_mask: Tensor[slice(None, None, None), slice(None, None, None)])[source]#
Stop one sampler building rotamers for the masked blocks.
- disable_packing_by_block_mask(block_type_mask: Tensor[slice(None, None, None), slice(None, None, None)]) None[source]#
Disable packing at selected pose/block entries.
- or_bump_check(setting: bool = True) None[source]#
Enable bump checking without allowing later calls to disable it.
- property bump_check#
bump_check eliminates rotamers from consideration if they have a high interaction energy with “the background,” which is computed by taking the best energy a rotamer has with each neighbor across all the neighbor’s rotamers.
bump_check removes ~40% of all rotamers and can significantly improve running time, but, this comes at the expense of eliminating rotamers that are sometimes the best option when all others are bad in ways that bump-check’s rosie estimation cannot predict. In ~10% of tested crystal structures packed with only the base rotamers (no ex flags), bump_check increased the energy of the final rotamer rotamer assignment by >20 kcal/mol.
bump_check’s logic: eliminate a rotamer if it has a best possible energy with its neighbors and itself >5 kcal/mol and at least one other rotamer of the same block type at that residue has an energy less than 5 kcal/mol.
- class tmol.ParameterDatabase(scoring: ScoringDatabase, chemical: PatchedChemicalDatabase)[source]#
Bases:
objectImmutable chemical and scoring parameter container used by tmol.
The process-global accessor
get_default()returns a shared read-only instance. To add ligand or custom residue data, use_inject_residue_params()which returns a new database.- classmethod get_default() ParameterDatabase[source]#
Return the process-global cached parameter database (read-only).
- classmethod from_file(path: str) ParameterDatabase[source]#
Load chemical and scoring parameters rooted at
path.
- with_symmetric_gly() ParameterDatabase[source]#
A copy with symmetric glycine backbone tables and C-alpha hydrogens.
Glycine is achiral, but the tables derived from PDB statistics are not, so by default a structure and its mirror image score differently. This points glycine at the symmetrized tables instead. Its two C-alpha hydrogen ideal lengths and bonded targets are averaged, so rebuilding glycine also preserves reflection when the equivalent H names exchange. Other residues are untouched.
This optional model uses uniformly trans glycine bbdep-omega tables. Uniformity is a modeling choice, not a consequence of achirality.
- create_stable_subset(desired_names: list[str], desired_variants: list[str]) ParameterDatabase[source]#
Create a ParameterDatabase representing a subset of the RefinedResidueTypes in this PD’s PatchedChemicalDatabase from a list of RRT names and patched with the given variants (identified by their display names) where the order in which RRTs will appear in the subset will be stable over time (as long as this source PCD is only accumulating new RRTs over time and not losing the RRTs that it starts with).
- class tmol.PatchedChemicalDatabase(element_types: Tuple[Element, ...], atom_types: Tuple[AtomType, ...], residues: Tuple[RawResidueType, ...], variants: Tuple[VariantType, ...], name3_aliases: Tuple[Name3Alias, ...] = ())[source]#
Bases:
objectChemical database containing residue types after variant application.
- with_variants_applied(variants)[source]#
Return a copy with new patches applied to the residues already held.
with_added_residuespatches only what it adds, which is right for a patch a new residue brings with it. A conjugation patch instead acts on a residue the database already has – serine gains a connection at OG – so its forms are built here and appended alongside the base.
- class tmol.PoseStack(packed_block_types: PackedBlockTypes, coords: Tensor[slice(None, None, None), slice(None, None, None), 3], block_coord_offset: Tensor[slice(None, None, None), slice(None, None, None)], block_coord_offset64: Tensor[slice(None, None, None), slice(None, None, None)], inter_residue_connections: Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None), 2], inter_residue_connections64: Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None), 2], inter_block_bondsep: InterBlockBondsep, block_type_ind: Tensor[slice(None, None, None), slice(None, None, None)], block_type_ind64: Tensor[slice(None, None, None), slice(None, None, None)], chain_id: Tensor[slice(None, None, None), slice(None, None, None)], chain_id64: Tensor[slice(None, None, None), slice(None, None, None)], pdb_info: PDBInfo, constraint_set: ConstraintSet | None, device: device, split_block_mapping: SplitBlockMapping | None = None)[source]#
Bases:
objectBatch of molecular systems with shared residue-type definitions.
Chemistry and connectivity are fixed after construction, while
coordsmay be updated in place during minimization. Useattr.evolve()for structural metadata changes and replace or clonecoordsto avoid sharing mutable coordinate storage between pose stacks.- Parameters:
packed_block_types – Residue types and their score-term annotations.
coords – Cartesian coordinates shaped
[pose, atom, xyz].block_coord_offset – Per-residue atom offsets shaped
[pose, residue].block_coord_offset64 – 64-bit copy of
block_coord_offsetfor PyTorch.inter_residue_connections – Connected residue and connection indices.
inter_residue_connections64 – 64-bit connection-index copy.
inter_block_bondsep – Bond separation between residue connections, capped at
MAX_SIG_BOND_SEPARATIONand stored only for nearby residue pairs.block_type_ind – Packed block-type index for each residue;
-1is padding.block_type_ind64 – 64-bit block-type-index copy.
chain_id – Chain index for each residue.
chain_id64 – 64-bit chain-index copy.
pdb_info – Source labels, occupancy, and B-factor metadata.
constraint_set – Optional geometric constraints.
device – Device holding all pose tensors.
split_block_mapping – Optional mapping back to pre-split residue blocks.
- property n_ats_per_block: Tensor[slice(None, None, None), slice(None, None, None)]#
Return the number of atoms in each block
- property real_atoms: Tensor[slice(None, None, None), slice(None, None, None)]#
Return the mask of real, non-padding atoms in
coords.
- clone_sharing_topology() PoseStack[source]#
Copy per-pose state but share this stack’s immutable bond topology.
clone()deep-copies every tensor, including the connection tensors, even though nothing ever mutates them in place: they are built once byPoseStackBuilderand thereafter only read.Callers that vary coordinates while holding topology fixed – the FastRelax accept/restore loop, for example – should use this instead. Sharing is also what lets a rendered scoring module recognise the result as the same topology and reuse its cached parameters.
- Returns:
A PoseStack whose coordinate and block state are independently owned, and whose connection topology aliases this stack’s.
- expand_coords() tuple[Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None), 3], Tensor[slice(None, None, None), slice(None, None, None), slice(None, None, None)]][source]#
Expand packed coordinates into residue-major layout.
- Returns:
Coordinates shaped
[pose, residue, residue_atom, xyz]and the corresponding real-atom mask shaped[pose, residue, residue_atom].
- property n_res_per_pose: Tensor#
Return the number of real residues in each pose.
- is_real_block(pose_ind: int, block_ind: int) Tensor[source]#
Return a scalar boolean tensor indicating whether a block is real.
- block_type(pose_ind: int, block_ind: int) RefinedResidueType[source]#
Look up the block type for a particular pose and block and retrieve it from the PackedBlockTypes object. is_real_block must return True
- get_constraint_set() ConstraintSet | None[source]#
Return the optional constraint set associated with this pose stack.
- class tmol.PoseStackBuilder[source]#
Bases:
objectBuild heterogeneous pose stacks while preserving chemical-database identity.
- classmethod from_poses(pose_stacks: List[PoseStack], device: device) PoseStack[source]#
Combine one or more pose stacks on a common device.
- Parameters:
pose_stacks – Pose stacks whose chemical databases are one database or extensions of one another.
device – Device for the combined tensors.
- Returns:
A padded pose stack containing every input pose in order. Split- block mappings are concatenated when present.
- classmethod from_block_type_names(packed_block_types: PackedBlockTypes, sequences, chain_lengths)[source]#
Construct a zero-coordinate PoseStack from per-pose block type names.
A name may carry a non-polymeric connection as “NAME–conn-label”, where “conn” is the name of an inter-residue connection on that block type and “label” pairs up the two partners. E.g. a pose with two disulfides:
AAAA[CYD–dslf-first]AAA[CYD–dslf-second]AAA … AA[CYD–dslf-second]AAAA[CYD–dslf-first]AAA
- class tmol.ScoreFunction(param_db: ParameterDatabase, device: device)[source]#
Bases:
objectWeighted collection of energy terms rendered for a pose topology.
- Parameters:
param_db – Chemical and scoring parameters used to construct terms.
device – Device on which weights and rendered scorers operate. An unindexed CUDA device resolves to the current CUDA device.
- set_weight(st: ScoreType, weight: float) None[source]#
Set the weight for one score type.
The energy term that implements
stis created lazily when the requested weight is nonzero.- Parameters:
st – Score type to update.
weight – New scalar weight.
- get_weight(st: ScoreType) Tensor[source]#
Return the scalar weight for
ston the score-function device.
- score_type_covered_by_contained_term(st: ScoreType) bool[source]#
Return whether a constructed energy term implements
st.
- remove_term_for_score_type(st: ScoreType)[source]#
Remove the term containing
stonce all its weights are zero.
- all_score_types() list[ScoreType][source]#
Return score types in the same order as
all_terms().
- render_whole_pose_scoring_module(pose_stack: PoseStack, cuda_graph: bool | str = False) WholePoseScoringModule[source]#
Render a callable that repeatedly scores one fixed pose topology.
The returned callable owns the term-specific
torch.nn.Moduleobjects forpose_stack. Its default call returns weighted energies shaped[n_poses]as coordinates change during inference or minimization.Set
cuda_graphto"forward"for repeated inference,"forward_backward"for repeated scoring with coordinate gradients, orTrueto capture both paths. Graph capture requires CUDA and a fixed coordinate shape, dtype, and device. Forward-only replay reuses its output buffer; clone an output that must survive the next call.
- render_block_pair_scoring_module(pose_stack: PoseStack, *, interaction_only: bool = False) BlockPairScoringModule[source]#
Render a callable that retains scores for every residue-block pair.
The default call returns weighted energies shaped
[n_poses, max_n_blocks, max_n_blocks].Set
interaction_only=Truewhen only strictly off-diagonal block pairs will be consumed. Terms whose block-pair scores are known to be diagonal-only are then omitted. Diagonal entries in the returned matrix are incomplete in this mode.
- render_rotamer_scoring_module(pose_stack: PoseStack, rotamer_set: RotamerSet) RotamerScoringModule[source]#
Render a weighted sparse scorer for one rotamer set.
- Parameters:
pose_stack – Poses whose fixed background interacts with the rotamers.
rotamer_set – Candidate conformers and their pose/block indexing.
- Returns:
A callable that accepts rotamer coordinates and returns a sparse COO tensor shaped
[n_poses, n_rotamers, n_rotamers]. Callcoalesce()before reading its indices or values; optimized CPU results may already be coalesced.
- pre_work_initialization(pose_stack: PoseStack) None[source]#
Prepare active energy terms for a pose topology.
Repeated calls reuse topology-dependent setup when neither the terms, their options, nor the packed block types have changed. A newly built PackedBlockTypes with the same ordered residue-type objects can reuse the previous packed annotations.
- Parameters:
pose_stack – Poses whose topology will be scored.
- set_option(key: str, value) None[source]#
Set an option for all energy terms.
Options are passed to each energy term’s set_options method as a dictionary during pre_work_initialization.
- set_options(options: Dict) None[source]#
Set the score function options by a dict.
This replaces the options dict entirely - any previous values are gone.
- classmethod from_sfxn_file(path, param_db, device)[source]#
Create a ScoreFunction from a YAML weights file.
- Parameters:
path – Path to a YAML file containing a
weightsdict mapping score type names (as inScoreType) to their weights, as well as any other options to configure the score function.param_db – ParameterDatabase instance.
device – Target torch device.
- Returns:
Configured ScoreFunction with all weights from the file applied.
- class tmol.ScoreType(*values)[source]#
Bases:
AutoNumberStable indices for energy terms in score-function weight tensors.
- tmol.atom_array_from_file(source: str | Path | IO, format: Literal['pdb', 'cif', 'mol2', 'sdf'] | None = None, *, model: int = 1, assembly_id: str | None = None, res_name: str | None = None) AtomArray[source]#
Read a PDB, CIF, MOL2 or SDF structure into an AtomArray.
Preserve supplied names, coordinates, hydrogens and covalent connections. Declared unresolved heavy atoms have NaN coordinates. Chemistry the file leaves out is supplemented from the component dictionary; a MOL2/SDF molecule is registered as its own component.
- Parameters:
source – A path, the file’s text, or a stream. CIF paths may be gzip or Zstandard compressed, or binary CIF.
format – One of “pdb”, “cif”, “mol2”, “sdf”. Inferred from the extension, or else the contents, when None.
model – Model to read from a PDB/CIF.
assembly_id – Biological assembly to build from a CIF.
res_name – Component code for a MOL2/SDF molecule; the file’s when None.
- tmol.atom_array_from_pose_stack(pose_stack: PoseStack, co: CanonicalOrdering | None = None, merge_fragments: bool = True, include_virtual_atoms: bool = False) AtomArray | AtomArrayStack[source]#
Convert a PoseStack to an AtomArray or AtomArrayStack.
- 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. By default it is built from the pose’s own chemical database when the pose holds types outside the standard ordering.
merge_fragments – Restore fragmented ligands to their original residue identity. Set to False to keep fragment residues separate.
include_virtual_atoms – Also write virtual atoms, such as a metal’s site virtuals. A metal split out of a component is then left as its own residue, which its virtuals belong to; otherwise it is put back in the component it came from.
- Returns:
Biotite AtomArray for single-pose or AtomArrayStack for multi-pose, with every bond the poses’ residue types and connections declare: bond orders within residues, and chemical bonds between them, metal coordination typed COORDINATION.
- tmol.atom_for_residue_label(pose_stack: PoseStack, pose_ind: int, chain_id: str, res_id: str, atom_id: str) Tensor[source]#
[pose, block, atom]triple for one atom, addressed entirely in PDB space.res_idis a residue number as a string, with an optional PDB insertion-code suffix (e.g."12"or"12A");atom_idis that residue’s atom name (e.g."CA"). The result is anint32tensor onpose_stack’s device, suitable directly as one row of theatomstensorConstraintSet.add_constraints()expects.Raises ValueError if no block matches the chain/residue, or if the matching block’s residue type has no atom by that name.
- tmol.beta2016_score_function(device: device, param_db: ParameterDatabase | None = None) ScoreFunction[source]#
Return a ScoreFunction implementing the beta_nov2016_cart score function of Rosetta3.
Note that in Rosetta3, beta_nov2016 and beta_nov2016_cart are identical except for the inclusion of the bond-length, bond-angle, and bond-torsion terms implemented by the CartBonded energy term, and the exclusion of the ProClose energy term (which is not implemented in tmol).
- Parameters:
device – Target torch device.
param_db – Optional parameter database. If omitted, uses the process default parameter database and a memoized score function.
- Returns:
Configured ScoreFunction.
When param_db is provided, this creates a fresh score function (no memoization — caller owns database lifecycle).
See: https://pubs.acs.org/doi/10.1021/acs.jctc.6b0081 and https://pubs.acs.org/doi/full/10.1021/acs.jctc.7b00125
- tmol.block_for_residue_label(pose_stack: PoseStack, pose_index: int, chain: str, residue_id: str) int[source]#
Block index of one (chain, author residue label).
residue_idis a residue number as a string, with an optional PDB insertion-code suffix (e.g."12"or"12A").Raises ValueError if no block in the pose matches.
- tmol.blocks_for_residue_labels(pose_stack: PoseStack, pose_index: int, chain: str, residue_numbers: Tensor) Tensor[source]#
Block index of each (chain, author residue number) label in a batch.
residue_numbersmay have any shape; the result has the same shape. Entries with no matching block resolve to-1.
- tmol.calculate_fragment_interactions(pose_stack: PoseStack, partner_mask: Tensor[torch.bool][:, :], *, sfxn: ScoreFunction, mapping: SplitBlockMapping | _LegacyFragmentMapping | None = None, sum_terms: bool = False) FragmentInteractionScores[source]#
Return each ligand fragment’s interaction with
partner_mask.The connected multi-block pose is scored once. Fragment-fragment entries remain in the block-pair matrix and are not silently assigned to either fragment.
sfxnmust use the same ligand-extended parameter database aspose_stack.- Parameters:
pose_stack – Connected poses with identical fragment block layouts.
partner_mask – Partner blocks shaped
[n_poses, max_n_blocks]. The mask must exclude every ligand fragment block.sfxn – Score function built from the pose’s parameter database.
mapping – Optional split-block mapping. By default the mapping attached to
pose_stackis used. Legacy fragmented-ligand mappings remain accepted for compatibility.sum_terms – Sum the score-term dimension when true.
- Returns:
Fragment scores shaped
[n_terms, n_poses, n_fragments], or[n_poses, n_fragments]whensum_termsis true, plus the pose-zero mapping records that define the fragment columns.- Raises:
TypeError – If
partner_maskis not Boolean.ValueError – If the mask, score function, or mapping is incompatible with the poses.
- tmol.constraint_atoms_for_labels(pose_stack: PoseStack, atoms) Tensor[source]#
The atoms of one constraint, addressed entirely in PDB space.
atomsis a sequence of 1 to 4(pose_ind, chain_id, res_id, atom_id)labels (seeatom_for_residue_label()) – one atom per constraint slot. The slot count matches whicheverConstraintEnergyTermfunction the result is eventually passed to: 1 for a coordinate constraint, 2 for a distance constraint (harmonic/bounded), 4 for a torsion-angle constraint (circularharmonic).Returns an
int32tensor shaped[len(atoms), 3]onpose_stack’s device. Stack the result for each constraint (e.g.torch.stack(...)) to build the[n_constraints, n_atoms, 3]tensorConstraintSet.add_constraints()expects.
- tmol.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.fast_relax(pose_stack: PoseStack, sfxn: ScoreFunction, *, minimizer: RelaxMinimizer | None = None, packer_palette: PackerPalette | None = None, task_operations: Sequence[Callable[[PackerTask], None]] | None = None, num_repeats: int = 2, ramp_constraints: bool | None = None, schedule: Sequence[float | int | dict[str, float]] | None = None, release_between_stages: bool = True, verbose: bool = False) PoseStack[source]#
Relax poses through repeated side-chain packing and minimization.
Each repeat applies the MonomerRelax2019 fa_rep ramp and retains the lowest-scoring conformation independently for every pose in the batch.
- Parameters:
pose_stack – Input poses to relax.
sfxn – Packing and minimization score function. Constraints are active only when its constraint weight is nonzero.
minimizer – The minimization mode and its settings: a
CartesianRelaxMinimizer(atom coordinates) or aKinematicRelaxMinimizer(torsions and jumps along a fold forest), or any callable followingRelaxMinimizer. If it providesrelease_retained_state(), FastRelax calls that hook after extracting each minimized pose so packing does not overlap retained scorer or optimizer storage. Defaults to aCartesianRelaxMinimizerwith every atom free.packer_palette – Residue types available to the packer. Defaults to
PackerPalette().task_operations – In-place task configuration callbacks. By default, restrict to repacking with the scoring database’s Dunbrack, fixed-AA, current and nucleic-acid rotamers, sampling covalent groups jointly.
num_repeats – Number of complete pack-minimize ramps.
ramp_constraints – Ramp an active constraint weight to zero. Defaults to true; the input weight is restored after relaxation.
schedule – Numeric fa_rep fractions or dictionaries with separate pack, minimize, and optional constraint fractions and
min_rtol. Defaults toDEFAULT_RELAX_SCHEDULE.release_between_stages – Drop the rendered scorer, CUDA graph and L-BFGS history after each stage’s minimization. On by default: a large system is bound by that retained state through the next packing phase, which is why the release exists. Turn it off when the setup cost dominates instead – a small pose on the default four-stage schedule otherwise pays four network constructions, and four graph captures, where one would do.
verbose – Print timing information for each step.
- Returns:
Best-scoring relaxed poses across all repeats.
- tmol.file_from_atom_array(atom_array: AtomArray | AtomArrayStack, path: str | Path | None = None, format: Literal['pdb', 'cif'] | None = None) str | Path[source]#
Write an AtomArray as PDB or CIF; return the text when path is None.
A CIF carries the structure’s bonds, so a component that is not a dictionary entry (a MOL2 ligand, a generated residue type) reads back with its chemistry.
- Parameters:
atom_array – Structure to write.
path – Where to write.
format – “pdb” or “cif”. Inferred from path’s extension when None.
- tmol.file_from_pose_stack(pose_stack: PoseStack, path: str | Path | None = None, format: Literal['pdb', 'cif'] | None = None, **kwargs) str | Path[source]#
Write a PoseStack as PDB or CIF; return the text when path is None.
Converts with atom_array_from_pose_stack, which takes the remaining keyword arguments, and writes with file_from_atom_array.
- tmol.get_ligand_mask(pose_stack: PoseStack) Tensor[source]#
Boolean mask shaped
[n_poses, max_n_blocks], true where a block is a ligand (or any other non-polymer residue, such as an ion). Padding blocks are false.
- tmol.get_sequence(pose_stack: PoseStack, pose: int = 0) str[source]#
One-letter sequence of one pose’s real (non-padding) blocks.
Blocks whose three-letter code has no one-letter equivalent (ligands, ions, and other non-canonical residues) appear as
"X".
- tmol.get_torsion_names(pose_stack: PoseStack, pose: int, block: int) List[str][source]#
Names of the torsions defined on a block’s type, in database order.
- tmol.has_cuda() bool[source]#
Whether the TMol backend in use includes CUDA kernels (independent of GPU availability).
In JIT mode (
TMOL_USE_JIT=1, or theTMOL_JIT_FALLBACKfallback) the precompiled library must not be loaded: JIT builds have already registered the same operators, and loading it would register them a second time. JIT compiles CUDA sources exactly whentorch.cuda.is_available(), so that is the answer there.
- tmol.mutate_residue(pose_stack: PoseStack, pose_index: int, block: int, new_identity: str, score_function: ScoreFunction | None = None, *, param_db: ParameterDatabase | None = None, seed: int | None = None) PoseStack[source]#
Change one block’s residue identity via the packer.
Builds a PackerTask restricted to repacking just the target block, with its allowed identities narrowed to
new_identity, and returns a new PoseStack with that block’s type and conformation chosen by the Dunbrack rotamer library. Every other block, and every other pose in the stack, is left untouched. The input PoseStack itself is not modified.- Parameters:
pose_stack – The pose stack to mutate.
pose_index – Which pose in the stack to mutate.
block – Block index to change.
new_identity – Three-letter code of the requested residue type.
score_function – Score function used for packing; defaults to beta2016 on the pose stack’s device.
param_db – Parameter database used to build the Dunbrack sampler; defaults to the score function’s own database.
seed – Packer seed, as for
pack_rotamers().
- Returns:
A new PoseStack with the requested block mutated.
- tmol.mutate_to_sequence(pose_stack: PoseStack, pose_index: int, sequence: str, score_function: ScoreFunction | None = None, *, param_db: ParameterDatabase | None = None, seed: int | None = None) PoseStack[source]#
Mutate every real block of one pose whose identity doesn’t match
sequence.sequenceis a one-letter sequence, as returned byget_sequence(), for the real (non-padding) blocks of one pose, in block order. Positions whose current three-letter code already matches their requested letter are left untouched; every differing position is redesigned to the requested identity in a single packing run.- Parameters:
pose_stack – The pose stack to mutate.
pose_index – Which pose in the stack to mutate.
sequence – One letter per real block of
pose_index, in block order.score_function – Score function used for packing; defaults to beta2016 on the pose stack’s device.
param_db – Parameter database used to build the Dunbrack sampler; defaults to the score function’s own database.
seed – Packer seed, as for
pack_rotamers().
- Returns:
A new PoseStack with every differing position mutated to match.
- tmol.overlay_view(structures: Mapping[str, Any], *, notes: Mapping[str, str] | None = None, colors: Mapping[str, str] | None = None, default: str = 'both', width: int = 720, height: int = 420)[source]#
Compare two or more structures, with the option to overlay them all.
A selector shows any one structure alone (as
view()would render it), or all of them at once in a single shared viewer, each colored distinctly.- Parameters:
structures – Two or more labeled structures, each accepted by
view().notes – Optional mapping of structure labels to short explanatory text, shown under each individual (non-overlay) panel.
colors – Optional mapping of structure labels to a color used for that structure in the overlay panel. Unlisted labels draw from a default categorical palette, cycling if there are more structures than colors in it.
default – Which panel is visible initially:
"both"(the overlay, the default) or one of the structure labels.width – Viewer width in pixels.
height – Viewer height in pixels.
- tmol.pack_rotamers(pose_stack: PoseStack, sfxn: ScoreFunction, task: PackerTask, verbose: bool = False, seed: int | None = None, anneal_device: device | str | None = None, n_anneal_trajectories: int = 128) PoseStack[source]#
Optimize side-chain conformers for a pose stack.
The annealer draws from torch’s generator on the pose device, so
torch.manual_seedcontrols it on the CPU as on CUDA.- Parameters:
pose_stack – Poses whose task-enabled blocks will be packed.
sfxn – Score function used to rank rotamer assignments.
task – Allowed block types, conformers, and packing positions.
verbose – Print synchronized stage timings when true.
seed – Seed for this call only, leaving torch’s global random state unchanged.
anneal_device – Run annealing on this device instead of the pose stack’s. Simulated annealing reads the interaction graph and writes rotamer indices, so it can run anywhere the tables can be put; on Apple silicon the tables cost almost nothing to move (9 ms for 174 MB of unified memory) and the Metal annealer searches both faster and far better than the host one. Left unset, host poses anneal on Metal when it is available, unless
TMOL_MPS_OFFLOAD=0.n_anneal_trajectories – High-temperature annealing trajectories per pose; at least 4. The single-trajectory CPU annealer, used below 8 threads, ignores it.
- Returns:
A new pose stack containing the lowest-ranked assignment per pose.
- tmol.pose_stack_from_atom_array(biotite_structure: AtomArray | AtomArrayStack, torch_device: device, param_db: ParameterDatabase | None = None, missing_density_distance_threshold: float = 2.4, no_optH: bool = False, optH_minimize: bool = False, backprop_compatible_rebuild: bool | 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', packer_seed: int | None = None, 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 an AtomArray or AtomArrayStack.
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_atom_array(struct0, dev, prepare_ligands=True) for struct in structures: pose_stack = pose_stack_from_atom_array(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
contextarg).Missing non-polymer atoms use prepared conformer geometry and resolved coordinate anchors. If only an attachment’s endpoints are resolved, its first declared torsion sample and the next resolved partner atom can orient the missing component. These are starting conformers for scoring/packing, not recovered experimental coordinates. Supplied heavy-atom coordinates stay unchanged; insufficient or degenerate references still raise.
- 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 polymer residues whose connection atoms exceed this distance are disconnected only where topology was inferred. A supplied bond across a gap raises; set to 0 to retain it. Default is 2.4.
no_optH – Residues the input gives no hydrogens take AtomWorks’ protonation state: database residues then get hydrogens built by tmol, other residues those AtomWorks places. When True, preserve finite input hydrogen coordinates and build only missing hydrogens and heavy-atom sidechains. When False (default), residues with complete heavy atoms are packed with OptHSampler to optimize hydrogen positions and NHQ flips, while residues with missing heavy atoms are rebuilt with DunbrackChiSampler. With
atom37_coords, nothing is flipped and input hydrogens keep their coordinates; only missing ones are optimized. Generated ligand hydrogens followligand_hydrogensinstead.optH_minimize – Unless
no_optH, minimize the proton chis in torsion space after packing them, rather than leaving them at the sampled values.backprop_compatible_rebuild – Set when gradients through construction will be used. Hydrogen optimization then rebuilds the atoms it moves differentiably from the input atoms, and a residue missing heavy atoms raises
ValueError, since only the packer can build them and its coordinates carry no gradient. When False, hydrogen optimization and any missing heavy atoms are packed together without gradients. Defaults to True withatom37_coordsand False otherwise.prepare_ligands – If True, detect and prepare non-standard residues (see
build_context_from_atom_arrayfor details).ligand_ph – pH AtomWorks protonates residues lacking hydrogens at (default 7.4).
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.
chem_comp_types –
{comp_id: type}from the input file’s_chem_comptable, 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 – Hydrogens of generated ligand types. “input” takes the input’s names where its hydrogens pair up with the prepared ones parent by parent, and keeps each input hydrogen at bond length from the parent its name gives it. “names” (default) takes the names but rebuilds every coordinate. “rebuild” names them by parent and rebuilds every coordinate.
packer_seed – Seed of the packer that places hydrogens and builds missing side chains; unseeded, it continues torch’s global random state.
return_context – If True, return
(pose_stack, PoseBuildContext).context – Reusable context from
build_context_from_atom_array. It must be ontorch_deviceand is mutually exclusive withparam_dbandprepare_ligands=True.atom37_coords – Optional coordinates shaped
[pose, token, 37, xyz]. When supplied, mapped coordinates are read from this tensor using the input structure’s integertoken_idandatom37_slotannotations. Wholly finite mapped triplets are authoritative; all-NaN mapped triplets are missing and do not fall back to the Biotite coordinates. Unmapped finite Biotite atoms remain context, and absent leaf atoms are completed normally. Partial-NaN or infinite mapped triplets raiseAtom37MappingError. 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 aspose_stack.split_block_mapping.
- tmol.pose_stack_from_file(source: str | Path | IO, device: device, format: Literal['pdb', 'cif', 'mol2', 'sdf'] | None = None, *, model: int = 1, assembly_id: str | None = None, residue_start: int | None = None, residue_end: int | None = None, **kwargs)[source]#
Build a PoseStack from a PDB, CIF, MOL2 or SDF structure.
Reads with atom_array_from_file and builds with pose_stack_from_atom_array, which takes the remaining keyword arguments. residue_start and residue_end select a half-open range of residues.
- tmol.recombine_fragmented_ligands(structure: AtomArray | AtomArrayStack, pose_stack) AtomArray | AtomArrayStack[source]#
Restore original residue identities on exported ligand fragments.
Uses
pose_stack.split_block_mappingto identify which residues in structure are split-block fragments and what their original PDB identity should be. Atoms are matched by the residue label stored in the pose’s PDBInfo (which is whatatom_array_from_pose_stackwrites tores_id).
- tmol.run_cart_min(pose_stack: PoseStack, sfxn: ScoreFunction, coord_mask: Tensor[slice(None, None, None), slice(None, None, None)] | None=None, optimizer_cls: type[Optimizer] = <class 'tmol.optimization._lbfgs_armijo.LBFGS_Armijo'>, optimizer_kwargs: dict[str, object] | None=None, verbose: bool = False, cuda_graph: bool = False) PoseStack[source]#
Run minimization on a PoseStack in Cartesian coordinate space.
Builds a
CartesianSfxnNetworkand delegates to_run_min().- Parameters:
pose_stack – Structures and coordinates to minimize.
sfxn – Score function defining the objective.
coord_mask – Movable atoms shaped
[pose, atom];Nonemoves all.optimizer_cls – Closure-based PyTorch optimizer class.
optimizer_kwargs – Optional optimizer constructor arguments.
verbose – Print synchronized setup and minimization timings.
cuda_graph – Capture the fixed-shape CUDA scoring forward/backward path.
- Returns:
A new pose stack containing the minimized coordinates.
- tmol.run_kin_min(pose_stack: PoseStack, sfxn: ScoreFunction, ff: FoldForest, mm: MoveMap, optimizer_cls: type[Optimizer] = <class 'tmol.optimization._lbfgs_armijo.LBFGS_Armijo'>, optimizer_kwargs: dict[str, object] | None=None, verbose: bool = False, cuda_graph: bool = False, kin_dtype: dtype = torch.float32) PoseStack[source]#
Run minimization on a PoseStack in internal DOF space.
Builds a
KinForestSfxnNetworkand delegates to_run_min().- Parameters:
pose_stack – Structures and coordinates to minimize.
sfxn – Score function defining the objective.
ff – Fold forest defining the kinematic tree.
mm – Internal-coordinate degrees of freedom allowed to move.
optimizer_cls – Closure-based PyTorch optimizer class.
optimizer_kwargs – Optional optimizer constructor arguments.
verbose – Print synchronized setup and minimization timings.
cuda_graph – Capture the fixed-shape CUDA DOF-to-score forward/backward path.
kin_dtype – Floating-point dtype for kinematic degrees of freedom.
- Returns:
A new pose stack containing the minimized coordinates.
- tmol.selection_gallery(atom_array: Any, selections: Mapping[str, object], *, notes: Mapping[str, str] | None = None, width: int = 720, height: int = 420, highlight_color: str = '#e83e8c')[source]#
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.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.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.
modelmay be aPoseStack, a BiotiteAtomArrayorAtomArrayStack, PDB text, or a PDB path.highlightedis 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 realpy3Dmol.viewobject for compatibility with existing notebooks.