Scoring#

Use tmol.score.beta2016_score_function() for the standard configured score function, or construct tmol.score.ScoreFunction and set individual tmol.score.ScoreType weights.

Score functions, energy terms, and standard weight sets.

class tmol.score.AcceptorHybridization(*values)[source]#

Bases: IntEnum

Hydrogen-bond acceptor hybridization categories.

class tmol.score.AtomTypeParamResolver(index: Index, params: AtomTypeParams, device: device)[source]#

Bases: ValidateAttrs

Container for global/type/pair parameters, indexed by atom type name.

Param resolver stores pair parameters for a collection of atom types, using a pandas Index to map from string atom type to a resolver-specific integer type index.

classmethod from_database(chemical_database: ChemicalDatabase, device: device)[source]#

Initialize param resolver for all atom types in database.

type_idx(atom_types: NDArray) Tensor[source]#

Convert array of atom type names to parameter indices.

pandas.Index.get_indexer only operates on 1-d input arrays. Coerces higher-dimensional arrays, as may be produced via broadcasting, into lower-dimensional views to resolver parameter indices.

class tmol.score.AtomTypeParams(is_acceptor: Tensor, acceptor_hybridization: Tensor, is_donor: Tensor, is_hydrogen: Tensor, is_hydroxyl: Tensor, is_polarh: Tensor)[source]#

Bases: TensorGroup, ValidateAttrs

Packed donor, acceptor, hydrogen, and hybridization atom-type flags.

class tmol.score.BlockPairScoringModule(weights: Tensor, term_modules: Sequence[Module])[source]#

Bases: object

Rendered energy modules that retain per-block-pair scores.

score_interactions(coords: Tensor, block_pair_indices: Tensor, *, sum_terms: bool = True, apply_weights: bool = True) Tensor[source]#

Sum selected block-pair entries with one indexed reduction.

Parameters:
  • coords – Pose coordinates accepted by this rendered scorer.

  • block_pair_indices – Shared block pairs shaped [n_pairs, 2]. Each row contains (block_i, block_j) and is applied to every pose in the coordinate batch.

  • sum_terms – Sum the score-type dimension when true.

  • apply_weights – Apply the score function’s weights when true.

Returns:

Scores shaped [n_poses] when sum_terms is true, otherwise [n_score_types, n_poses].

class tmol.score.FragmentInteractionScores(scores: Tensor, mapping: tuple[SplitBlockEntry | _LegacyFragmentRecord, ...])[source]#

Bases: object

Per-fragment interactions with an explicitly selected partner.

class tmol.score.IndexedBonds(bonds: Tensor[slice(None, None, None), slice(None, None, None), 2], bond_spans: Tensor[slice(None, None, None), slice(None, None, None), 2])[source]#

Bases: object

Sorted atom bonds with per-atom spans for efficient neighborhood lookup.

classmethod to_directed(src_bonds)[source]#

Convert a potentially-undirected bond-table into dense, directed bonds. The input “bonds” tensor is a two dimensional array of nbonds x 3, where the 2nd dimension holds [stack index, atom 1 index, atom 2 index].

Eg. Converts [[0, 0, 1], [0, 0, 2]] into [[0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 2, 0]]

class tmol.score.RotamerScoringModule(weights: Tensor, term_modules: Sequence[Module])[source]#

Bases: object

Rendered energy modules that build sparse rotamer-pair energy tables.

Large identical index layouts are combined before sparse coalescing to avoid retaining and sorting redundant block-pair indices.

class tmol.score.ScoreFunction(param_db: ParameterDatabase, device: device)[source]#

Bases: object

Weighted 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.

all_score_types() list[ScoreType][source]#

Return score types in the same order as all_terms().

all_terms()[source]#

Grant read access to the list of terms.

Do not modify this list directly

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 weights dict mapping score type names (as in ScoreType) 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.

get_weight(st: ScoreType) Tensor[source]#

Return the scalar weight for st on the score-function device.

multi_body_terms()[source]#

Return the active multi-body energy terms in score-type order.

one_body_terms()[source]#

Return the active one-body energy terms in score-type order.

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.

Parameters:

pose_stack – Poses whose topology will be scored.

remove_term_for_score_type(st: ScoreType)[source]#

Remove the term containing st once all its weights are zero.

render_block_pair_scoring_module(pose_stack: PoseStack, *, interaction_only: bool = False)[source]#

Create an object designed to evaluate the score of a set of Poses repeatedly as the Poses change their conformation, e.g., as in minimization. This object will derive from torch.nn.Module and it will contain a set of objects rendered by the ScoreFunction’s terms that themselves are derived from torch.nn.Module. This object’s __call__ will return a tensor of weighted energies of shape (n_poses, max_n_blocks, max_n_blocks).

Set interaction_only=True when 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 an uncoalesced sparse COO tensor shaped [n_poses, n_rotamers, n_rotamers]. Call coalesce() before reading its indices or values.

render_whole_pose_scoring_module(pose_stack: PoseStack, cuda_graph=False)[source]#

Create an object designed to evaluate the score of a set of Poses repeatedly as the Poses change their conformation, e.g., as in minimization. This object will derive from torch.nn.Module and it will contain a set of objects rendered by the ScoreFunction’s terms that themselves are derived from torch.nn.Module. This object’s __call__ will return a tensor of weighted energies of shape (n_poses,).

Set cuda_graph to "forward" for repeated inference, "forward_backward" for repeated scoring with coordinate gradients, or True to 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.

score_type_covered_by_contained_term(st: ScoreType) bool[source]#

Return whether a constructed energy term implements st.

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.

set_weight(st: ScoreType, weight: float) None[source]#

Set the weight for one score type.

The energy term that implements st is created lazily when the requested weight is nonzero.

Parameters:
  • st – Score type to update.

  • weight – New scalar weight.

two_body_terms()[source]#

Return the active two-body energy terms in score-type order.

weights_tensor() Tensor[source]#

Return weights aligned with the rendered term/subterm order.

class tmol.score.ScoreType(*values)[source]#

Bases: AutoNumber

Stable indices for energy terms in score-function weight tensors.

class tmol.score.WholePoseScoringModule(weights: Tensor, term_modules: Sequence[Module])[source]#

Bases: object

Rendered energy modules that score complete poses.

enable_cuda_graphs(example_coords, mode='both')[source]#

Capture the default weighted score for a fixed coordinate shape.

The returned scorer accepts new coordinate values with the same shape, dtype, and device and retains forward and backward support. Calls that request unweighted or unsummed terms continue to use the eager path. Forward-only replay reuses its output buffer.

mode may be "forward", "forward_backward", or "both". Capture has a one-time cost and retains static buffers, so select only the paths that will be reused. Calling this method again is a no-op for paths that are already captured.

tmol.score.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.score.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. sfxn must use the same ligand-extended parameter database as pose_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_stack is 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] when sum_terms is true, plus the pose-zero mapping records that define the fragment columns.

Raises:
  • TypeError – If partner_mask is not Boolean.

  • ValueError – If the mask, score function, or mapping is incompatible with the poses.

SFXN_FORMAT_VERSION

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