Polymer builder#
The scm.structures.builder.polymer module joins monomers at named link points. Use a link table to choose
the next monomer according to the available links and their weights, or a sequence to describe a pattern along
the chain. Both approaches can build a copolymer.
Basic usage#
from scm.structures.builder.polymer import Monomer, build_polymer, homopolymer_links
styrene = Monomer.from_smiles("[*]CC([*])c1ccccc1")
monomers = {"styrene": styrene}
links = homopolymer_links(monomers, "styrene")
chain = build_polymer(monomers, links, 20, seed=1)
[*] marks a link point in the SMILES. The monomer key ("styrene") names the monomer type in link tables
and sequences; link-point names such as A and B identify positions within that monomer.
See the chain and copolymer example for link tables, sequences, tacticity, and branching. The periodic chain example and amorphous cell example cover other build modes.
Monomers and links#
- class Monomer(system: ChemicalSystem, link_points: Mapping[str, int], head: str | None = None, tail: str | None = None, kinds: Mapping[str, str | None] | None = None, caps: Mapping[str, str | Monomer | None] | None = None)#
A monomer: a chemical system with named link points.
link_pointsmaps each name to the index of a dummy atom (Xx). Each dummy atom must be bonded to exactly one atom, the attach atom. The system is copied, so changing it afterwards does not affect the monomer.The roles
headandtailname the link points through which the monomer joins a linear chain: the head bonds to the tail of the previous monomer. They are used by the sequences and the link helpers. With exactly two link points they default to the first and the second. All other link points are branch points.kindsgives the chemistry of link points (seekinds), only link points of kinds that react with each other can bond. Link points without a kind can bond to anything.capsgives the cap of link points that remain free, instead of the cap of the build function: an element, a group with one link point (e.g. a hydroxyl group to restore a carboxylic acid), or None to keep the dummy atom.- classmethod from_group(system: ChemicalSystem, attach: int) Monomer#
A group with one link point at atom
attach, e.g. a cap like a methyl group without its fourth bond.The link point (named
A) is added along the free valence: opposite to the bonds of the attach atom.
- classmethod from_smiles(smiles: str, names: Sequence[str] | None = None, head: str | None = None, tail: str | None = None) Monomer#
Create a monomer from SMILES, with
*marking the link points, e.g."[*]CC([*])c1ccccc1".The link points are named
A,B, … in the order they appear in the SMILES.
- classmethod from_system(system: ChemicalSystem, names: Sequence[str] | None = None, head: str | None = None, tail: str | None = None) Monomer#
Use all dummy atoms (
Xx) as link points, namedA,B, … in order of the atom index.This is the same naming as the link point labels in the GUI, e.g.
1Ais link pointAof monomer1. Optionally,namesgives other names in the same order.
- mirrored() Monomer#
The mirror image, e.g. to change the configuration of the stereocenters for tacticity.
- relaxed(max_iterations: int = 500, embed: bool = False) Monomer#
A copy with the geometry optimized with UFF.
During the optimization the link points are methyl groups (like
ChemicalSystem.from_smilesdoes), which mimic the next monomer. A monomer drawn by hand or from an unoptimized structure has distorted bond angles, which make the chains get stuck much more often. Withembedthe geometry is first made from scratch (RDKit embedding of the bonds), for a geometry that is far off, e.g. after opening a ring. If the optimization is not possible the monomer is returned unchanged.
- class LinkPoint(monomer: str, name: str)#
A link point of a monomer: the key of the monomer and the name of the link point.
- class Link(site: LinkPoint, incoming: LinkPoint, weight: float = 1.0)#
A directed link: a monomer may be attached with its
incominglink point at a freesiteof the chain.The weight is the relative probability of this link compared to the other links possible at that site. A weight of zero disables the link.
- class PolymerBuildError(message: str, system: ChemicalSystem | None = None)#
Raised when a polymer can not be built.
If the growth got stuck,
systemholds the partial result, with the unused link points still present as dummy atoms, so that it is possible to see where the growth got stuck.
- homopolymer_links(monomers: Mapping[str, Monomer], key: str, defects: float = 0.0) List[Link]#
Head-to-tail homopolymer, growing at both chain ends.
defectsis the relative weight of head-to-head and tail-to-tail links (regio defects), e.g. 0.05 for about 5% of the links.
- alternating_links(monomers: Mapping[str, Monomer], a: str, b: str) List[Link]#
Strictly alternating copolymer ABAB…
- statistical_links(monomers: Mapping[str, Monomer], fractions: Mapping[str, float]) List[Link]#
Statistical (random) copolymer: each new monomer is chosen with its fraction, independent of the chain end.
- copolymer_links(monomers: Mapping[str, Monomer], feed: Mapping[str, float], reactivity: Mapping[str, float] | Mapping[Tuple[str, str], float]) List[Link]#
Copolymer from the terminal model with reactivity ratios (Mayo-Lewis).
feedgives the fraction of each monomer in the feed. For two monomersreactivitycan be given as{"A": r_A, "B": r_B}, withr_A = k_AA / k_AB. For more monomers it maps pairs(X, Y)tor_XY = k_XX / k_XY. A chain ending in X then adds monomer Y with a probability proportional tofeed[Y] / r_XY, and X itself proportional tofeed[X].r_A * r_B = 1gives an ideal random copolymer, both close to zero an alternating one, and both large a blocky one.
- hyperbranched_links(monomers: Mapping[str, Monomer], key: str, focal: str | None = None) List[Link]#
Hyperbranched polymer from an AB_n monomer: the focal link point A bonds to any of the B link points.
focalis the A link point, by default the head of the monomer.
- tacticity_links(monomers: Mapping[str, Monomer], key: str, tacticity: Literal['isotactic', 'syndiotactic', 'atactic']) List[Link]#
Head-to-tail homopolymer with the given tacticity.
Syndiotactic and atactic chains use the mirror image of the monomer, so
monomersmust contain it askey + "*", seewith_mirror_images().
- with_mirror_images(monomers: Mapping[str, Monomer], keys: Sequence[str] | None = None) Dict[str, Monomer]#
Add the mirror image of monomers, with the key followed by
*, e.g."1*"for monomer"1".
- links_from_pairs(pairs: Iterable[Tuple[str | LinkPoint, str | LinkPoint, float]], both_directions: bool = True) List[Link]#
Create links where every link has its own weight.
Each pair
(a, b, weight)allows attaching link pointbof a new monomer at a free link pointa, and ifboth_directionsis set alsoaatb, both with the same weight.
- links_from_matrix(allowed: Iterable[Tuple[str | LinkPoint, str | LinkPoint]], monomer_weights: Mapping[str, float]) List[Link]#
Create links where the weight belongs to the incoming monomer.
Each allowed pair
(a, b)lets link pointsaandbbond in both directions. Attaching a new monomer uses the weight of that monomer frommonomer_weights, monomers without a weight get weight 1.
- links_from_kinds(monomers: Mapping[str, Monomer], monomer_weights: Mapping[str, float] | None = None, reactions: Iterable[str] | None = None) List[Link]#
Create all links that the kinds of the link points allow (see
kinds).Every pair of link points whose kinds react is linked, in both directions, also within one monomer (e.g. the acid and the alcohol of a hydroxy acid). Link points without a kind are left out, they would link to anything. Head-to-head and tail-to-tail links of vinyl monomers (regio defects) are not made. Like
links_from_matrix(), attaching a monomer uses its weight frommonomer_weights(default 1).reactionslimits the links to these reactions, e.g.["esterification"].
Sequences#
Sequence nodes can be nested. Repeat controls a block length, Seq joins blocks in order, and nodes such
as Choice or Gradient select monomers while the sequence is expanded. A distribution can supply a count
instead of a fixed integer.
- class Seq(nodes: Sequence[str | Node | Sequence[str | Node | Sequence[NodeLike]]])#
The nodes in order.
- class Repeat(node: str | Node | Sequence[NodeLike], count: int | Distribution)#
The node repeated
counttimes, the count can be aDistribution.
- class Choice(options: Mapping[str, float] | Sequence[Tuple[str | Node | Sequence[str | Node | Sequence[NodeLike]], float]])#
One of the nodes, chosen with probability proportional to the weight.
- class Markov(transitions: Mapping[str, Mapping[str, float]], count: int | Distribution, start: str | None = None)#
countmonomers where each is chosen depending on the previous one (a first order Markov chain).transitions[x][y]is the relative weight of monomer y following monomer x. The first monomer isstart, or chosen from the stationary distribution of the chain.
- class Gradient(a: str, b: str, count: int | Distribution, profile: Callable[[float], float] | None = None)#
countmonomers a or b, where the fraction of b goes from 0 to 1 along the chain.profilemaps the relative position (0 to 1) to the probability of b, by default linear.
- class Branch(at: str, node: str | Node | Sequence[NodeLike])#
A side chain growing from link point
atof the previous monomer, which then continues the main chain.
- class Star(core: str, arm: str | Node | Sequence[str | Node | Sequence[NodeLike]] | None = None, arms: Sequence[str | Node | Sequence[str | Node | Sequence[NodeLike]]] | None = None, at: Sequence[str] | None = None)#
A core monomer with an arm growing from each of the given link points (by default all of them).
Pass
armfor the same arm everywhere, orarmswith one node per link point.
- class Comb(backbone: str, side: str | Node | Sequence[NodeLike], count: int | Distribution, every: int = 1, probability: float = 1.0, at: str | None = None)#
A backbone of
countmonomers with side chains: a comb or graft polymer.After every
every-th backbone monomer a side chain grows from its branch pointat(by default its only branch point), with the givenprobability.sideis the sequence of a side chain.
- tactic(key: str, tacticity: Literal['isotactic', 'syndiotactic', 'atactic'], count: int | Distribution) Node#
countmonomers with the given tacticity, usingkey + "*"as the mirror image.See
with_mirror_images()to add the mirror image to the monomers.
Count distributions#
- class Distribution#
A distribution of positive integers, e.g. of chain or block lengths.
Building structures#
build_polymer builds one chain. build_polymers can grow multiple chains together in a periodic box;
Chain describes each requested chain. For an infinite one-dimensional chain, use
build_periodic_polymer.
- build_polymer(monomers: Mapping[str, Monomer] | Sequence[Monomer], links: Sequence[Link] | None = None, repeats: int | Distribution | None = None, *, sequence: str | Node | Sequence[str | Node | Sequence[NodeLike]] | None = None, start: str | None = None, **kwargs) ChemicalSystem#
Build one polymer chain, from a link table with
repeatsmonomers or from asequence.See
build_polymers()for the other arguments.
- class Chain(links: Sequence[Link] | None = None, repeats: int | Distribution | None = None, sequence: str | Node | Sequence[str | Node | Sequence[NodeLike]] | None = None, start: str | None = None, count: int = 1)#
Description of a chain: either a link table with a number of monomers, or a sequence.
- links, repeats:
Grow
repeatsmonomers (an int or a distribution) by randomly choosing from the links.- sequence:
Grow the monomers of a sequence, see
sequence.- start:
Links mode: key of the first monomer, by default the first one that can be added and grow further.
- count:
Number of chains like this, each sampled separately (repeats, random choices of the sequence).
- build_polymers(monomers: Mapping[str, Monomer] | Sequence[Monomer], chains: Sequence[Chain], *, box: float | Sequence[float] | None = None, density: float | None = None, growth_density: float | None = None, compress_steps: int = 5000, compress_temperature: float = 300.0, cap: str | Monomer | None = 'H', orient: OrientMethod = 'sterics', temperature: float = 0.0, seed: int | None = None, clash_scale: float = 0.6, fallback_clash_scale: float | None | str = 'auto', site_selection: SiteSelection = 'uniform', reserve_link_space: bool = True, max_tries: int = 30, backtrack: int = 3, max_backtracks: int = 200, crosslinks: Sequence[Link] | None = None, crosslink_distance: float = 5.0, max_crosslinks: int | None = None, regions: bool = True, optimize: Engine | None = None, optimize_iterations: int = 300, trajectory: str | Path | None = None, trajectory_every: int = 1, progress: ProgressCallback | None = None, progress_stage: Callable[[str], None] | None = None) ChemicalSystem#
Build one or more polymer chains, growing all chains at the same time.
- monomers:
The monomers by key. A sequence is keyed
"1","2", …, like the monomer numbers in the GUI.- chains:
What to build, see
Chain.- box, density:
Grow the chains in a periodic orthorhombic box:
boxgives the edge lengths in angstrom (one number for a cube), ordensityin g/cm^3 sizes a cubic box for the expected mass. Needed for more than one chain. Before growing, every edge of the growth box is checked to fit the largest diameter of each monomer the chains can use and of their cap groups, in any conformer, plus the clash clearance. For a box that is too small, use a larger growth box (orgrowth_density) and compress afterwards.- growth_density, compress_steps, compress_temperature:
Random growth jams below the density of a real melt, especially for bulky monomers. With
growth_densitythe chains are grown in a larger box at this density, and then compressed todensitywith molecular dynamics that deforms the lattice (compress_stepssteps of 0.5 fs atcompress_temperatureK, with theoptimizeengine or UFF), seecompress_polymer().- cap:
Element that replaces the remaining link points, a monomer with one link point that is attached there, or None to keep them as dummy atoms.
- orient, temperature:
How the dihedral around each new bond is chosen.
"sterics"and"forcefield"compute the energy of each dihedral for a dimer, from the overlap of the van der Waals spheres or from a UFF PES scan (runs AMS). Attemperature0 the dihedrals are tried from low to high energy, at a temperature in kelvin they are drawn from the Boltzmann distribution, which gives more realistic random coils."random"tries random dihedrals.- seed:
Seed for all random choices. None gives a different result every time.
- clash_scale:
Atoms of a new monomer may not come closer to other atoms than this fraction of the sum of their van der Waals radii. Atoms at most two bonds apart across the new bond are not checked.
- fallback_clash_scale:
If no placement of a monomer fits, even after backtracking, accept the best one if it fits with this smaller fraction. Random growth jams well below the density of a real melt, and crowded monomers (e.g. isobutylene) hardly fit in a single chain, so this leaves some close contacts: optimize the result.
"auto"uses 0.4, None never accepts close contacts.- site_selection:
Links mode:
"uniform"first picks a free link point and then a link for it, so the link weights are the probabilities at each chain end."weighted"picks from all links of all free link points at once.- reserve_link_space:
Model open link points as carbon during steric checks to leave room for the next monomer. Set to False to model them as hydrogen during growth, allowing more placements in crowded branches.
- max_tries, backtrack, max_backtracks:
After
max_triesconsecutive failed attempts, or when no link is possible, the lastbacktrackmonomers of the chain are removed and regrown (more if it gets stuck again at the same length). Gives up aftermax_backtracksbacktracks in total.backtrack=0disables backtracking.- crosslinks, crosslink_distance, max_crosslinks:
After the growth, bond free link points according to these links when their attach atoms are within
crosslink_distanceangstrom and their dummies point at each other, closest first. With compression (growth_density) this is done again in the compressed box, for link points whose caps point at each other, removing the caps: most pairs only come close there. At mostmax_crosslinksin total. The new bonds are strained, an optimization is recommended.- regions:
Put the atoms of each chain (if more than one) and of each type of monomer in a region.
- optimize, optimize_iterations:
Optionally optimize the final geometry, see
optimize_polymer().- trajectory, trajectory_every:
Optional
.rkffile or folder to which the growing polymer is written, everytrajectory_everyadded monomers, ending with the final result. A folder gets aframe_<n>.infile for every frame (1-based). An RKF trajectory stores the whole system for every frame, so it gets large for large polymers: write fewer frames, or use a folder and remove the frames that have been read.- progress:
Called as
progress(step, total, frame)after each added monomer, with the 1-based trajectory frame number if a frame was written, else None. Seeprint_progress().- progress_stage:
Called with a status message before growth, during force field scans, and before each enabled finishing stage.
Returns the polymer. Raises
PolymerBuildErrorif the chains can not be grown, with the partial result.
- build_periodic_polymer(monomers: Mapping[str, Monomer] | Sequence[Monomer], sequence: NodeLike, *, cap: str | Monomer | None = 'H', copies: int | None = None, max_copies: int = 4, tolerance: float = 1.0, clash_scale: float = 0.6, starts: int = 48, seed: int | None = None, regions: bool = True, optimize: Engine | None = None, optimize_iterations: int = 300, progress_stage: Callable[[str], None] | None = None) ChemicalSystem#
Build an infinite chain, periodic in one dimension, with the lattice vector along x.
- sequence:
The repeat unit, a linear sequence (no branches) of monomers with a head and a tail, e.g.
"1"or["A", "B"].- copies:
Number of copies of the sequence in the cell. By default the smallest number from 1 to
max_copiesfor which a periodic chain is found.- tolerance:
Largest accepted rotation in degrees between the first monomer and its periodic image. The rest is absorbed by the bond between the cells, an optimization (with the lattice) removes it.
- cap:
Element or group with one link point for the branch points of the monomers, or None to keep dummies.
- starts:
Number of starting points of the dihedral optimization.
- progress_stage:
Called with a status message before each attempt to fit the cell and before geometry optimization.
See
build_polymers()for the other arguments.
- check_periodic(monomers: Mapping[str, Monomer], sequence: NodeLike, cap: str | Monomer | None = None, optimize: Engine | None = None) None#
Raise a ValueError if no periodic chain is possible, without trying to build it.
A periodic chain needs a regular, linear sequence (see
is_regular()) of monomers with a head and a tail, and an optimization engine that supports one-dimensional periodicity (GFN-FF does not). A periodic chain may still not be found for a valid input, then the builder raises aPolymerBuildError.
- print_progress(step: int, total: int, frame: int | None) None#
Progress callback that prints machine readable lines, for following the build from another program.
Prints
POLYMER STEP <step>/<total>after each added monomer andPOLYMER FRAME <frame>once a frame has been written completely to the trajectory file.
Preparation and visualization#
These helpers optimize a built polymer, draw monomers or chains, or derive monomers and links from reactants.
- optimize_polymer(system: ChemicalSystem, engine: Engine = 'uff', max_iterations: int = 300, optimize_lattice: bool = False, name: str = 'polymer_optimization') ChemicalSystem#
Optimize the geometry of a polymer, and return the optimized system.
- engine:
"uff"or"gfnff", or PLAMS settings with the engine block, e.g.Settings({"ForceField": {...}}).- max_iterations:
The polymer only needs to be relaxed, so a result that is not fully converged is accepted.
- optimize_lattice:
Also optimize the lattice vectors of a periodic system.
- compress_polymer(system: ChemicalSystem, box: Sequence[float], engine: Engine = 'uff', steps: int = 5000, temperature: float = 300.0, timestep: float = 0.5, name: str = 'polymer_compression') ChemicalSystem#
Compress a periodic polymer to an orthorhombic box with molecular dynamics, deforming the lattice.
Growing chains at a high density jams, so chains are grown at a lower density and compressed afterwards.
stepsMD steps oftimestepfs attemperatureK, the lattice changes linearly toboxover the run. A short geometry optimization first removes close contacts.
- depict_monomers(monomers: Mapping[str, Monomer], *, size: Tuple[int, int] = (500, 300), legend: str = '', image_format: str = 'png', filename: str | None = None, transparent_background: bool = False)#
A 2D drawing of the monomers, with their link points labelled like in AMSinput, e.g.
1A.Set
transparent_backgroundto draw without a background.
- depict_polymer(monomers: Mapping[str, Monomer], sequence: str | Node | Sequence[NodeLike], *, cap: str | None = 'H', size: Tuple[int, int] = (500, 300), legend: str = '', image_format: str = 'png', filename: str | None = None, transparent_background: bool = False)#
A 2D drawing of the polymer that the sequence builds, as PNG bytes or an SVG string.
Each repeat is drawn once, in brackets with the number of repeats. A random choice is drawn as its options, each in brackets with its fraction. The stereochemistry of the monomers comes from their 3D geometry, so mirrored monomers (e.g. syndiotactic polymers) show the alternating wedges.
capis the element on the free branch points (a cap group is not drawn). Withfilenamethe image is also written to that file. Settransparent_backgroundto draw without a background.
- class Reactant(reactant: str | ChemicalSystem, name: str | None = None, templates: Sequence[SiteTemplate] | None = None)#
A complete molecule with its reactive sites, which can become a monomer.
- monomer(sites: Sequence[int | str] | None = None, relax: bool = True) Monomer#
The repeat unit with the chosen sites (indices or template names) as link points, by default the default sites. The link points are named
A,B, … in the order of the sites.relaxoptimizes the geometry with UFF (seeMonomer.relaxed()), the opened double bonds and rings need that.
- class ReactantPolymer(monomers: Dict[str, Monomer], links: List[Link], reactants: Dict[str, Reactant], sites: Dict[str, List[int]], report: str)#
The monomers and links made from reactants, see
polymer_from_reactants().
- find_sites(reactant: str | ChemicalSystem, templates: Sequence[SiteTemplate] | None = None) List[Site]#
All reactive sites in a reactant (SMILES or a ChemicalSystem with bonds and hydrogen atoms).
Overlapping sites are all returned, with their
conflicts, only one of them can be used.defaultmarks the sites thatReactant.monomer()uses when no sites are chosen.
- polymer_from_reactants(reactants: Sequence[str | ChemicalSystem | Reactant] | Mapping[str, str | ChemicalSystem | Reactant], sites: Mapping[str, Sequence[int | str]] | None = None, reactions: Sequence[str] | None = None, monomer_weights: Mapping[str, float] | None = None, relax: bool = True) ReactantPolymer#
Monomers and a link table from complete reactant molecules.
The reactants are SMILES, ChemicalSystems or
Reactant, as a list (named"1","2", …) or a dictionary with names. Each reactant uses its default sites, or the ones insites(by reactant name). If one of the reactants has epoxide groups, the primary amines of the others react with both hydrogens (an epoxy resin with a hardener forms a network). All links that the kinds allow are made, or only the givenreactions(seekinds.REACTIONS). Use the result withbuild.build_polymer()orbuild.build_polymers();reportdescribes the sites and reactions that are used.
- class MonomerDatabase(entries: List[MonomerEntry], path: Path | None = None)#
The entries of a monomer database, by name (any of
MonomerEntry.names, case insensitive).- get(name: str) MonomerEntry | None#
The entry with this name, else the first entry with this as one of its other names.
- search(text: str) List[MonomerEntry]#
The entries with all words of the text in one of their names.
- class MonomerEntry(name: str, polymer: str, other_names: ~typing.List[str] = <factory>, category: str = '', note: str = '', reactants: ~typing.List[~scm.structures.builder.polymer.database.ReactantSpec] = <factory>, unit: str | None = None, kinds: ~typing.Dict[str, str | None] = <factory>, caps: ~typing.Dict[str, str] = <factory>)#
A polymer in the database.
- load_monomer_database(path: str | Path | None = None) MonomerDatabase#
Read a monomer database (JSON), by default the one of AMS.