Ligands#
Ligand detection, preparation, parameter I/O, and fragmentation are available
from the public tmol.ligand package. tmol.LigandFragmentDefinition
and tmol.recombine_fragmented_ligands() are imported from the top-level
package and documented in Top-level API.
Ligand typing, preparation, fragmentation, and serialization.
- exception tmol.ligand.LigandPreparationError[source]#
Bases:
RuntimeErrorA detected ligand could not be prepared, registered, or retained.
Raised by
prepare_ligands()(and theprepare_ligands=TrueIO paths) whenstrict_ligands=Trueand a non-standard residue is skipped or fails preparation, instead of silently dropping it. Passstrict_ligands=Falseto downgrade these failures to warnings.
- class tmol.ligand.NonStandardResidueInfo(res_name: str, component_type: str, atom_names: tuple[str, ...], elements: tuple[str, ...], coords: ndarray, atom_array: AtomArray, covalently_linked: bool = False, partial_charges: dict[str, float] | None = None, skip_protonation: bool = False, original_single_bonds: frozenset[frozenset[str]] | None = None, source_atom_order: tuple[int, ...] | None = None, connection_atom_names: frozenset[str] | None = None, in_polymer_entity: bool | None = None, chemistry_problem: str | None = None, connection_partners: dict | None = None)[source]#
Bases:
objectDetected non-standard residue requiring preparation.
Any residue not in tmol’s standard database is represented here, regardless of whether it is a true ligand, modified amino acid, or modified nucleotide.
- component_type#
Chemical component type the input file declares, or “UNKNOWN” where it declares none.
- Type:
- in_polymer_entity#
Whether the input file places this residue in a polymer entity (mmCIF label_seq_id).
Nonewhere the source cannot say, as a bare SMILES cannot.- Type:
bool | None
- chemistry_problem#
Why this residue’s chemistry cannot be established, or None. A residue carrying one is refused rather than prepared from atoms that may not be the whole molecule.
- Type:
str | None
- coords#
Cartesian coordinates of shape (n_atoms, 3).
- Type:
- atom_array#
The sub-AtomArray (with bonds if available).
- Type:
biotite.structure.AtomArray
- connection_atom_names#
Names of the atoms bonded to a neighbouring residue, which is where this residue’s polymer connections attach.
Nonewhere the source cannot say, as a bare SMILES cannot.
- partial_charges#
Authoritative
{atom_name: charge}map (OpenBabel MMFF94 charges). Set only on the mol2 / SMILES-via-mol2 reader path, whereprepare_single_ligandconsumes them directly.Nonefor raw CIF/atom-array detections (the unified path re-derives charges from the SMILES).
- skip_protonation#
If True, Dimorphite-DL protonation is skipped and explicit hydrogens from the input (mol2) are preserved. Paired with
partial_chargeson the mol2 / SMILES-via-mol2 path.- Type:
- original_single_bonds#
Optional set of
frozenset({name_a, name_b})pairs that the source mol2 records as literal single (order'1') bonds, keyed by disambiguated atom name._build_chi_topologyuses these to honor the mol2 bond order (Rosetta-faithful) instead of RDKit’s post-kekulization order. Only set on the mol2 / SMILES-via- mol2 paths;Noneelsewhere.
- tmol.ligand.inject_params_file(param_db: ParameterDatabase, path: str | Path, *, strict_atom_types: bool = False) ParameterDatabase[source]#
Load a single
.tmolfile and inject it into a ParameterDatabase.
- tmol.ligand.inject_params_files(param_db: ParameterDatabase, paths: list[str | Path], *, strict_atom_types: bool = False) ParameterDatabase[source]#
Load multiple
.tmolfiles and inject them in one shot.
- tmol.ligand.ligand_smiles_from_atom_array(atom_array: AtomArray, *, res_name: str | None = None, with_atom_map: bool = False, keep_hydrogens: bool = False) str[source]#
Derive a canonical SMILES for a ligand AtomArray from its bond table.
The SMILES is derived purely from the input atoms and their explicit bonds (never a residue-code / CCD-template lookup, never geometry-based bond perception). Geometry-based bond-order corrections are still applied for motifs the input encodes inconsistently (carboxylates).
- Parameters:
atom_array – The ligand sub-array (heavy + optional hydrogen atoms).
res_name – Residue code, used only for log/error messages.
with_atom_map – Tag heavy atoms with source-index map numbers for CIF atom naming downstream.
keep_hydrogens – Preserve the supplied hydrogen counts, including zero, when the input already has its intended protonation state.
- Returns:
A canonical SMILES string.
- Raises:
ValueError – If the AtomArray carries no bond table (bond orders must be supplied by the input; a bonds-absent ligand such as a plain PDB cannot be prepared without guessing chemistry), or if no SMILES could be derived from the bonds present.
- tmol.ligand.load_params_file(path: str | Path) list[LigandPreparation][source]#
Load a tmol params YAML file as a list of
LigandPreparation.The returned list is the same abstraction the AtomArray pipeline produces (see
tmol.ligand.prepare_single_ligand()), so the caller can pass it directly totmol.ligand._registry._inject_ligand_preparationsregardless of which input form (file or AtomArray) it came from.The
.tmolschema is the nestedchemical:/elec:/cartbonded:shape — files using the legacy flat schema (top-levelresidues:etc.) raise aValueErrorpointing at the migration.
- tmol.ligand.nonstandard_residue_info_from_mol2(mol2_path: str | Path, res_name: str | None = None) NonStandardResidueInfo[source]#
Construct
NonStandardResidueInfofrom a ligand Mol2 file.Low-level reader retained for the DUD-80 SMILES->params parity harness (it reads both the OpenBabel-generated and Rosetta ground-truth mol2 files). Preserves Tripos aromatic flags, atom-type subtypes, and per-atom partial charges, avoiding lossy rdkit<->biotite round-trips.
- tmol.ligand.nonstandard_residue_info_from_smiles_via_mol2(smiles: str, res_name: str | None = None, *, ph: float = 7.4, protonate: bool = True, seed: int | None = None) NonStandardResidueInfo[source]#
Construct
NonStandardResidueInfofrom a SMILES via the mol2 route.Implements the canonical ligand-prep protocol end to end:
normalize bare radical oxygens (
[O]->[O-]) so source carboxylate/sulfonate notation has a well-defined charge,optionally pKa-protonate the SMILES with Dimorphite-DL (
protonate),generate a 3D mol2 with MMFF94 partial charges via OpenBabel (kept in memory as a string — no temp file), then
read that mol2 with
_nonstandard_residue_info_from_mol2_block().
This never builds a biotite atom-array from an RDKit embedding and never recomputes MMFF on a reconstructed graph — the OpenBabel MMFF94 charges flow through untouched (
skip_protonation/ authoritative charges are set by the mol2 reader), so fused-ring aromatics keep correct charges.- Parameters:
smiles – Ligand SMILES string.
res_name – Residue name (default inferred /
"L_1").ph – Target pH for the Dimorphite protonation step.
protonate – When
True(default) run Dimorphite onsmilesfirst; setFalseto pin an already-protonated SMILES verbatim.seed – Fixed RNG seed for reproducible 3D coordinates;
Noneis random.
- Raises:
OpenBabelUnavailableError – If the
openbabelpackage is missing (this path requires it for the SMILES -> mol2 conversion).ValueError – If OpenBabel cannot build a charged mol2 for
smiles.
- tmol.ligand.prepare_ligand_from_cif(cif_path: str, *, param_db: ParameterDatabase | None = None, ph: float = 7.4, seed: int | None = None, strict_atom_types: bool = False, res_name: str | None = None) tuple[ParameterDatabase, CanonicalOrdering][source]#
Prepare a single ligand from a CIF file and inject it into a database.
Runs the same full pipeline as
prepare_ligand_from_smiles(); the only CIF-specific step is the front end. A SMILES is derived from the CIF ligand’s bond table (supplemented from the CCD, never geometry perception) and run through the SMILES -> mol2 -> params path (protonation, 3D conformer, MMFF94 charges). The prepared residue’s heavy-atom names are then mapped back to the CIF atom names via the atom-order map carried through the round-trip.- Parameters:
cif_path – One ligand residue in a text, compressed or binary CIF file; the first model is selected. Use
prepare_ligands()for arrays containing multiple residues.param_db – Base database (not modified); defaults to the tmol default.
ph – Target pH for protonation.
seed – Reproducible conformer seed, shared with the MOL2/SMILES entry paths.
strict_atom_types – Fail on unknown atom-type element mappings.
res_name – Optional residue name override.
- Returns:
A
(ParameterDatabase, CanonicalOrdering)with the ligand injected.
- tmol.ligand.prepare_ligand_from_mol2(mol2_path: str, *, param_db: ParameterDatabase | None = None, ph: float = 7.4, mode: str = 'auto', seed: int | None = None, strict_atom_types: bool = False, res_name: str | None = None) tuple[ParameterDatabase, CanonicalOrdering][source]#
Prepare a single ligand from a Tripos mol2 file and inject it.
By default, preserve complete molecules with supported partial charges; otherwise run shared protonation and charge generation. Use
regenerateto apply the requested pH even to a neutralized, fully hydrogenated input.- Parameters:
mol2_path – Path to the ligand MOL2 or SDF file.
param_db – Base database (not modified); defaults to the tmol default.
ph – Target pH for protonation.
mode –
"keep"requires prepared input and retains its protonation and charges;"auto"(default) regenerates only unprepared input;"regenerate"always runs pH-dependent preparation. Complete hydrogens and supported charges do not establish the intended pH.seed – Reproducible conformer seed when charges must be generated.
strict_atom_types – Fail on unknown atom-type element mappings.
res_name – Optional residue name override.
- Returns:
A
(ParameterDatabase, CanonicalOrdering)with the ligand injected.
- tmol.ligand.prepare_ligand_from_smiles(smiles: str, *, param_db: ParameterDatabase | None = None, ph: float = 7.4, strict_atom_types: bool = False, res_name: str | None = None, protonate: bool = True, seed: int | None = None) tuple[ParameterDatabase, CanonicalOrdering][source]#
Prepare a single ligand from a SMILES string and inject it into a database.
Follows the canonical ligand-prep protocol: Dimorphite-DL pKa-protonates the SMILES at
ph, OpenBabel generates a 3D mol2 with MMFF94 partial charges, and that mol2 is read verbatim (atom names, coordinates, charges, and bond orders preserved). The MMFF94 charges flow through untouched — there is no biotite atom-array round-trip or MMFF recompute.- Parameters:
protonate – When
True(default) Dimorphite protonatessmilesfirst; setFalseto pin an already-protonated SMILES verbatim.seed – Fixed RNG seed for reproducible 3D coordinates;
Noneis random.
- tmol.ligand.prepare_ligands(atom_array: AtomArray, param_db: ParameterDatabase | None = None, ph: float = 7.4, strict_atom_types: bool = False, params_files: list[str] | None = None, params_output: str | None = None, strict_ligands: bool = True, return_fragment_definitions: bool = False, return_cut_partners: bool = False, chem_comp_types: dict[str, str] | None = None, seed: int | None = None, coordinating_atoms: dict[str, frozenset[str]] | None = None, input_hydrogen_names: bool = True) tuple[source]#
Detect, prepare, and register all non-standard residues.
Scans the input AtomArray for residues not in the ParameterDatabase, runs each through the unified SMILES→OpenBabel mol2→typing→residue-build pipeline, and returns a new ParameterDatabase with the ligand data injected. Ligand/glycan attachment chemistry uses the connected capped model for local typing, bonded terms and atom construction, preserving prepared residue charges. Lengths and angles use the same Cartesian constants as ordinary ligand parameters. Supplied explicit connection records take precedence and preserve both endpoint residue types.
- Parameters:
atom_array – A biotite AtomArray from a CIF or PDB file.
param_db – The base ParameterDatabase (not modified). If None, the default database is used.
ph – pH AtomWorks protonates residues without hydrogens at; each ligand keeps the protonation state its hydrogens give it.
strict_atom_types – If True, fail when unknown atom-type element mappings are encountered during registration.
params_files – Optional list of tmol YAML params file paths to inject before detection. Residues defined in these files skip residue generation. Missing attachment records are generated; existing records are reused without regeneration.
params_output – Optional path to write all prepared ligand data to a tmol YAML params file for later reuse.
strict_ligands – If True (default), raise
LigandPreparationErrorwhen a detected non-standard residue is skipped (metal-containing or covalently linked) or fails preparation, instead of silently dropping it. If False, such residues are logged as warnings and skipped, leaving them to be filtered out during pose construction.return_cut_partners – Internal option. If True, append the residue names whose covalent bonds were cut. A ligand skipped under
strict_ligands=Falseloses its bonds here, and a caller that goes on to build a pose must know that, or it will reject the dangling partner it was told to drop.return_fragment_definitions – Internal/context-building option. If True, include definitions derived from
tmol_fragment_idannotations as the third return value.chem_comp_types –
{comp_id: type}read from the input file’s_chem_comptable (seetmol.ligand._detect._chem_comp_types_from_cif), consulted where the file does not number the residue along a polymer sequence. A polymer-linking type routes the residue to_prepare_polymer_residue()instead of the free-molecule ligand path.seed – Fixed RNG seed for the 3D conformer each residue is built from.
Noneis random, which makes the prepared residue types differ between runs.coordinating_atoms – {residue name: atoms bonded to a metal}, which a residue’s charges cannot account for. Each hydrogen state the copies of a ligand present gets a type (see
_state_variants).input_hydrogen_names – Name a ligand’s hydrogens after the input’s where they pair up parent by parent; otherwise name them by parent.
- Returns:
A (ParameterDatabase, CanonicalOrdering) tuple. When
return_fragment_definitionsis true, a third element containing the structure-independent ligand fragment definitions is returned. The returned ParameterDatabase is a new instance with all detected ligands injected; the inputparam_dbis not modified.- Raises:
LigandPreparationError – If
strict_ligandsand any detected ligand cannot be prepared and registered.
- tmol.ligand.prepare_single_ligand(ligand_info: NonStandardResidueInfo, name_source: NonStandardResidueInfo | None = None, assign_ring_chis: bool = False, generate_heavy_chi_samples: bool = False, input_hydrogen_names: bool = True) LigandPreparation[source]#
Build a
LigandPreparationfrom a SMILES-derived ligand.This is the final, naming-and-typing step of the unified pipeline. Its input must already be fully resolved chemistry: explicit hydrogens at the desired protonation state and authoritative per-atom partial charges (the OpenBabel MMFF94 charges produced by the SMILES -> mol2 step). Protonation and charge generation are not done here – they happen upstream in
tmol.ligand.nonstandard_residue_info_from_smiles_via_mol2.Charges are mapped onto atoms by stable RDKit index (source atom order), so they are independent of the atom renaming below and never recomputed.
Returns a
LigandPreparation– the same structtmol.ligand.load_params_file()produces for each residue defined in a.tmolfile, so the AtomArray-driven path and the params-file path converge on a single abstraction that_inject_ligand_preparations()consumes.- Parameters:
ligand_info – A SMILES-derived ligand (
skip_protonation=Truewith authoritativepartial_charges). Raw CIF/atom-array ligands must be routed throughprepare_ligands()/prepare_ligand_from_cif().name_source – Optional ligand whose atom names the prepared residue should adopt (mapped to the prepared heavy atoms via the atom-order map). On the unified CIF path this is the original CIF ligand. Defaults to
ligand_info.input_hydrogen_names – Name hydrogens after name_source’s where they pair up parent by parent; otherwise name them by parent.
- Raises:
ValueError – If
ligand_infolacks explicit hydrogens / authoritative charges (there is no charge-generation fallback).
- tmol.ligand.smiles_from_block_type(block_type, chem_db, *, hydrogens: bool = False, atom_map: bool = False) str[source]#
Canonical SMILES of a residue type, with stereochemistry from its ideal geometry and a [*] for each connection that is not a metal site.
- Parameters:
block_type – A RefinedResidueType (patched types describe patched chemistry).
chem_db – The chemical database the type was built from (element lookup).
hydrogens – Keep explicit hydrogens in the SMILES.
atom_map – Number each atom by its block-type atom index + 1 (hydrogens only when kept).
- tmol.ligand.smiles_from_pose_stack(pose_stack, pose_ind: int, block_ind: int, *, hydrogens: bool = False, atom_map: bool = False) str[source]#
Canonical SMILES of one residue of a PoseStack, with stereochemistry from its coordinates and a [*] for each connection that is not a metal bond.
- Parameters:
pose_stack – The PoseStack.
pose_ind – Pose index.
block_ind – Residue (block) index within the pose; must be a real block.
hydrogens – Keep explicit hydrogens in the SMILES.
atom_map – Number each atom by its block-type atom index + 1 (hydrogens only when kept).
- tmol.ligand.write_params_file(preparation: LigandPreparation | list[LigandPreparation], path: str | Path) None[source]#
Write a ligand
LigandPreparationas a tmol.tmolfile.- Parameters:
preparation – A
LigandPreparation(itsresidue_type/partial_charges/cartbonded_paramsare used), or a list of them.path – Output file, holding every supplied residue.
- tmol.ligand.write_params_from_mol2(mol2_path: str | Path, out_path: str | Path, *, res_name: str | None = None, ph: float = 7.4, mode: str = 'auto', seed: int | None = None) None[source]#
Build params from a mol2 file and write a tmol
.tmolfile.- Parameters:
mol2_path – Input Tripos MOL2 or MDL SDF; see
prepare_ligand_from_mol2().out_path – Output file path (see
write_params_file()).res_name – Optional residue name override.
ph – Target pH for protonation.
mode –
"keep","auto"(default), or"regenerate", as inprepare_ligand_from_mol2().seed – Reproducible conformer seed when charges must be generated.