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.

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 count times, the count can be a Distribution.

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)#

count monomers 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 is start, or chosen from the stationary distribution of the chain.

class Gradient(a: str, b: str, count: int | Distribution, profile: Callable[[float], float] | None = None)#

count monomers a or b, where the fraction of b goes from 0 to 1 along the chain.

profile maps the relative position (0 to 1) to the probability of b, by default linear.

class Exact(counts: Mapping[str, int])#

Exactly the given number of each monomer, in random order.

class Branch(at: str, node: str | Node | Sequence[NodeLike])#

A side chain growing from link point at of 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 arm for the same arm everywhere, or arms with 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 count monomers with side chains: a comb or graft polymer.

After every every-th backbone monomer a side chain grows from its branch point at (by default its only branch point), with the given probability. side is the sequence of a side chain.

tactic(key: str, tacticity: Literal['isotactic', 'syndiotactic', 'atactic'], count: int | Distribution) → Node#

count monomers with the given tacticity, using key + "*" 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.

class Poisson(mean: float)#

Poisson distribution with the given mean, at least 1.

class Uniform(low: int, high: int)#

Uniform distribution between low and high, both included.

class Flory(mean: float)#

Most probable (Flory) distribution of chain lengths with the given number average, dispersity about 2.

class SchulzZimm(mean: float, dispersity: float)#

Schulz-Zimm distribution of chain lengths with the given number average and dispersity (Mw/Mn > 1).

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 repeats monomers or from a sequence.

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 repeats monomers (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: box gives the edge lengths in angstrom (one number for a cube), or density in 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 (or growth_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_density the chains are grown in a larger box at this density, and then compressed to density with molecular dynamics that deforms the lattice (compress_steps steps of 0.5 fs at compress_temperature K, with the optimize engine or UFF), see compress_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). At temperature 0 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_tries consecutive failed attempts, or when no link is possible, the last backtrack monomers of the chain are removed and regrown (more if it gets stuck again at the same length). Gives up after max_backtracks backtracks in total. backtrack=0 disables backtracking.

crosslinks, crosslink_distance, max_crosslinks:

After the growth, bond free link points according to these links when their attach atoms are within crosslink_distance angstrom 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 most max_crosslinks in 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 .rkf file or folder to which the growing polymer is written, every trajectory_every added monomers, ending with the final result. A folder gets a frame_<n>.in file 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. See print_progress().

progress_stage:

Called with a status message before growth, during force field scans, and before each enabled finishing stage.

Returns the polymer. Raises PolymerBuildError if 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_copies for 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 a PolymerBuildError.

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 and POLYMER 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. steps MD steps of timestep fs at temperature K, the lattice changes linearly to box over 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_background to 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. cap is the element on the free branch points (a cap group is not drawn). With filename the image is also written to that file. Set transparent_background to 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. relax optimizes the geometry with UFF (see Monomer.relaxed()), the opened double bonds and rings need that.

select(sites: Sequence[int | str] | None = None) → List[int]#

The indices of the sites: given by index or by template name (all sites of that template).

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. default marks the sites that Reactant.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 in sites (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 given reactions (see kinds.REACTIONS). Use the result with build.build_polymer() or build.build_polymers(); report describes 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.