vibe-sketcherDocumentation
Source code for vibesketcher.document.polymer_packing
"""Amorphous polymer boxes and membranes grown from stated repeat units (#205).
A packing request names the repeat units (a SMILES with two connection
markers, a polymer template from the library or a bracketed repeat unit drawn
in the document), the chains to build from them (homopolymer, explicit
sequence or a composition with an arrangement, chain lengths, tacticity and
end groups), the cell (a periodic box, or a membrane periodic in plane with a
nonperiodic normal and vacuum), a target density or explicit lengths, the
torsion states, a radius table, a collision scale, attempt limits and the
seed. The preview returns a *derived* periodic model under a new ID with each
chain's sequence, its parent repeat-unit map and the connection markers it
consumed, the checks below and refusals with stable codes. Nothing is stored
until the model is applied, and an applied packing can be undone while the
model is unchanged (the contract of :mod:`vibesketcher.document.guest_loading`).
The drawing templates and sequence notation are not changed. A template or
drawn bracket is only read for its structural repeat unit (SRU): the atoms in
the bracket, with a connection marker on each of the two bonds crossing it.
Method. Each chain is grown unit by unit as a self-avoiding walk in the cell,
the chain-growth construction of amorphous polymer cells by D. N. Theodorou and
U. W. Suter (*Macromolecules* 18, 1467-1478 (1985), doi:10.1021/ma00149a018).
The repeat unit is embedded once with RDKit (ETKDGv3 and MMFF94 under a fixed
seed, the embedding of the framework builder) with hydrogen stand-ins on its
connection markers; the stand-in directions are the bond directions. A new
unit is placed so that its head atom sits on the previous tail's bond
direction at the covalent bond length and its own head direction points back,
which leaves the torsion about the new bond free. That torsion, and each
rotatable single backbone bond inside the unit, takes one of the stated
rotational-isomeric states (P. J. Flory, *Statistical Mechanics of Chain
Molecules*, 1969; default trans 180 deg with weight 1 and gauche +-60 deg with
weight 0.5, of the order of polyethylene's first-order weight, A. Abe, R. L.
Jernigan and P. J. Flory, *J. Am. Chem. Soc.* 88, 631-639 (1966),
doi:10.1021/ja00956a001), plus a uniform offset of at most
``torsion_jitter_deg``. Conjugated bonds inside a unit keep the embedded
torsion, a conjugated junction tries twelve evenly spaced torsions with equal
weight, and side-group rotors (methyls, ester alkyls) turn uniformly. Every
junction state is tried; a state is free when no atom of the new unit comes
closer than ``collision_scale (r_i + r_j)`` to an atom of another chain, of
its own chain more than three bonds away, or of a periodic image, and stays
inside the growth region and outside the excluded regions. A free state is
chosen with probability proportional to its weight, the selection of
Rosenbluth growth (M. N. Rosenbluth and A. W. Rosenbluth, *J. Chem. Phys.* 23,
356-359 (1955), doi:10.1063/1.1741967). Long-range interactions are a hard
core here, not the energies Theodorou and Suter minimise afterwards; nothing
is relaxed. A step with no free state is retried with fresh internal
torsions, then the previous placement is undone and redrawn (backtracking),
and past ``max_backtracks`` the chain is regrown from a new start, within the
stated limits. Crowded backbones (quaternary carbons, as in PMMA or
polyisobutylene) open their bond angles on relaxation and may need a smaller
collision scale here. Neighbour lookup is a linked-cell grid (Allen and
Tildesley, *Computer Simulation of Liquids*, 2nd ed., 2017, 5.3).
Tacticity is a configuration, not a torsion: an isotactic chain repeats one
embedded enantiomer of a unit with a backbone stereocentre, a syndiotactic
chain alternates it with its mirror image, and an atactic chain draws each
from the seed. The placed chain is checked from its coordinates: the sign of
each backbone stereocentre's (head-side, tail-side, side group) volume gives
meso and racemo diads.
Every chain keeps its own bond graph and is stored wrapped site by site with
bond images; no bond joins two chains (crosslinking needs explicit chemistry
and conversion and is refused, never inferred from contacts). The checks are
one connected component per chain and no bond between chains, valence by
RDKit sanitisation of each chain, every bond's image length against covalent
radii, and the element count against the stated units and end groups. A
packed cell at the target density is an unrelaxed starting geometry, not an
equilibrated morphology.
Fixed inclusions (#241). :func:`preview` also takes an :class:`Inclusion`: a
cell and growth region stated by the caller, fixed atoms (such as a nanotube
bundle) entered in the collision grid before the first chain, and a test for
forbidden interiors (such as the inside of a tube). A placement that overlaps an
inclusion atom is rejected as ``inclusion_contact`` and one with an atom in a
forbidden interior as ``inclusion_interior``; the inclusion atoms themselves are
not part of the derived model, which the caller combines with them.
"""
from __future__ import annotations
import hashlib
import json
import math
from collections import Counter
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, Literal, Self
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, field_validator, model_validator
from vibesketcher.document import crystal
from vibesketcher.document import periodic_graph as pg
from vibesketcher.document.guest_loading import radius_of
from vibesketcher.document.model import Document, PeriodicStructure
from vibesketcher.elements import ATOMIC_NUMBER
from vibesketcher.limits import MAX_ATOMS
NOTE = (
"A packed polymer cell is an unrelaxed starting geometry at the stated density: it is not an "
"equilibrated morphology, and its density, chain dimensions and contacts are not "
"predictions until the model is relaxed and equilibrated by an admitted engine."
)
METHOD = "unit-by-unit self-avoiding chain growth with rotational-isomeric torsion states"
REFERENCES = [
"D. N. Theodorou and U. W. Suter, Macromolecules 18, 1467 (1985), doi:10.1021/ma00149a018",
"M. N. Rosenbluth and A. W. Rosenbluth, J. Chem. Phys. 23, 356 (1955), doi:10.1063/1.1741967",
"P. J. Flory, Statistical Mechanics of Chain Molecules (1969)",
"A. Abe, R. L. Jernigan and P. J. Flory, J. Am. Chem. Soc. 88, 631 (1966), "
"doi:10.1021/ja00956a001",
"M. P. Allen and D. J. Tildesley, Computer Simulation of Liquids, 2nd ed. (2017), 5.3",
]
#: Chains one request may ask for, and repeat units one chain may have.
MAX_CHAINS = 500
MAX_LENGTH = 2000
#: Candidate placements (one per torsion state tried) one request may make.
MAX_ATTEMPTS = 5_000_000
#: Real atoms one repeat unit or end group may have (hydrogens included).
MAX_UNIT_ATOMS = 300
#: Bond images are checked against covalent radii within these factors.
BOND_LENGTH_WINDOW = (0.75, 1.3)
CODES: dict[str, str] = {
"polymer.unit_unreadable": "a repeat unit or end group cannot be read",
"polymer.unit_markers": "a repeat unit needs exactly two connection points, an end group one",
"polymer.unit_ambiguous": "the template or drawing has more than one repeat unit",
"polymer.unit_unknown": "a chain names a repeat unit that is not defined",
"polymer.charged": "charged repeat units or end groups need counter-ions (not supported)",
"polymer.open_shell": "repeat units or end groups with radicals leave the spin state unstated",
"polymer.tacticity_unstated": "the repeat unit has a backbone stereocentre; state tacticity",
"polymer.tacticity_inapplicable": "tacticity is stated but no unit has a backbone stereocentre",
"polymer.box_too_small": "a periodic length is shorter than twice the collision cutoff",
"polymer.too_many_sites": "the packed model would exceed the site limit",
"polymer.crosslinking_unavailable": "crosslinking chemistry is not implemented",
"polymer.budget_exhausted": "the attempt or regrowth limit ran out before every chain grew",
"polymer.partial_packing": "fewer chains were packed than requested (partial result)",
"polymer.check_failed": "a topology, valence, bond-length or stoichiometry check failed",
"polymer.side_chain_stereo": "a side-chain stereocentre keeps its embedded configuration",
"polymer.unrelaxed": "the model is unrelaxed and not an equilibrated morphology",
}
class _Model(BaseModel):
model_config = ConfigDict(extra="forbid")
def _identifier(value: str) -> str:
if not (
1 <= len(value) <= 64
and value[0].isascii()
and value[0].isalpha()
and all(c.isascii() and (c.isalnum() or c in "_-") for c in value)
):
raise ValueError("IDs start with a letter and use letters, digits, _ and - (64 at most)")
return value
[docs]
class RepeatUnit(_Model):
"""One structural repeat unit with a head and a tail connection point.
``smiles`` marks the two points with ``*`` (``[*:1]`` head and ``[*:2]``
tail, or the first and second marker in SMILES order); ``template`` is a
polymer entry of the template library and ``generic`` a bracketed generic
of the document, each read for the atoms of its one SRU bracket.
"""
smiles: str | None = Field(default=None, min_length=1, max_length=4000)
template: str | None = Field(default=None, min_length=1, max_length=200)
generic: str | None = Field(default=None, min_length=1, max_length=64)
@model_validator(mode="after")
def _one_source(self) -> Self:
if sum(x is not None for x in (self.smiles, self.template, self.generic)) != 1:
raise ValueError("give exactly one of smiles, template or generic for a repeat unit")
return self
[docs]
class ChainSpec(_Model):
"""A group of chains built the same way."""
label: str | None = Field(default=None, max_length=80)
count: int = Field(default=1, ge=1, le=MAX_CHAINS)
#: Repeat units per chain, or one length per chain in ``lengths``.
length: int | None = Field(default=None, ge=1, le=MAX_LENGTH)
lengths: list[int] | None = Field(default=None, min_length=1, max_length=MAX_CHAINS)
#: Exactly one of: a homopolymer unit, an explicit sequence or a composition.
unit: str | None = None
sequence: list[str] | None = Field(default=None, min_length=1, max_length=MAX_LENGTH)
composition: dict[str, float] | None = Field(default=None, min_length=1, max_length=10)
arrangement: Literal["random", "alternating", "block"] = "random"
tacticity: Literal["isotactic", "syndiotactic", "atactic"] | None = None
#: End groups: ``H`` or a SMILES with one ``*`` marker, such as ``*C`` for methyl.
head: str = Field(default="H", min_length=1, max_length=2000)
tail: str = Field(default="H", min_length=1, max_length=2000)
@model_validator(mode="after")
def _shape(self) -> Self:
given = [x is not None for x in (self.unit, self.sequence, self.composition)]
if sum(given) != 1:
raise ValueError("give exactly one of unit, sequence or composition for a chain")
if self.sequence is not None:
if self.length is not None or self.lengths is not None:
raise ValueError("a sequence sets the length; give no length or lengths")
elif (self.length is None) == (self.lengths is None):
raise ValueError("give exactly one of length or lengths")
if self.lengths is not None:
if len(self.lengths) != self.count:
raise ValueError("lengths takes one length per chain (count entries)")
if any(not 1 <= n <= MAX_LENGTH for n in self.lengths):
raise ValueError(f"chain lengths must be between 1 and {MAX_LENGTH}")
if self.composition is not None:
if any(not (math.isfinite(v) and v > 0) for v in self.composition.values()):
raise ValueError("composition fractions must be positive")
if self.arrangement == "alternating" and len(set(self.composition.values())) != 1:
raise ValueError("an alternating composition takes equal fractions")
return self
[docs]
def chain_lengths(self) -> list[int]:
if self.sequence is not None:
return [len(self.sequence)] * self.count
if self.lengths is not None:
return list(self.lengths)
assert self.length is not None
return [self.length] * self.count
[docs]
def units_named(self) -> set[str]:
if self.unit is not None:
return {self.unit}
if self.sequence is not None:
return set(self.sequence)
assert self.composition is not None
return set(self.composition)
[docs]
class Cell(_Model):
"""A periodic orthorhombic box, or a membrane periodic in a and b with vacuum along c."""
kind: Literal["box", "membrane"] = "box"
#: Box: the three edge lengths (angstrom); or a density sets a cube.
lengths_angstrom: tuple[float, float, float] | None = None
density_g_cm3: float | None = Field(default=None, gt=0, le=5, allow_inf_nan=False)
#: Membrane: in-plane edges a and b, and the polymer layer thickness or a density.
lateral_angstrom: tuple[float, float] | None = None
thickness_angstrom: float | None = Field(default=None, gt=0, le=1000, allow_inf_nan=False)
#: Membrane: the vacuum on each side of the layer (angstrom).
vacuum_angstrom: float = Field(default=10.0, ge=0, le=500, allow_inf_nan=False)
@model_validator(mode="after")
def _sizes(self) -> Self:
def check(values: tuple[float, ...]) -> None:
if any(not (math.isfinite(v) and 1 <= v <= 1000) for v in values):
raise ValueError("cell edges must be between 1 and 1000 angstrom")
if self.kind == "box":
if self.lateral_angstrom is not None or self.thickness_angstrom is not None:
raise ValueError("lateral_angstrom and thickness_angstrom belong to a membrane")
if (self.lengths_angstrom is None) == (self.density_g_cm3 is None):
raise ValueError("a box takes exactly one of lengths_angstrom or density_g_cm3")
if self.lengths_angstrom is not None:
check(self.lengths_angstrom)
else:
if self.lengths_angstrom is not None:
raise ValueError("a membrane takes lateral_angstrom, not lengths_angstrom")
if self.lateral_angstrom is None:
raise ValueError("a membrane needs lateral_angstrom (a, b)")
check(self.lateral_angstrom)
if (self.thickness_angstrom is None) == (self.density_g_cm3 is None):
raise ValueError("a membrane takes exactly one of thickness or density_g_cm3")
return self
[docs]
class TorsionState(_Model):
angle_deg: float = Field(ge=-180, le=180, allow_inf_nan=False)
weight: float = Field(gt=0, le=1000, allow_inf_nan=False)
[docs]
class Region(_Model):
"""A fractional box no atom may enter (an exclusion rule), such as a pore kept open."""
lower: tuple[float, float, float]
upper: tuple[float, float, float]
@model_validator(mode="after")
def _corners(self) -> Self:
if not all(0 <= lo < hi <= 1 for lo, hi in zip(self.lower, self.upper, strict=True)):
raise ValueError("excluded corners need 0 <= lower < upper <= 1 on every axis")
return self
[docs]
class Crosslinking(_Model):
"""Explicit crosslinking chemistry and conversion (not implemented: refused)."""
chemistry: str = Field(min_length=1, max_length=200)
conversion: float = Field(gt=0, le=1, allow_inf_nan=False)
_DEFAULT_STATES = [
TorsionState(angle_deg=180.0, weight=1.0),
TorsionState(angle_deg=60.0, weight=0.5),
TorsionState(angle_deg=-60.0, weight=0.5),
]
[docs]
class PolymerPacking(_Model):
identifier: str
units: dict[str, RepeatUnit] = Field(min_length=1, max_length=10)
chains: list[ChainSpec] = Field(min_length=1, max_length=20)
seed: int = Field(ge=0, lt=2**63)
cell: Cell
torsion_states: list[TorsionState] = Field(
default_factory=lambda: list(_DEFAULT_STATES), min_length=1, max_length=12
)
#: Each drawn torsion is its state plus a uniform offset within this many degrees.
torsion_jitter_deg: float = Field(default=10.0, ge=0, le=60, allow_inf_nan=False)
radii: Literal["vdw", "covalent"] = "vdw"
radius_overrides: dict[str, float] = Field(default_factory=dict, max_length=118)
collision_scale: float = Field(default=0.6, ge=0.3, le=1.5, allow_inf_nan=False)
max_attempts: int = Field(default=200_000, ge=1, le=MAX_ATTEMPTS)
#: Fresh internal-torsion draws for a step before the chain is regrown.
step_retries: int = Field(default=8, ge=1, le=100)
#: Placements one chain may undo (backtracking) before it is regrown from a new start.
max_backtracks: int = Field(default=200, ge=0, le=100_000)
#: Regrowths of one chain from a new start before the request gives up.
max_regrowths: int = Field(default=20, ge=0, le=10_000)
on_exhausted: Literal["refuse", "partial"] = "refuse"
excluded: list[Region] = Field(default_factory=list, max_length=20)
crosslinking: Crosslinking | None = None
@field_validator("identifier")
@classmethod
def _id(cls, value: str) -> str:
return _identifier(value)
@model_validator(mode="after")
def _radii(self) -> Self:
for symbol, radius in self.radius_overrides.items():
if symbol not in ATOMIC_NUMBER:
raise ValueError(f"unknown element {symbol!r} in radius_overrides")
if not (math.isfinite(radius) and 0.1 <= radius <= 4.0):
raise ValueError("override radii must be between 0.1 and 4 angstrom")
for label in self.units:
_identifier(label)
if sum(c.count for c in self.chains) > MAX_CHAINS:
raise ValueError(f"at most {MAX_CHAINS} chains in one request")
return self
[docs]
def parse_packing(data: dict[str, Any]) -> PolymerPacking:
return TypeAdapter(PolymerPacking).validate_python(data)
[docs]
def content_digest(structure: PeriodicStructure) -> str:
"""Digest of a structure without its provenance (which records the digest)."""
data = structure.model_dump(mode="json", exclude={"provenance", "source_cif"})
return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
def _refusal(code: str, message: str) -> dict[str, Any]:
return {"code": code, "message": message}
[docs]
class PolymerRefused(ValueError):
"""A repeat unit or end group cannot be used; ``code`` is a stable refusal code."""
def __init__(self, code: str, message: str) -> None:
super().__init__(message)
self.code = code
[docs]
@dataclass(frozen=True)
class Inclusion:
"""Fixed atoms the chains grow around, in a cell the caller states (#241).
``lengths``, ``pbc``, ``lower`` and ``upper`` replace the request's cell:
the orthorhombic edges, the periodic axes and the growth region's corners
(nonperiodic axes only). ``volume`` is the region volume the unrelaxed
density is reported over. ``xyz`` are Cartesian positions of the fixed
atoms; ``forbidden`` maps an ``(n, 3)`` array of unwrapped Cartesian chain
positions to an ``(n,)`` boolean array, true where a position lies in a
forbidden interior.
"""
label: str
lengths: np.ndarray
pbc: tuple[bool, bool, bool]
lower: np.ndarray
upper: np.ndarray
volume: float
symbols: list[str]
xyz: np.ndarray
forbidden: Callable[[np.ndarray], np.ndarray] | None = None
#: The grid's chain index of an inclusion atom.
INCLUSION_CHAIN = -1
# Fragments: repeat units and end groups --------------------------------------
@dataclass
class _Fragment:
"""An embedded repeat unit or end group, in the frame of its stand-in molecule.
``xyz`` holds every stand-in atom; ``real`` indexes the atoms that are kept
(markers and nothing else are dropped). Indices below are stand-in indices.
"""
label: str
source: dict[str, Any]
symbols: list[str] # of the real atoms, in ``real`` order
real: list[int]
xyz: np.ndarray
#: Head and tail: (marker, anchor); an end group has a head only.
head: tuple[int, int]
tail: tuple[int, int] | None
bonds: list[tuple[int, int, float, str]] # real positions, order, RDKit bond type name
aromatic: list[bool]
charges: list[int]
hydrogens: list[int] # explicit H count of each real atom carried by RDKit
#: Backbone path in stand-in indices, head marker first.
path: list[int]
#: Rotatable backbone bonds: (a, b, c, d, moving stand-in atoms, conjugated).
torsions: list[tuple[int, int, int, int, np.ndarray, bool]]
#: Backbone stereocentres: (centre, head-side, tail-side, side) stand-in indices.
stereo: list[tuple[int, int, int, int]]
side_stereo: int
#: Side-group rotors: (b, c, moving stand-in atoms on c's side), turned uniformly.
rotors: list[tuple[int, int, np.ndarray]]
topology: np.ndarray # real-by-real bond-count distances
from_anchor: np.ndarray # bond count from the head anchor, per real atom
mass: float
formula: Counter[str]
planar_head: bool
planar_tail: bool
notes: list[str] = field(default_factory=list)
radicals: int = 0
def position(self, stand_in: int) -> int:
return self.real.index(stand_in)
def _marker_mol(smiles: str, what: str) -> Any:
"""``smiles`` read with RDKit; an SRU bracket (if any) cut out with markers 1 and 2."""
from rdkit import Chem
mol = Chem.MolFromSmiles(smiles)
if mol is None:
raise PolymerRefused("polymer.unit_unreadable", f"cannot read the {what} {smiles!r}")
groups = [g for g in Chem.GetMolSubstanceGroups(mol) if g.GetProp("TYPE") == "SRU"]
if not groups:
return mol
if len(groups) > 1:
raise PolymerRefused(
"polymer.unit_ambiguous",
f"the {what} has {len(groups)} repeat-unit brackets; give one unit as SMILES",
)
inside = set(groups[0].GetAtoms())
crossing = sorted(
(
(b.GetBeginAtomIdx(), b.GetEndAtomIdx())
if b.GetBeginAtomIdx() in inside
else (b.GetEndAtomIdx(), b.GetBeginAtomIdx())
)
for b in mol.GetBonds()
if (b.GetBeginAtomIdx() in inside) != (b.GetEndAtomIdx() in inside)
)
if len(crossing) != 2:
raise PolymerRefused(
"polymer.unit_markers",
f"the {what}'s bracket is crossed by {len(crossing)} bonds; a chain needs two",
)
for a, b in crossing:
if mol.GetBondBetweenAtoms(a, b).GetBondTypeAsDouble() != 1.0:
raise PolymerRefused("polymer.unit_markers", f"the {what}'s crossing bonds are single")
editable = Chem.RWMol()
order: dict[int, int] = {}
for index in sorted(inside):
order[index] = editable.AddAtom(mol.GetAtomWithIdx(index))
for bond in mol.GetBonds():
a, b = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()
if a in order and b in order:
editable.AddBond(order[a], order[b], bond.GetBondType())
for number, (a, _) in enumerate(crossing, start=1):
marker = Chem.Atom(0)
marker.SetAtomMapNum(number)
editable.AddBond(order[a], editable.AddAtom(marker), Chem.BondType.SINGLE)
cut = editable.GetMol()
try:
Chem.SanitizeMol(cut)
except Exception as error: # RDKit raises several sanitisation types
raise PolymerRefused("polymer.unit_unreadable", f"the {what}: {error}") from None
return cut
def _fragment(label: str, smiles: str, source: dict[str, Any], points: int) -> _Fragment:
"""Embed a unit (``points=2``) or an end group (``points=1``) with H stand-ins."""
from rdkit import Chem
from vibesketcher.chem.frameworks import _embed_mol, _rdkit_version
what = "repeat unit" if points == 2 else "end group"
mol = _marker_mol(smiles, f"{what} {label}")
markers = [a.GetIdx() for a in mol.GetAtoms() if a.GetAtomicNum() == 0]
if len(markers) != points:
raise PolymerRefused(
"polymer.unit_markers",
f"the {what} {label} has {len(markers)} connection points; it needs {points}",
)
numbers = [mol.GetAtomWithIdx(m).GetAtomMapNum() for m in markers]
if points == 2 and sorted(numbers) == [1, 2]:
markers = [markers[numbers.index(1)], markers[numbers.index(2)]]
anchors = []
for m in markers:
neighbours = list(mol.GetAtomWithIdx(m).GetNeighbors())
if len(neighbours) != 1 or neighbours[0].GetAtomicNum() == 0:
raise PolymerRefused(
"polymer.unit_markers", f"a connection point of {label} bonds to one real atom"
)
if mol.GetBondBetweenAtoms(m, neighbours[0].GetIdx()).GetBondTypeAsDouble() != 1.0:
raise PolymerRefused(
"polymer.unit_markers", f"a connection point of {label} is singly bonded"
)
anchors.append(neighbours[0].GetIdx())
# Potential stereocentres, read with the markers as distinct neighbours.
from vibesketcher.chem._rdkit import untyped
found = untyped(Chem).FindMolChiralCenters(
mol, includeUnassigned=True, useLegacyImplementation=False
)
centres = [index for index, _ in found]
canonical = Chem.MolToSmiles(mol)
editable = Chem.RWMol(mol)
for m in markers:
atom = editable.GetAtomWithIdx(m)
atom.SetAtomicNum(1)
atom.SetAtomMapNum(0)
atom.SetIsotope(0)
atom.SetNoImplicit(True)
stand_in = editable.GetMol()
try:
Chem.SanitizeMol(stand_in)
except Exception as error: # RDKit raises several sanitisation types
raise PolymerRefused("polymer.unit_unreadable", f"the {what} {label}: {error}") from None
from vibesketcher.chem.periodic_geometry import BuildRefused
try:
embedded = _embed_mol(stand_in, f"{what} {label}")
except BuildRefused as error:
raise PolymerRefused("polymer.unit_unreadable", str(error)) from None
xyz = np.asarray(embedded.GetConformer().GetPositions(), dtype=float)
real = [a.GetIdx() for a in embedded.GetAtoms() if a.GetIdx() not in markers]
if len(real) > MAX_UNIT_ATOMS:
raise PolymerRefused(
"polymer.unit_unreadable", f"the {what} {label} has more than {MAX_UNIT_ATOMS} atoms"
)
position = {old: new for new, old in enumerate(real)}
bonds = [
(
position[b.GetBeginAtomIdx()],
position[b.GetEndAtomIdx()],
float(b.GetBondTypeAsDouble()),
str(b.GetBondType()),
)
for b in embedded.GetBonds()
if b.GetBeginAtomIdx() in position and b.GetEndAtomIdx() in position
]
atoms = [embedded.GetAtomWithIdx(i) for i in real]
symbols = [a.GetSymbol() for a in atoms]
table = Chem.GetPeriodicTable()
mass = float(sum(table.GetAtomicWeight(ATOMIC_NUMBER[s]) for s in symbols))
matrix = Chem.GetDistanceMatrix(embedded)
topology = np.asarray(matrix, dtype=float)[np.ix_(real, real)].astype(int)
head_marker, head_anchor = markers[0], anchors[0]
from_anchor = topology[position[head_anchor]]
path: list[int] = [head_marker, head_anchor]
torsions: list[tuple[int, int, int, int, np.ndarray, bool]] = []
stereo: list[tuple[int, int, int, int]] = []
tail = None
if points == 2:
tail = (markers[1], anchors[1])
path = list(Chem.GetShortestPath(embedded, markers[0], markers[1]))
for k in range(1, len(path) - 2):
b, c = path[k], path[k + 1]
bond = embedded.GetBondBetweenAtoms(b, c)
if bond.IsInRing() or bond.GetBondTypeAsDouble() != 1.0 or bond.GetIsConjugated():
continue # conjugated backbone bonds keep the embedded torsion
moving = _side(embedded, b, c)
torsions.append(
(path[k - 1], b, c, path[k + 2], np.asarray(moving), bool(bond.GetIsConjugated()))
)
on_path = set(path)
for centre in centres:
if centre not in on_path:
continue
k = path.index(centre)
others = [
n.GetIdx()
for n in embedded.GetAtomWithIdx(centre).GetNeighbors()
if n.GetIdx() not in on_path
]
others.sort(key=lambda i: (embedded.GetAtomWithIdx(i).GetAtomicNum() == 1, i))
stereo.append((centre, path[k - 1], path[k + 1], others[0]))
side_stereo = len([c for c in centres if c not in set(path)])
# Side-group rotors (methyls and other single bonds off the backbone) turn freely.
rotors: list[tuple[int, int, np.ndarray]] = []
backbone_bonds = {frozenset(pair) for pair in zip(path, path[1:], strict=False)}
for bond in embedded.GetBonds():
b, c = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()
if (
bond.IsInRing()
or bond.GetBondTypeAsDouble() != 1.0
or bond.GetIsConjugated()
or frozenset((b, c)) in backbone_bonds
or min(bond.GetBeginAtom().GetDegree(), bond.GetEndAtom().GetDegree()) < 2
):
continue
moving = _side(embedded, b, c)
if markers[0] in moving:
b, c = c, b
moving = _side(embedded, b, c)
if any(m in moving for m in markers) or len(moving) < 2:
continue
rotors.append((b, c, np.asarray(moving)))
def planar(index: int) -> bool:
atom = embedded.GetAtomWithIdx(index)
return bool(atom.GetIsAromatic()) or str(atom.GetHybridization()) == "SP2"
notes = [
f"{what} {label} embedded with RDKit {_rdkit_version()} "
"(ETKDGv3, MMFF94/UFF, fixed seed), H stand-ins on the connection points"
]
return _Fragment(
label=label,
source={**source, "unit_smiles": canonical},
symbols=symbols,
real=real,
xyz=xyz,
head=(head_marker, head_anchor),
tail=tail,
bonds=bonds,
aromatic=[bool(a.GetIsAromatic()) for a in atoms],
charges=[int(a.GetFormalCharge()) for a in atoms],
hydrogens=[int(a.GetNumExplicitHs()) for a in atoms],
path=path,
torsions=torsions,
rotors=rotors,
stereo=stereo,
side_stereo=side_stereo,
topology=topology,
from_anchor=np.asarray(from_anchor, dtype=int),
mass=mass,
formula=Counter(symbols),
planar_head=planar(head_anchor),
planar_tail=planar(tail[1]) if tail else False,
notes=notes,
radicals=sum(int(a.GetNumRadicalElectrons()) for a in atoms),
)
def _side(mol: Any, b: int, c: int) -> list[int]:
"""Atoms on ``c``'s side of the bond b-c (``c`` included)."""
seen = {b, c}
todo = [c]
while todo:
atom = todo.pop()
for n in mol.GetAtomWithIdx(atom).GetNeighbors():
if n.GetIdx() not in seen:
seen.add(n.GetIdx())
todo.append(n.GetIdx())
seen.discard(b)
return sorted(seen)
def _hydrogen() -> _Fragment:
"""The default end group: a hydrogen atom on the connection point."""
return _Fragment(
label="H",
source={"source": "hydrogen"},
symbols=["H"],
real=[1],
xyz=np.asarray([[1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
head=(0, 1),
tail=None,
bonds=[],
aromatic=[False],
charges=[0],
hydrogens=[0],
path=[0, 1],
torsions=[],
rotors=[],
stereo=[],
side_stereo=0,
topology=np.zeros((1, 1), dtype=int),
from_anchor=np.zeros(1, dtype=int),
mass=1.008,
formula=Counter({"H": 1}),
planar_head=False,
planar_tail=False,
)
def _unit(document: Document | None, label: str, unit: RepeatUnit) -> _Fragment:
source: dict[str, Any]
if unit.smiles is not None:
smiles, source = unit.smiles, {"source": "smiles", "smiles": unit.smiles}
elif unit.template is not None:
from vibesketcher.document.reaction_library import ReactionRefused
from vibesketcher.document.template_library import get_template
try:
entry = get_template(unit.template)
except ReactionRefused as error:
raise PolymerRefused("polymer.unit_unreadable", str(error)) from None
if entry.kind != "polymer" or entry.smiles is None:
raise PolymerRefused(
"polymer.unit_unreadable", f"template {unit.template!r} is not a polymer"
)
smiles = entry.smiles
source = {"source": "template", "template": entry.id, "cxsmiles": smiles}
else:
if document is None:
raise PolymerRefused(
"polymer.unit_unreadable", "a drawn repeat unit needs the document"
)
found = {g.id: g for g in document.generics}
generic = found.get(unit.generic or "")
if generic is None or generic.kind != "bracketed":
raise PolymerRefused(
"polymer.unit_unreadable", f"no bracketed generic {unit.generic!r} in the document"
)
smiles = generic.cxsmiles
source = {"source": "generic", "generic": generic.id, "cxsmiles": smiles}
return _fragment(label, smiles, source, 2)
def _end(text: str) -> _Fragment:
if text == "H":
return _hydrogen()
return _fragment(text, text, {"source": "smiles", "smiles": text}, 1)
# Geometry ---------------------------------------------------------------------
def _rotation_about(axis: np.ndarray, angle: float) -> np.ndarray:
axis = axis / np.linalg.norm(axis)
x, y, z = axis
c, s = math.cos(angle), math.sin(angle)
C = 1 - c
return np.asarray(
[
[c + x * x * C, x * y * C - z * s, x * z * C + y * s],
[y * x * C + z * s, c + y * y * C, y * z * C - x * s],
[z * x * C - y * s, z * y * C + x * s, c + z * z * C],
]
)
def _align(v: np.ndarray, target: np.ndarray) -> np.ndarray:
"""The smallest rotation taking unit vector ``v`` onto unit vector ``target``."""
v, target = v / np.linalg.norm(v), target / np.linalg.norm(target)
axis = np.cross(v, target)
sine, cosine = float(np.linalg.norm(axis)), float(v @ target)
if sine < 1e-9:
if cosine > 0:
return np.eye(3)
helper = np.asarray([1.0, 0, 0]) if abs(v[0]) < 0.9 else np.asarray([0, 1.0, 0])
return _rotation_about(np.cross(v, helper), math.pi)
return _rotation_about(axis, math.atan2(sine, cosine))
def _dihedral(a: np.ndarray, b: np.ndarray, c: np.ndarray, d: np.ndarray) -> float:
b0, b1, b2 = a - b, c - b, d - c
b1 = b1 / np.linalg.norm(b1)
v = b0 - (b0 @ b1) * b1
w = b2 - (b2 @ b1) * b1
return math.atan2(float(np.cross(b1, v) @ w), float(v @ w))
def _rotation(rng: np.random.Generator) -> np.ndarray:
from vibesketcher.document.guest_loading import _rotation as uniform
return uniform(rng)
def _states(packing: PolymerPacking, planar: bool) -> tuple[np.ndarray, np.ndarray]:
if planar:
return np.radians(np.arange(-150.0, 181.0, 30.0)), np.ones(12)
return (
np.radians([s.angle_deg for s in packing.torsion_states]),
np.asarray([s.weight for s in packing.torsion_states]),
)
def _conformer(
fragment: _Fragment, mirror: bool, packing: PolymerPacking, rng: np.random.Generator
) -> np.ndarray:
"""Stand-in coordinates with each rotatable backbone torsion drawn from its states."""
xyz = fragment.xyz.copy()
if mirror:
xyz[:, 0] = -xyz[:, 0]
jitter = math.radians(packing.torsion_jitter_deg)
for a, b, c, d, moving, conjugated in fragment.torsions:
angles, weights = _states(packing, conjugated)
target = float(rng.choice(angles, p=weights / weights.sum()))
target += float(rng.uniform(-jitter, jitter))
now = _dihedral(xyz[a], xyz[b], xyz[c], xyz[d])
turn = _rotation_about(xyz[c] - xyz[b], target - now)
xyz[moving] = (xyz[moving] - xyz[c]) @ turn.T + xyz[c]
for b, c, moving in fragment.rotors:
turn = _rotation_about(xyz[c] - xyz[b], float(rng.uniform(0, 2 * math.pi)))
xyz[moving] = (xyz[moving] - xyz[c]) @ turn.T + xyz[c]
return xyz
# Collision grid -------------------------------------------------------------
class _Grid:
"""Placed atoms binned in an orthorhombic cell (a linked-cell list, Allen and Tildesley 5.3).
Periodic axes use the minimum image, which the box-size refusal makes exact
(every periodic length is at least twice the largest cutoff).
"""
def __init__(
self, lengths: np.ndarray, pbc: tuple[bool, bool, bool], cutoff: float, capacity: int
):
self.lengths = lengths
self.pbc = np.asarray(pbc)
self.count = np.asarray([max(1, int(lengths[k] // cutoff)) for k in range(3)])
self.pos = np.zeros((capacity, 3))
self.radius = np.zeros(capacity)
self.chain = np.zeros(capacity, dtype=int)
self.n = 0
self.bins: dict[tuple[int, int, int], list[int]] = {}
self._around: dict[tuple[int, int, int], list[tuple[int, int, int]]] = {}
def wrap(self, xyz: np.ndarray) -> np.ndarray:
out = np.array(xyz, dtype=float)
for k in range(3):
if self.pbc[k]:
out[..., k] -= self.lengths[k] * np.floor(out[..., k] / self.lengths[k])
return out
def _key(self, p: np.ndarray) -> tuple[int, int, int]:
f = np.clip(p / self.lengths, 0, 1 - 1e-12)
k = np.minimum((f * self.count).astype(int), self.count - 1)
return int(k[0]), int(k[1]), int(k[2])
def _near(self, home: tuple[int, int, int]) -> list[tuple[int, int, int]]:
if home not in self._around:
options = []
for k in range(3):
c = int(self.count[k])
if self.pbc[k]:
these = set(range(c)) if c < 3 else {(home[k] + o) % c for o in (-1, 0, 1)}
else:
these = {home[k] + o for o in (-1, 0, 1) if 0 <= home[k] + o < c}
options.append(sorted(these))
self._around[home] = [
(i, j, k) for i in options[0] for j in options[1] for k in options[2]
]
return self._around[home]
def delta(self, d: np.ndarray) -> np.ndarray:
d = np.array(d, dtype=float)
for k in range(3):
if self.pbc[k]:
d[..., k] -= self.lengths[k] * np.round(d[..., k] / self.lengths[k])
return d
def add(self, xyz: np.ndarray, radii: np.ndarray, chain: int) -> None:
wrapped = self.wrap(xyz)
for p, r in zip(wrapped, radii, strict=True):
self.pos[self.n], self.radius[self.n], self.chain[self.n] = p, r, chain
self.bins.setdefault(self._key(p), []).append(self.n)
self.n += 1
def truncate(self, start: int) -> None:
"""Forget every atom from index ``start`` on (a chain being regrown)."""
for index in range(start, self.n):
self.bins[self._key(self.pos[index])].remove(index)
self.n = start
def clash(
self, xyz: np.ndarray, radii: np.ndarray, scale: float, excluded: dict[int, set[int]]
) -> int | None:
"""The chain of a placed atom the trial atoms overlap, or ``None``.
``excluded`` maps a trial atom to the placed atoms it is bonded close to.
"""
wrapped = self.wrap(xyz)
chosen: set[int] = set()
for p in wrapped:
for near in self._near(self._key(p)):
chosen.update(self.bins.get(near, ()))
if not chosen:
return None
index = np.fromiter(chosen, dtype=int)
d = self.delta(self.pos[index][None, :, :] - wrapped[:, None, :])
dist = np.sqrt(np.einsum("ijk,ijk->ij", d, d))
hit = dist < scale * (radii[:, None] + self.radius[index][None, :])
for i, bonded in excluded.items():
if bonded:
hit[i] &= ~np.isin(index, list(bonded))
rows, cols = np.nonzero(hit)
if not len(rows):
return None
return int(self.chain[index[cols[0]]])
# Chains -------------------------------------------------------------------------
@dataclass
class _Plan:
"""One chain to grow: its spec, sequence of unit labels and mirror flags."""
spec: int
label: str
sequence: list[str]
mirror: list[bool]
head: str
tail: str
tacticity: str | None
@dataclass
class _Placed:
"""A fragment placed in a chain: its real atoms in Cartesian coordinates."""
fragment: _Fragment
kind: Literal["head", "unit", "tail"]
residue: int # 0-based unit index; -1 head end, length for the tail end
xyz: np.ndarray # stand-in coordinates (markers included)
start: int # global index of the first real atom in the chain's atom list
mirror: bool = False
def _sequence(spec: ChainSpec, length: int, rng: np.random.Generator) -> list[str]:
if spec.unit is not None:
return [spec.unit] * length
if spec.sequence is not None:
return list(spec.sequence)
assert spec.composition is not None
labels = list(spec.composition)
weights = np.asarray([spec.composition[k] for k in labels], dtype=float)
weights = weights / weights.sum()
if spec.arrangement == "alternating":
return [labels[i % len(labels)] for i in range(length)]
if spec.arrangement == "block":
sizes = [int(round(w * length)) for w in weights]
sizes[-1] = length - sum(sizes[:-1])
if min(sizes) < 0:
sizes = [length] + [0] * (len(labels) - 1)
return [label for label, n in zip(labels, sizes, strict=True) for _ in range(n)]
return [labels[int(i)] for i in rng.choice(len(labels), size=length, p=weights)]
def _plans(packing: PolymerPacking, rng: np.random.Generator) -> list[_Plan]:
plans = []
for index, spec in enumerate(packing.chains):
for number, length in enumerate(spec.chain_lengths()):
sequence = _sequence(spec, length, rng)
mirror = [False] * length
if spec.tacticity == "syndiotactic":
mirror = [i % 2 == 1 for i in range(length)]
elif spec.tacticity == "atactic":
mirror = [bool(x) for x in rng.integers(0, 2, size=length)]
label = spec.label or (spec.unit or f"chains{index + 1}")
plans.append(
_Plan(
spec=index,
label=f"{label} {number + 1}"[:80],
sequence=sequence,
mirror=mirror,
head=spec.head,
tail=spec.tail,
tacticity=spec.tacticity,
)
)
return plans
@dataclass
class _Growth:
"""Counters shared by every chain of one request."""
attempts: int = 0
backtracks: int = 0
rejections: Counter[str] = field(default_factory=Counter)
regrowths: int = 0
class _Exhausted(Exception):
pass
def _bond_length(a: str, b: str) -> float:
return pg.covalent_radius(a) + pg.covalent_radius(b)
class _Dead(Exception):
pass
class _Chain:
"""One chain being grown: its atoms (chain-local order) and the placements so far."""
def __init__(
self,
index: int,
packing: PolymerPacking,
grid: _Grid,
region: tuple[np.ndarray, np.ndarray],
excluded: list[tuple[np.ndarray, np.ndarray]],
radius: dict[str, float],
rng: np.random.Generator,
growth: _Growth,
forbidden: Callable[[np.ndarray], np.ndarray] | None = None,
) -> None:
self.index, self.packing, self.grid = index, packing, grid
self.forbidden = forbidden
self.lower, self.upper = region
self.excluded, self.radius, self.rng, self.growth = excluded, radius, rng, growth
self.origin = grid.n # grid index of the chain's first atom
self.reset()
def reset(self) -> None:
self.grid.truncate(self.origin)
self.atoms: list[np.ndarray] = []
self.symbols: list[str] = []
self.adjacency: list[list[int]] = []
#: Accepted placements in order, each with its attach atom and backbone length before.
self.stack: list[tuple[_Placed, int | None, int]] = []
self.backbone: list[int] = []
def accept(self, placed: _Placed, attach: int | None) -> None:
fragment, xyz = placed.fragment, placed.xyz
start = len(self.symbols)
assert start == placed.start
for s, p in zip(fragment.symbols, xyz[fragment.real], strict=True):
self.symbols.append(s)
self.atoms.append(p)
self.adjacency.append([])
for i, j, _, _ in fragment.bonds:
self.adjacency[start + i].append(start + j)
self.adjacency[start + j].append(start + i)
if attach is not None:
anchor = start + fragment.position(fragment.head[1])
self.adjacency[attach].append(anchor)
self.adjacency[anchor].append(attach)
radii = np.asarray([self.radius[s] for s in fragment.symbols])
self.grid.add(xyz[fragment.real], radii, self.index)
self.stack.append((placed, attach, len(self.backbone)))
if placed.kind == "head":
self.backbone.insert(0, start + fragment.position(fragment.head[1]))
elif placed.kind == "unit":
self.backbone += [start + fragment.position(i) for i in fragment.path[1:-1]]
def pop(self) -> None:
"""Remove the last placement (backtracking)."""
placed, attach, backbone = self.stack.pop()
start = placed.start
self.grid.truncate(self.origin + start)
del self.atoms[start:], self.symbols[start:], self.adjacency[start:]
if attach is not None:
self.adjacency[attach] = [n for n in self.adjacency[attach] if n < start]
if placed.kind == "head":
self.backbone.pop(0)
else:
del self.backbone[backbone:]
def free(self, fragment: _Fragment, xyz: np.ndarray, attach: int | None) -> str | None:
"""Why the placed fragment ``xyz`` is not free, or ``None``."""
packing, grid = self.packing, self.grid
if self.growth.attempts >= packing.max_attempts:
raise _Exhausted
self.growth.attempts += 1
mine = xyz[fragment.real]
for k in range(3):
if not grid.pbc[k] and (
mine[:, k].min() < self.lower[k] or mine[:, k].max() > self.upper[k]
):
return "outside_region"
if self.excluded:
frac = grid.wrap(mine) / grid.lengths
for lo, hi in self.excluded:
if np.any(np.all((frac > lo) & (frac < hi), axis=1)):
return "excluded_region"
if self.forbidden is not None and bool(np.any(self.forbidden(mine))):
return "inclusion_interior"
radii = np.asarray([self.radius[s] for s in fragment.symbols])
scale = packing.collision_scale
# Pairs inside the fragment more than three bonds apart.
far = fragment.topology > 3
if far.any():
d = np.linalg.norm(mine[:, None, :] - mine[None, :, :], axis=-1)
if np.any(far & (d < scale * (radii[:, None] + radii[None, :]))):
return "intra_unit"
# Atoms of the chain up to three bonds from a new atom are not contacts.
near: dict[int, set[int]] = {}
if attach is not None:
depth = self.depths(attach)
for i in range(len(mine)):
reach = 2 - int(fragment.from_anchor[i])
near[i] = {self.origin + j for j, n in depth.items() if n <= reach}
hit = grid.clash(mine, radii, scale, near)
if hit is None:
return None
if hit == INCLUSION_CHAIN:
return "inclusion_contact"
return "self_contact" if hit == self.index else "chain_contact"
def depths(self, origin: int) -> dict[int, int]:
seen = {origin: 0}
frontier = [origin]
for depth in (1, 2):
following = []
for atom in frontier:
for n in self.adjacency[atom]:
if n not in seen:
seen[n] = depth
following.append(n)
frontier = following
return seen
def first(self, fragment: _Fragment, mirror: bool) -> _Placed | None:
"""The first unit: a uniformly random orientation and position in the region."""
for _ in range(self.packing.step_retries * 10):
xyz = _conformer(fragment, mirror, self.packing, self.rng)
centre = xyz[fragment.real].mean(axis=0)
where = self.lower + self.rng.random(3) * (self.upper - self.lower)
xyz = (xyz - centre) @ _rotation(self.rng).T + where
reason = self.free(fragment, xyz, None)
if reason is None:
return _Placed(fragment, "unit", 0, xyz, 0, mirror)
self.growth.rejections[reason] += 1
return None
def attach(
self,
fragment: _Fragment,
kind: Literal["head", "unit", "tail"],
residue: int,
mirror: bool,
point: tuple[_Placed, Literal["head", "tail"]],
reference: np.ndarray,
) -> tuple[_Placed, int] | None:
"""Place ``fragment`` on a connection point of an earlier placement."""
owner, which = point
end = owner.fragment.head if which == "head" else owner.fragment.tail
assert end is not None
m, t = end
anchor = owner.start + owner.fragment.position(t)
direction = owner.xyz[m] - owner.xyz[t]
direction = direction / np.linalg.norm(direction)
planar = (
owner.fragment.planar_head if which == "head" else owner.fragment.planar_tail
) and (fragment.planar_head)
h = fragment.head[1]
target = self.atoms[anchor] + direction * _bond_length(
self.symbols[anchor], fragment.symbols[fragment.position(h)]
)
start = len(self.symbols)
for _ in range(self.packing.step_retries):
xyz = _conformer(fragment, mirror, self.packing, self.rng)
turn = _align(xyz[fragment.head[0]] - xyz[h], -direction)
base = (xyz - xyz[h]) @ turn.T + target
if len(fragment.real) == 1:
reason = self.free(fragment, base, anchor)
if reason is None:
return _Placed(fragment, kind, residue, base, start, mirror), anchor
self.growth.rejections[reason] += 1
continue
now = _dihedral(reference, self.atoms[anchor], base[h], base[_ahead(fragment)])
angles, weights = _states(self.packing, planar)
candidates, chosen = [], []
jitter = math.radians(self.packing.torsion_jitter_deg)
for angle, weight in zip(angles, weights, strict=True):
offset = float(self.rng.uniform(-jitter, jitter))
spin = _rotation_about(direction, angle + offset - now)
trial = (base - target) @ spin.T + target
reason = self.free(fragment, trial, anchor)
if reason is None:
candidates.append(trial)
chosen.append(weight)
else:
self.growth.rejections[reason] += 1
if candidates:
w = np.asarray(chosen)
pick = int(self.rng.choice(len(candidates), p=w / w.sum()))
return _Placed(fragment, kind, residue, candidates[pick], start, mirror), anchor
return None
def _grow(
plan: _Plan,
chain: _Chain,
fragments: dict[str, _Fragment],
ends: dict[str, _Fragment],
) -> tuple[list[_Placed], np.ndarray]:
"""Grow one chain with backtracking; its placements (head, units, tail) and atoms.
Steps are the first unit, the head end group, the other units and the
tail end group. A step with no free state pops the previous placement and
retries it; past ``max_backtracks`` the chain is regrown from a new start.
"""
packing, growth = chain.packing, chain.growth
count = len(plan.sequence)
steps = count + 2
for _ in range(packing.max_regrowths + 1):
chain.reset()
backtracks = 0
step = 0
while step < steps:
units = [p for p, _, _ in chain.stack if p.kind == "unit"]
got: tuple[_Placed, int | None] | None
if step == 0:
found = chain.first(fragments[plan.sequence[0]], plan.mirror[0])
got = None if found is None else (found, None)
elif step == 1:
first = units[0]
got = chain.attach(
ends[plan.head],
"head",
-1,
False,
(first, "head"),
first.xyz[first.fragment.path[2]],
)
elif step < steps - 1:
residue = step - 1
got = chain.attach(
fragments[plan.sequence[residue]],
"unit",
residue,
plan.mirror[residue],
(units[-1], "tail"),
chain.atoms[chain.backbone[-2]],
)
else:
got = chain.attach(
ends[plan.tail],
"tail",
count,
False,
(units[-1], "tail"),
chain.atoms[chain.backbone[-2]],
)
if got is not None:
chain.accept(*got)
step += 1
continue
backtracks += 1
growth.backtracks += 1
if step == 0 or backtracks > packing.max_backtracks:
break
chain.pop()
step -= 1
else:
ordered = sorted((p for p, _, _ in chain.stack), key=lambda p: p.residue)
return ordered, np.asarray(chain.atoms)
growth.regrowths += 1
chain.reset()
raise _Exhausted
def _ahead(fragment: _Fragment) -> int:
"""A stand-in atom one bond past the head anchor, for the junction torsion."""
if len(fragment.path) > 2:
return fragment.path[2]
h = fragment.head[1]
# An end group: a real neighbour of its anchor, heavy atoms first.
for i, j, _, _ in fragment.bonds:
for x, y in ((i, j), (j, i)):
if fragment.real[x] == h:
return fragment.real[y]
return fragment.head[0]
# Checks -------------------------------------------------------------------------
def _valence(chain: list[_Placed], bonds: list[tuple[int, int, float, str]]) -> str | None:
"""Why the chain does not sanitise in RDKit, or ``None``."""
from rdkit import Chem
mol = Chem.RWMol()
for placed in chain:
f = placed.fragment
for n in range(len(f.symbols)):
atom = Chem.Atom(ATOMIC_NUMBER[f.symbols[n]])
atom.SetFormalCharge(f.charges[n])
atom.SetIsAromatic(f.aromatic[n])
atom.SetNumExplicitHs(f.hydrogens[n])
atom.SetNoImplicit(True)
mol.AddAtom(atom)
for i, j, _, kind in bonds:
bond_type = getattr(Chem.BondType, kind)
mol.AddBond(i, j, bond_type)
if bond_type == Chem.BondType.AROMATIC:
mol.GetBondBetweenAtoms(i, j).SetIsAromatic(True)
try:
Chem.SanitizeMol(mol)
except Exception as error: # RDKit raises several sanitisation types
return str(error)
return None
def _components(count: int, bonds: list[tuple[int, int]]) -> list[int]:
parent = list(range(count))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in bonds:
parent[find(a)] = find(b)
return [find(x) for x in range(count)]
def _signed_volume(c: np.ndarray, a: np.ndarray, b: np.ndarray, s: np.ndarray) -> float:
return float(np.linalg.det(np.stack([a - c, b - c, s - c])))
# Preview, apply, undo --------------------------------------------------------
def _cell(
packing: PolymerPacking, mass: float
) -> tuple[np.ndarray, tuple[bool, bool, bool], np.ndarray, np.ndarray, float]:
"""Cell lengths, pbc, the growth region's lower and upper corners and its volume."""
# V = M / (rho N_A) with M in g/mol, V in A^3 (1 cm^3 = 1e24 A^3); N_A from CODATA 2018.
cell = packing.cell
if cell.kind == "box":
if cell.lengths_angstrom is not None:
lengths = np.asarray(cell.lengths_angstrom, dtype=float)
else:
assert cell.density_g_cm3 is not None
volume = mass / (cell.density_g_cm3 * 6.02214076e23) * 1e24
lengths = np.full(3, volume ** (1 / 3))
return lengths, (True, True, True), np.zeros(3), lengths.copy(), float(np.prod(lengths))
assert cell.lateral_angstrom is not None
a, b = cell.lateral_angstrom
if cell.thickness_angstrom is not None:
thickness = cell.thickness_angstrom
else:
assert cell.density_g_cm3 is not None
thickness = mass / (cell.density_g_cm3 * 6.02214076e23) * 1e24 / (a * b)
vacuum = cell.vacuum_angstrom
lengths = np.asarray([a, b, thickness + 2 * vacuum], dtype=float)
lower = np.asarray([0.0, 0.0, vacuum])
upper = np.asarray([a, b, vacuum + thickness])
return lengths, (True, True, False), lower, upper, float(a * b * thickness)
[docs]
def preview(
packing: PolymerPacking,
document: Document | None = None,
*,
inclusion: Inclusion | None = None,
) -> dict[str, Any]:
"""The packed model, its chains, checks, refusals and provenance; nothing is stored.
With ``inclusion`` the chains grow in its cell and region around its fixed
atoms; the request's cell is not used.
"""
refusals: list[dict[str, Any]] = []
notices: list[dict[str, Any]] = [_refusal("polymer.unrelaxed", NOTE)]
record_base: dict[str, Any] = {
"operation": "pack_polymer",
"method": METHOD,
"references": REFERENCES,
"parameters": packing.model_dump(mode="json", exclude={"identifier"}),
"note": NOTE,
}
result: dict[str, Any] = {
"identifier": packing.identifier,
"applicable": False,
"refusals": refusals,
"notices": notices,
"requested_chains": sum(c.count for c in packing.chains),
"packed_chains": 0,
"attempts": 0,
"backtracks": 0,
"regrowths": 0,
"rejections": {},
"units": {},
"chains": [],
"checks": {},
"cell": None,
"provenance": record_base,
"derived": None,
"codes": CODES,
"note": NOTE,
}
if packing.crosslinking is not None:
refusals.append(
_refusal(
"polymer.crosslinking_unavailable",
f"crosslinking ({packing.crosslinking.chemistry}, conversion "
f"{packing.crosslinking.conversion}) is not implemented; a network is never "
"inferred from contacts",
)
)
fragments: dict[str, _Fragment] = {}
ends: dict[str, _Fragment] = {}
for label, unit in packing.units.items():
try:
fragments[label] = _unit(document, label, unit)
except PolymerRefused as error:
refusals.append(_refusal(error.code, str(error)))
for spec in packing.chains:
for text in (spec.head, spec.tail):
if text not in ends:
try:
ends[text] = _end(text)
except PolymerRefused as error:
refusals.append(_refusal(error.code, str(error)))
unknown = spec.units_named() - set(packing.units)
if unknown:
refusals.append(
_refusal("polymer.unit_unknown", f"undefined repeat units {sorted(unknown)}")
)
if refusals:
return result
for label, f in fragments.items():
result["units"][label] = {
**f.source,
"formula": crystal._json(dict(sorted(f.formula.items()))),
"atoms": len(f.symbols),
"mass": round(f.mass, 4),
"head_anchor": f.symbols[f.position(f.head[1])],
"tail_anchor": f.symbols[f.position(f.tail[1])] if f.tail else None,
"backbone_atoms": len(f.path) - 2,
"rotatable_backbone_bonds": len(f.torsions),
"backbone_stereocentres": len(f.stereo),
"notes": f.notes,
}
if f.side_stereo:
notices.append(
_refusal(
"polymer.side_chain_stereo",
f"{label}: {f.side_stereo} side-chain stereocentre(s) keep the embedded "
"configuration in every unit",
)
)
for spec in packing.chains:
stereo = any(fragments[u].stereo for u in spec.units_named())
if stereo and spec.tacticity is None:
refusals.append(
_refusal(
"polymer.tacticity_unstated",
f"{sorted(spec.units_named())}: a backbone stereocentre needs "
"tacticity isotactic, syndiotactic or atactic",
)
)
if not stereo and spec.tacticity is not None:
refusals.append(
_refusal(
"polymer.tacticity_inapplicable",
f"{sorted(spec.units_named())} have no backbone stereocentre",
)
)
if any(sum(f.charges) for f in [*(fragments[u] for u in spec.units_named())]) or any(
sum(ends[t].charges) for t in (spec.head, spec.tail)
):
refusals.append(_refusal("polymer.charged", CODES["polymer.charged"]))
if any(fragments[u].radicals for u in spec.units_named()) or any(
ends[t].radicals for t in (spec.head, spec.tail)
):
refusals.append(_refusal("polymer.open_shell", CODES["polymer.open_shell"]))
rng = np.random.Generator(np.random.PCG64(packing.seed))
plans = _plans(packing, rng)
mass = sum(
sum(fragments[u].mass for u in p.sequence) + ends[p.head].mass + ends[p.tail].mass
for p in plans
)
planned_sites = sum(
sum(len(fragments[u].symbols) for u in p.sequence)
+ len(ends[p.head].symbols)
+ len(ends[p.tail].symbols)
for p in plans
)
if planned_sites > MAX_ATOMS:
refusals.append(
_refusal("polymer.too_many_sites", f"{planned_sites} sites exceed {MAX_ATOMS}")
)
lengths, pbc, lower, upper, volume = _cell(packing, mass)
if inclusion is not None:
lengths, pbc = np.asarray(inclusion.lengths, dtype=float), inclusion.pbc
lower, upper = np.asarray(inclusion.lower), np.asarray(inclusion.upper)
volume = inclusion.volume
symbols_all = {s for f in [*fragments.values(), *ends.values()] for s in f.symbols}
if inclusion is not None:
symbols_all |= set(inclusion.symbols)
radius = {s: radius_of(s, packing.radii, packing.radius_overrides) for s in sorted(symbols_all)}
cutoff = packing.collision_scale * 2 * max(radius.values())
for k in range(3):
if pbc[k] and lengths[k] < 2 * cutoff:
refusals.append(
_refusal(
"polymer.box_too_small",
f"edge {'abc'[k]} = {lengths[k]:.3f} A is shorter than twice the "
f"collision cutoff {cutoff:.3f} A",
)
)
if not pbc[k] and upper[k] - lower[k] < 1.0:
refusals.append(
_refusal("polymer.box_too_small", "the membrane layer is thinner than 1 A")
)
if any(not 1 <= x <= 2000 for x in lengths):
refusals.append(
_refusal(
"polymer.box_too_small", f"cell edges {lengths.round(3).tolist()} out of range"
)
)
result["cell"] = {
"kind": packing.cell.kind,
"lengths_angstrom": [round(float(x), 6) for x in lengths],
"pbc": list(pbc),
"region_lower_angstrom": [round(float(x), 6) for x in lower],
"region_upper_angstrom": [round(float(x), 6) for x in upper],
"region_volume_angstrom3": round(volume, 6),
"target_density_g_cm3": packing.cell.density_g_cm3,
}
if inclusion is not None:
result["cell"].update(
{
"kind": inclusion.label,
"target_density_g_cm3": None,
"inclusion_atoms": len(inclusion.symbols),
}
)
if refusals:
return result
fixed = 0 if inclusion is None else len(inclusion.symbols)
grid = _Grid(lengths, pbc, cutoff, planned_sites + fixed)
if inclusion is not None and fixed:
grid.add(
np.asarray(inclusion.xyz, dtype=float),
np.asarray([radius[s] for s in inclusion.symbols]),
INCLUSION_CHAIN,
)
forbidden = None if inclusion is None else inclusion.forbidden
growth = _Growth()
excluded = [(np.asarray(r.lower), np.asarray(r.upper)) for r in packing.excluded]
grown: list[tuple[_Plan, list[_Placed], np.ndarray]] = []
exhausted = False
for index, plan in enumerate(plans):
chain = _Chain(
index, packing, grid, (lower, upper), excluded, radius, rng, growth, forbidden
)
try:
placed, xyz = _grow(plan, chain, fragments, ends)
except _Exhausted:
chain.reset()
exhausted = True
break
grown.append((plan, placed, xyz))
result.update(
{
"packed_chains": len(grown),
"attempts": growth.attempts,
"backtracks": growth.backtracks,
"regrowths": growth.regrowths,
"rejections": dict(sorted(growth.rejections.items())),
}
)
if exhausted:
message = (
f"packed {len(grown)} of {len(plans)} chains in {growth.attempts} attempts and "
f"{growth.backtracks} backtracks and {growth.regrowths} regrowths "
f"(rejected: {dict(sorted(growth.rejections.items()))})"
)
if packing.on_exhausted == "refuse" or not grown:
refusals.append(_refusal("polymer.budget_exhausted", message))
return result
notices.append(_refusal("polymer.partial_packing", message))
# The derived model: every chain wrapped site by site with bond images.
counts: Counter[str] = Counter()
sites: list[dict[str, Any]] = []
bonds: list[dict[str, Any]] = []
records: list[dict[str, Any]] = []
site_chain: list[int] = []
graph_bonds: list[tuple[int, int]] = []
expected: Counter[str] = Counter()
problems: list[str] = []
length_report: dict[str, float] = {
"bonds": 0,
"min_ratio": math.inf,
"max_ratio": 0.0,
"image_bonds": 0,
}
tacticity_report: list[dict[str, Any]] = []
for chain_index, (plan, placed, xyz) in enumerate(grown):
offset = len(sites)
chain_symbols = chain_symbols_by(placed)
# Chain-local bonds: inside each fragment, then the junctions.
local: list[tuple[int, int, float, str]] = []
for p in placed:
local += [(p.start + i, p.start + j, o, k) for i, j, o, k in p.fragment.bonds]
units = [p for p in placed if p.kind == "unit"]
head, tail = placed[0], placed[-1]
local.append((anchor_of(units[0], "head"), anchor_of(head, "head"), 1.0, "SINGLE"))
for left, right in zip(units, units[1:], strict=False):
local.append((anchor_of(left, "tail"), anchor_of(right, "head"), 1.0, "SINGLE"))
local.append((anchor_of(units[-1], "tail"), anchor_of(tail, "head"), 1.0, "SINGLE"))
problem = _valence(sorted(placed, key=lambda p: p.start), local)
if problem:
problems.append(f"chain {chain_index + 1} valence: {problem}")
# Sites (wrapped) and bond images from the unwrapped coordinates.
frac = xyz / lengths
wrap = np.zeros_like(frac, dtype=int)
for k in range(3):
if pbc[k]:
wrap[:, k] = np.floor(frac[:, k]).astype(int)
ids = []
for s, f, w in zip(chain_symbols, frac, wrap, strict=True):
counts[s] += 1
sid = f"{s}{counts[s]}"
ids.append(sid)
sites.append({"id": sid, "symbol": s, "fractional": [crystal._clean(x) for x in f - w]})
site_chain.append(chain_index)
for i, j, order, _ in local:
image = wrap[j] - wrap[i]
bonds.append(
{
"a": ids[i],
"b": ids[j],
"image": [int(x) for x in image],
"order": order,
"kind": "authored",
"order_source": "builder",
"rule": f"polymer chain {chain_index + 1}"[:200],
}
)
graph_bonds.append((offset + i, offset + j))
# The image length must be the unwrapped bond length.
cart = ((frac[j] - wrap[j] + image) - (frac[i] - wrap[i])) * lengths
ratio = float(np.linalg.norm(cart)) / _bond_length(chain_symbols[i], chain_symbols[j])
length_report["bonds"] += 1
length_report["image_bonds"] += int(any(image))
length_report["min_ratio"] = min(length_report["min_ratio"], ratio)
length_report["max_ratio"] = max(length_report["max_ratio"], ratio)
for p in placed:
expected.update(p.fragment.formula)
# Tacticity from the placed coordinates: (head-side, tail-side, side) volume signs.
signs: list[int] = []
for p in units:
for centre, before, after, side in p.fragment.stereo:
points = [_atom_at(placed, p, xyz, i) for i in (centre, before, after, side)]
signs.append(1 if _signed_volume(*points) > 0 else -1)
diads = ["m" if a == b else "r" for a, b in zip(signs, signs[1:], strict=False)]
meso = diads.count("m") / len(diads) if diads else None
if plan.tacticity is not None:
tacticity_report.append(
{"chain": chain_index + 1, "tacticity": plan.tacticity, "meso_fraction": meso}
)
if plan.tacticity == "isotactic" and diads and meso != 1:
problems.append(f"chain {chain_index + 1}: isotactic but {diads.count('r')} r")
if plan.tacticity == "syndiotactic" and diads and meso != 0:
problems.append(f"chain {chain_index + 1}: syndiotactic but {diads.count('m')} m")
residues = []
for p in placed:
n = len(p.fragment.symbols)
residues.append(
{
"kind": p.kind,
"residue": p.residue,
"unit": p.fragment.label,
"sites": ids[p.start : p.start + n],
"parent_atoms": list(p.fragment.real),
"mirror": p.mirror,
}
)
consumed = 2 * len(units)
records.append(
{
"index": chain_index,
"spec": plan.spec,
"label": plan.label,
"length": len(plan.sequence),
"sequence": plan.sequence,
"tacticity": plan.tacticity,
"meso_diad_fraction": meso,
"head": plan.head,
"tail": plan.tail,
"formula": crystal._json(dict(sorted(Counter(chain_symbols).items()))),
"sites": len(ids),
"connection_points_consumed": consumed + 2,
"unreacted_connection_points": 0,
"residues": residues,
}
)
# Topology: one component per chain, and no bond joins two chains.
roots = _components(len(sites), graph_bonds)
per_chain: dict[int, set[int]] = {}
for site, root in enumerate(roots):
per_chain.setdefault(site_chain[site], set()).add(root)
for chain_index, found in per_chain.items():
if len(found) != 1:
problems.append(f"chain {chain_index + 1} has {len(found)} components")
if len(set(roots)) != len(grown):
problems.append(f"{len(set(roots))} components for {len(grown)} chains")
cross = sum(1 for a, b in graph_bonds if site_chain[a] != site_chain[b])
if cross:
problems.append(f"{cross} bonds join different chains")
low, high = BOND_LENGTH_WINDOW
if length_report["bonds"] and not (
low <= length_report["min_ratio"] and length_report["max_ratio"] <= high
):
problems.append(
f"bond lengths {length_report['min_ratio']:.3f}-{length_report['max_ratio']:.3f} "
f"of the covalent sums fall outside {low}-{high}"
)
placed_counts = Counter(s["symbol"] for s in sites)
if +placed_counts != +expected:
problems.append(f"element count {dict(placed_counts)} differs from {dict(expected)}")
packed_mass = sum(sum(p.fragment.mass for p in placed) for _, placed, _ in grown)
density = packed_mass / (volume * 1e-24 * 6.02214076e23)
checks = {
"topology": {
"components": len(set(roots)),
"chains": len(grown),
"interchain_bonds": cross,
},
"valence": "rdkit sanitised every chain"
if not any("valence" in p for p in problems)
else "failed",
"bond_lengths": {
"bonds": int(length_report["bonds"]),
"image_bonds": int(length_report["image_bonds"]),
"min_ratio_to_covalent_sum": round(float(length_report["min_ratio"]), 4),
"max_ratio_to_covalent_sum": round(float(length_report["max_ratio"]), 4),
"window": list(BOND_LENGTH_WINDOW),
},
"stoichiometry": crystal._json(dict(sorted(placed_counts.items()))),
"tacticity": tacticity_report,
"density_g_cm3_unrelaxed": round(density, 6),
"problems": problems,
"equilibrated": False,
}
result["checks"] = checks
if problems:
refusals.append(_refusal("polymer.check_failed", "; ".join(problems)[:2000]))
return result
record = {
**record_base,
"cell": result["cell"],
"units": result["units"],
"requested_chains": len(plans),
"packed_chains": len(grown),
"partial": exhausted,
"attempts": growth.attempts,
"backtracks": growth.backtracks,
"regrowths": growth.regrowths,
"rejections": dict(sorted(growth.rejections.items())),
"radii": {"table": packing.radii, "values": radius},
"checks": checks,
"chains": records,
}
rows = np.diag(lengths)
data: dict[str, Any] = {
"id": packing.identifier,
"lattice_angstrom": rows.tolist(),
"pbc": list(pbc),
"sites": sites,
"bonds": bonds,
"charge": 0,
"multiplicity": 1,
"provenance": {"polymer": crystal._json(record)},
}
made = PeriodicStructure.model_validate(data)
provenance = dict(made.provenance)
provenance["polymer"] = {**record, "derived_sha256": content_digest(made)}
made = made.model_copy(update={"provenance": crystal._json(provenance)})
result.update(
{
"applicable": True,
"chains": [{k: v for k, v in r.items() if k != "residues"} for r in records],
"provenance": made.provenance["polymer"],
"derived": made.model_dump(mode="json", exclude_none=True),
}
)
return result
[docs]
def anchor_of(p: _Placed, which: Literal["head", "tail"]) -> int:
"""The chain-local index of a placement's head or tail anchor."""
point = p.fragment.head if which == "head" else p.fragment.tail
assert point is not None
return p.start + p.fragment.position(point[1])
def _atom_at(placed: list[_Placed], p: _Placed, xyz: np.ndarray, stand_in: int) -> np.ndarray:
"""Where stand-in atom ``stand_in`` of ``p`` is in the chain; a marker is the bonded atom."""
if stand_in in p.fragment.real:
return np.asarray(xyz[p.start + p.fragment.position(stand_in)])
at_head = stand_in == p.fragment.head[0]
neighbour = placed[placed.index(p) + (-1 if at_head else 1)]
which: Literal["head", "tail"] = "tail" if at_head and neighbour.kind == "unit" else "head"
return np.asarray(xyz[anchor_of(neighbour, which)])
[docs]
def chain_symbols_by(placed: list[_Placed]) -> list[str]:
"""The chain's atom symbols in chain-local order (by fragment start)."""
return [s for p in sorted(placed, key=lambda p: p.start) for s in p.fragment.symbols]
[docs]
def apply(document: Document, packing: PolymerPacking) -> Document:
"""Add the packed model to a copy of ``document``; refusals fail."""
from vibesketcher.document.periodic import with_periodic
if packing.identifier in {s.id for s in document.periodic_structures}:
raise ValueError(f"periodic structure {packing.identifier!r} already exists")
result = preview(packing, document)
if not result["applicable"]:
reasons = "; ".join(r["message"] for r in result["refusals"]) or "nothing packed"
raise ValueError(f"polymer packing refused: {reasons}")
return with_periodic(document, PeriodicStructure.model_validate(result["derived"]))
[docs]
def undo(document: Document, identifier: str) -> Document:
"""Remove a packed model again, if it is unchanged since it was packed."""
found = {s.id: s for s in document.periodic_structures}
structure = found.get(identifier)
if structure is None:
raise ValueError(f"periodic structure {identifier!r} not found")
record = structure.provenance.get("polymer")
if not isinstance(record, dict) or "derived_sha256" not in record:
raise ValueError(f"{identifier} is not a packed polymer model")
if record["derived_sha256"] != content_digest(structure):
raise ValueError(f"{identifier} changed after it was packed; undo refused")
data = document.to_json_data()
data["periodic_structures"] = [
s.model_dump(mode="json", exclude_none=True)
for s in document.periodic_structures
if s.id != identifier
]
return Document.model_validate(data)