vibe-sketcherDocumentation
Source code for vibesketcher.document.cnt_composites
"""Representative coated and disordered carbon nanotube fibre composites (#241).
A composite request names one nanotube (explicit chiral indices (n, m), with
optional concentric outer walls), a bounded bundle of copies of it, a cell
policy, a polymer (repeat units and one chain specification as in
:mod:`vibesketcher.document.polymer_packing`), an explicit composition and a
seed. The preview returns a *derived* periodic model under a new ID: the tubes,
then the polymer chains grown around them, with provenance that lists each
tube's and each chain's parent map, both seeds, the stated macroscopic
dimensions and the status "unrelaxed representative model". Nothing is stored
until the model is applied, and an applied composite can be undone while it is
unchanged (the contract of :mod:`vibesketcher.document.polymer_packing`).
Tubes. A ``periodic`` tube is the periodic nanotube cell of
:mod:`vibesketcher.chem.nanotube_cells` (the chiral-vector construction of
Saito, Dresselhaus and Dresselhaus, *Physical Properties of Carbon Nanotubes*,
1998, ch. 3) and runs through the cell along c, which is the fibre axis; c is
then a whole number of translation periods. A ``segment`` tube is the finite,
hydrogen-terminated tube of :mod:`vibesketcher.chem.nanostructures` and must fit
inside the cell with the stated gap to its own image.
Bundle. ``hexagonal`` places the tube axes on a triangular lattice of pitch
``2 R + gap``, where R is the outer-wall radius (atom centres) and ``gap`` the
stated intertube atom-centre separation (the default 3.4 angstrom is of the
order of the graphite interlayer spacing, 3.35 angstrom); the ``count`` lattice
points closest to the centre are taken, so incomplete shells are allowed. This
is the close-packed bundle of aligned tubes seen in single-wall rope
diffraction (A. Thess et al., *Science* 273, 483-487 (1996),
doi:10.1126/science.273.5274.483), stated here as geometry, not fitted.
``random`` draws each axis uniformly in a disc of the stated radius, a uniform
rotation about the axis and a uniform axial shift, and for segments a tilt with
cos(theta) uniform up to ``max_tilt_deg``; a draw closer than the gap to an
earlier tube (atom pairs by brute force, periodic images included) or with an
atom inside another tube's cylinder is rejected, and past ``max_attempts`` the
request is refused. A tilted tube cannot run through a periodic axis and is
refused for periodic tubes.
Cells. ``matrix`` is a fully periodic orthorhombic box with the bundle at its
centre; the polymer fills the space between the tubes and their images.
``coated_fibre`` is periodic along c only: a cylindrical coating shell of the
stated thickness around the bundle envelope (the largest radial atom distance
from the bundle axis), with vacuum outside; with ``infiltrate`` false the
polymer stays outside the envelope. The chains are grown by
:func:`vibesketcher.document.polymer_packing.preview` with the tube atoms as a
fixed :class:`~vibesketcher.document.polymer_packing.Inclusion`: a chain atom
may neither overlap a tube atom (the hard-core test of that module) nor lie
inside any tube's outer-wall cylinder, so exclusion is by distance to tube
atoms and by the tube interiors, not by boxes.
Composition. Exactly one of a chain count, a target composite density (tubes
plus polymer over the cell volume, or over the coated cylinder for a fibre)
or a polymer weight fraction sets the number of chains; the achieved values are
reported. Macroscopic dimensions (fibre diameters, coating thickness, tube
lengths) are recorded as labelled metadata; the atomistic cell is a
representative volume element, never the macroscopic object. Nothing is
relaxed, and no electrical, mechanical or biological property is inferred.
"""
from __future__ import annotations
import copy
import functools
import math
from collections import Counter
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 polymer_packing as pp
from vibesketcher.document.guest_loading import radius_of
from vibesketcher.document.model import Chirality, Document, PeriodicStructure
from vibesketcher.limits import MAX_ATOMS
NOTE = (
"An unrelaxed representative model: a nanotube bundle with polymer chains grown around it "
"at the stated composition. It is a representative volume element, not the macroscopic "
"fibre, and its geometry, density and contacts are not predictions; no electrical, "
"mechanical or biological property is inferred from it."
)
STATUS = "unrelaxed representative model"
METHOD = (
"bounded nanotube bundle (hexagonal lattice or seeded random placement with clash refusal) "
"and unit-by-unit self-avoiding polymer chain growth around the fixed tubes"
)
REFERENCES = [
"R. Saito, G. Dresselhaus and M. S. Dresselhaus, Physical Properties of Carbon Nanotubes "
"(1998), ch. 3",
"A. Thess et al., Science 273, 483 (1996), doi:10.1126/science.273.5274.483",
*pp.REFERENCES,
]
MAX_TUBES = 61
AVOGADRO = 6.02214076e23 # CODATA 2018, exact
CODES: dict[str, str] = {
"composite.tube_refused": "the nanotube cannot be built as stated",
"composite.tilt_periodic": "a tilted tube cannot run through a periodic axis; use segments",
"composite.cell_too_small": "the cell does not hold the bundle with the gap to its images",
"composite.segment_too_long": "a segment and the gap do not fit in the cell length",
"composite.length_unstated": "segment tubes need the cell length; periodic tubes set it",
"composite.disorder_exhausted": "random placement ran out of attempts before every tube fit",
"composite.tube_contact": "two tubes are closer than the stated gap",
"composite.density_below_inclusion": "the tubes alone reach the target density",
"composite.no_polymer": "the composition leaves no polymer chain",
"composite.too_many_sites": "the composite would exceed the site limit",
"composite.polymer_refused": "the polymer packing around the tubes was refused",
"composite.check_failed": "a brute-force composite check failed",
"composite.unrelaxed": "the model is an unrelaxed representative model",
"composite.no_properties": "no electrical, mechanical or biological property is inferred",
}
class _Model(BaseModel):
model_config = ConfigDict(extra="forbid")
[docs]
class TubeSpec(_Model):
"""The one nanotube every bundle member copies: (n, m) innermost, optional outer walls."""
n: int = Field(ge=1, le=40)
m: int = Field(default=0, ge=0, le=40)
outer_walls: list[Chirality] = Field(default_factory=list, max_length=4)
#: ``periodic``: through the cell along c; ``segment``: finite, hydrogen-terminated.
form: Literal["periodic", "segment"] = "periodic"
#: Translation periods of the innermost wall: per cell (periodic) or per segment.
periods: int = Field(default=4, ge=1, le=100)
@model_validator(mode="after")
def _ordered(self) -> Self:
if self.m > self.n:
raise ValueError(f"({self.n},{self.m}): write the indices with m <= n")
return self
[docs]
def walls(self) -> list[Chirality]:
return [Chirality(n=self.n, m=self.m), *self.outer_walls]
[docs]
class Bundle(_Model):
count: int = Field(default=1, ge=1, le=MAX_TUBES)
packing: Literal["hexagonal", "random"] = "hexagonal"
#: Intertube atom-centre separation (hexagonal: exact; random: minimum), angstrom.
gap_angstrom: float = Field(default=3.4, ge=2.0, le=50, allow_inf_nan=False)
#: Random: axes are drawn uniformly in a disc of this radius about the bundle axis.
radius_angstrom: float | None = Field(default=None, ge=0, le=300, allow_inf_nan=False)
#: Random segments: the largest tilt of a tube axis from c, degrees.
max_tilt_deg: float = Field(default=0.0, ge=0, le=30, allow_inf_nan=False)
max_attempts: int = Field(default=5000, ge=1, le=1_000_000)
@model_validator(mode="after")
def _random(self) -> Self:
if self.packing == "random" and self.radius_angstrom is None:
raise ValueError("a random bundle needs radius_angstrom")
if self.packing == "hexagonal" and (self.radius_angstrom is not None or self.max_tilt_deg):
raise ValueError("radius_angstrom and max_tilt_deg belong to a random bundle")
return self
[docs]
class CompositeCell(_Model):
kind: Literal["matrix", "coated_fibre"] = "matrix"
#: Matrix: the a and b edges (angstrom).
lateral_angstrom: tuple[float, float] | None = None
#: Segment tubes: the c edge (angstrom); periodic tubes set it.
length_angstrom: float | None = Field(default=None, ge=2, le=1000, allow_inf_nan=False)
#: Coated fibre: the coating thickness outside the bundle envelope (angstrom).
coating_thickness_angstrom: float | None = Field(
default=None, gt=0, le=200, allow_inf_nan=False
)
#: Coated fibre: whether chains may enter the bundle envelope between tubes.
infiltrate: bool = False
#: Coated fibre: vacuum outside the coating on each side (angstrom).
vacuum_angstrom: float = Field(default=10.0, ge=0, le=200, allow_inf_nan=False)
@model_validator(mode="after")
def _policy(self) -> Self:
if self.kind == "matrix":
if self.lateral_angstrom is None:
raise ValueError("a matrix cell needs lateral_angstrom (a, b)")
if any(not (math.isfinite(v) and 5 <= v <= 1000) for v in self.lateral_angstrom):
raise ValueError("lateral edges must be between 5 and 1000 angstrom")
if self.coating_thickness_angstrom is not None or self.infiltrate:
raise ValueError("coating_thickness_angstrom and infiltrate belong to a fibre")
else:
if self.lateral_angstrom is not None:
raise ValueError("a coated fibre's lateral size follows from the coating")
if self.coating_thickness_angstrom is None:
raise ValueError("a coated fibre needs coating_thickness_angstrom")
return self
[docs]
class Composition(_Model):
"""Exactly one of a chain count, a target composite density or a polymer weight fraction."""
chains: int | None = Field(default=None, ge=1, le=pp.MAX_CHAINS)
target_density_g_cm3: float | None = Field(default=None, gt=0, le=5, allow_inf_nan=False)
polymer_weight_fraction: float | None = Field(default=None, gt=0, lt=1, allow_inf_nan=False)
@model_validator(mode="after")
def _one(self) -> Self:
given = (self.chains, self.target_density_g_cm3, self.polymer_weight_fraction)
if sum(x is not None for x in given) != 1:
raise ValueError(
"give exactly one of chains, target_density_g_cm3 or polymer_weight_fraction"
)
return self
[docs]
class CompositePolymer(_Model):
"""The coating or matrix polymer: repeat units and one chain specification.
The chain's ``count`` is replaced by the number the composition sets. The
growth options are those of :class:`~vibesketcher.document.polymer_packing.PolymerPacking`.
"""
units: dict[str, pp.RepeatUnit] = Field(min_length=1, max_length=10)
chain: pp.ChainSpec
torsion_states: list[pp.TorsionState] = Field(
default_factory=lambda: list(pp._DEFAULT_STATES), min_length=1, max_length=12
)
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=pp.MAX_ATTEMPTS)
step_retries: int = Field(default=8, ge=1, le=100)
max_backtracks: int = Field(default=200, ge=0, le=100_000)
max_regrowths: int = Field(default=20, ge=0, le=10_000)
on_exhausted: Literal["refuse", "partial"] = "refuse"
@model_validator(mode="after")
def _single_lengths(self) -> Self:
if self.chain.lengths is not None:
raise ValueError("a composite chain takes one length (the count is derived)")
return self
[docs]
class MacroscopicDimension(_Model):
"""A labelled experimental dimension, recorded as metadata and never built."""
quantity: str = Field(min_length=1, max_length=120)
value: float = Field(gt=0, allow_inf_nan=False)
unit: Literal["nm", "um", "mm", "cm", "m"]
spread: float | None = Field(default=None, ge=0, allow_inf_nan=False)
source: str | None = Field(default=None, max_length=200)
note: str | None = Field(default=None, max_length=400)
[docs]
class CompositeRequest(_Model):
identifier: str
label: str | None = Field(default=None, max_length=1000)
tube: TubeSpec
bundle: Bundle = Field(default_factory=Bundle)
cell: CompositeCell
polymer: CompositePolymer
composition: Composition
seed: int = Field(ge=0, lt=2**63)
macroscopic: list[MacroscopicDimension] = Field(default_factory=list, max_length=20)
references: list[str] = Field(default_factory=list, max_length=20)
@field_validator("identifier")
@classmethod
def _id(cls, value: str) -> str:
return pp._identifier(value)
@model_validator(mode="after")
def _forms(self) -> Self:
if self.tube.form == "periodic" and self.cell.length_angstrom is not None:
raise ValueError("periodic tubes set the cell length; leave length_angstrom out")
return self
[docs]
def parse_composite(data: dict[str, Any]) -> CompositeRequest:
return TypeAdapter(CompositeRequest).validate_python(data)
def _refusal(code: str, message: str) -> dict[str, Any]:
return {"code": code, "message": message}
class _Refused(Exception):
def __init__(self, code: str, message: str) -> None:
super().__init__(message)
self.code = code
# Tubes ------------------------------------------------------------------------
class _Tube:
"""One template tube centred on the z axis: symbols, positions, bonds and its extent."""
def __init__(
self,
symbols: list[str],
xyz: np.ndarray,
bonds: list[tuple[int, int, float, np.ndarray]],
period: float | None,
record: list[dict[str, Any]],
) -> None:
self.symbols, self.xyz, self.bonds, self.period = symbols, xyz, bonds, period
self.walls = record
carbons = np.asarray([s == "C" for s in symbols])
self.radius = float(np.hypot(xyz[carbons, 0], xyz[carbons, 1]).max())
self.half_length = float(np.abs(xyz[:, 2]).max())
self.mass = float(sum(_mass(s) for s in symbols))
@functools.cache
def _mass(symbol: str) -> float:
from rdkit import Chem
from vibesketcher.elements import ATOMIC_NUMBER
return float(Chem.GetPeriodicTable().GetAtomicWeight(ATOMIC_NUMBER[symbol]))
def _template(spec: TubeSpec) -> _Tube:
"""The template tube, or :class:`_Refused` with the builder's reason."""
from vibesketcher.chem import nanostructures as nano
from vibesketcher.chem.periodic_geometry import BuildRefused
walls = spec.walls()
record = [nano.wall_properties(w) for w in walls]
if spec.form == "periodic":
from vibesketcher.chem.nanotube_cells import NanotubeRecipe, build_nanotube_cell
try:
cell = build_nanotube_cell(
NanotubeRecipe(
identifier="tube",
n=spec.n,
m=spec.m,
type="chiral",
outer_walls=list(spec.outer_walls),
periods=spec.periods,
)
)
except (BuildRefused, ValueError) as error:
raise _Refused("composite.tube_refused", str(error)) from None
lattice = np.asarray(cell.lattice_angstrom, dtype=float)
index = {s.id: k for k, s in enumerate(cell.sites)}
frac = np.asarray([s.fractional for s in cell.sites], dtype=float)
xyz = frac @ lattice
xyz[:, 0] -= lattice[0, 0] / 2
xyz[:, 1] -= lattice[1, 1] / 2
bonds = []
for b in cell.bonds:
i, j = index[b.a], index[b.b]
vector = xyz[j] + np.asarray(b.image, dtype=float) @ lattice - xyz[i]
bonds.append((i, j, float(b.order), vector))
return _Tube([s.symbol for s in cell.sites], xyz, bonds, float(lattice[2, 2]), record)
from vibesketcher.document.model import Nanotube
try:
model = nano._tube(
Nanotube(kind="nanotube", walls=walls, periods=spec.periods, ends=("H", "H"))
)
except (nano.NanostructureRefused, BuildRefused, ValueError) as error:
raise _Refused("composite.tube_refused", str(error)) from None
xyz = np.asarray(model.positions, dtype=float)
xyz -= xyz.mean(axis=0)
bonds = [(i, j, float(order), xyz[j] - xyz[i]) for i, j, order in model.bonds]
return _Tube(list(model.symbols), xyz, bonds, None, record)
def _delta(d: np.ndarray, lengths: np.ndarray, pbc: tuple[bool, bool, bool]) -> np.ndarray:
out = np.array(d, dtype=float)
for k in range(3):
if pbc[k]:
out[..., k] -= lengths[k] * np.round(out[..., k] / lengths[k])
return out
class _Placed:
"""A placed copy of the template: its centre, axis, turn, shift and atom positions."""
def __init__(
self,
tube: _Tube,
centre: np.ndarray,
azimuth: float,
shift: float,
tilt: float,
tilt_azimuth: float,
) -> None:
self.centre, self.azimuth, self.shift = centre, azimuth, shift
self.tilt, self.tilt_azimuth = tilt, tilt_azimuth
turn = pp._rotation_about(np.asarray([0.0, 0, 1]), azimuth)
axis = np.asarray(
[
math.sin(tilt) * math.cos(tilt_azimuth),
math.sin(tilt) * math.sin(tilt_azimuth),
math.cos(tilt),
]
)
tip = pp._align(np.asarray([0.0, 0, 1]), axis)
self.rotation = tip @ turn
self.axis = axis
self.xyz = tube.xyz @ self.rotation.T + centre + np.asarray([0, 0, shift])
self.radius, self.half_length = tube.radius, tube.half_length
self.periodic = tube.period is not None
def inside(
self, points: np.ndarray, lengths: np.ndarray, pbc: tuple[bool, bool, bool]
) -> np.ndarray:
"""Which points lie inside this tube's outer-wall cylinder (periodic images included)."""
d = _delta(points - (self.centre + np.asarray([0, 0, self.shift])), lengths, pbc)
if self.periodic:
return np.asarray(np.hypot(d[..., 0], d[..., 1]) < self.radius)
along = d @ self.axis
radial = np.linalg.norm(d - along[..., None] * self.axis, axis=-1)
return np.asarray((np.abs(along) <= self.half_length) & (radial < self.radius))
def _min_distance(
a: np.ndarray, b: np.ndarray, lengths: np.ndarray, pbc: tuple[bool, bool, bool]
) -> float:
best = math.inf
for start in range(0, len(a), 512):
d = _delta(a[start : start + 512, None, :] - b[None, :, :], lengths, pbc)
best = min(best, float(np.sqrt(np.einsum("ijk,ijk->ij", d, d)).min()))
return best
def _hexagonal(count: int, pitch: float) -> list[np.ndarray]:
"""The ``count`` triangular-lattice points nearest the origin, centred on their mean."""
reach = int(math.ceil(math.sqrt(count))) + 2
a1, a2 = np.asarray([pitch, 0.0]), np.asarray([pitch / 2, pitch * math.sqrt(3) / 2])
points = [i * a1 + j * a2 for i in range(-reach, reach + 1) for j in range(-reach, reach + 1)]
points.sort(
key=lambda p: (round(float(np.hypot(*p)), 6), round(math.atan2(p[1], p[0]) % math.tau, 6))
)
chosen = np.asarray(points[:count])
chosen -= chosen.mean(axis=0)
return [np.asarray([x, y, 0.0]) for x, y in chosen]
def _bundle(
request: CompositeRequest,
tube: _Tube,
lengths_of: Any,
rng: np.random.Generator,
) -> tuple[list[_Placed], int]:
"""Placed tubes about the origin of the bundle frame, and the attempts used.
``lengths_of`` gives the cell lengths and periodic axes for the contact test
(lateral sizes are not known before a coated fibre's bundle is placed).
"""
bundle = request.bundle
gap = bundle.gap_angstrom
if bundle.packing == "hexagonal":
centres = _hexagonal(bundle.count, 2 * tube.radius + gap)
return [_Placed(tube, c, 0.0, 0.0, 0.0, 0.0) for c in centres], 0
if bundle.max_tilt_deg and tube.period is not None:
raise _Refused(
"composite.tilt_periodic",
f"max_tilt_deg {bundle.max_tilt_deg}: a periodic tube runs along c and cannot tilt; "
"use segment tubes for tilt disorder",
)
assert bundle.radius_angstrom is not None
lengths, pbc = lengths_of
placed: list[_Placed] = []
attempts = 0
cos_max = math.cos(math.radians(bundle.max_tilt_deg))
while len(placed) < bundle.count:
if attempts >= bundle.max_attempts:
raise _Refused(
"composite.disorder_exhausted",
f"placed {len(placed)} of {bundle.count} tubes in {attempts} attempts within a "
f"{bundle.radius_angstrom} A disc at a {gap} A gap",
)
attempts += 1
r = bundle.radius_angstrom * math.sqrt(float(rng.random()))
phi = float(rng.uniform(0, math.tau))
centre = np.asarray([r * math.cos(phi), r * math.sin(phi), 0.0])
azimuth = float(rng.uniform(0, math.tau))
shift = float(rng.uniform(0, tube.period if tube.period else 1.0))
if tube.period is None:
shift = 0.0
tilt = math.acos(1 - float(rng.random()) * (1 - cos_max)) if bundle.max_tilt_deg else 0.0
tilt_azimuth = float(rng.uniform(0, math.tau)) if bundle.max_tilt_deg else 0.0
trial = _Placed(tube, centre, azimuth, shift, tilt, tilt_azimuth)
if all(_apart(trial, other, gap, lengths, pbc) for other in placed):
placed.append(trial)
return placed, attempts
def _apart(
a: _Placed, b: _Placed, gap: float, lengths: np.ndarray, pbc: tuple[bool, bool, bool]
) -> bool:
if a.tilt == 0 and b.tilt == 0:
# Parallel axes: every atom lies within R of its axis, so the axis distance
# bounds the atom distance from below (and an axis inside the other tube fails).
d = _delta((a.centre - b.centre)[None, :], lengths, pbc)[0]
apart = float(np.hypot(d[0], d[1]))
if apart < max(a.radius, b.radius):
return False
if apart - a.radius - b.radius >= gap:
return True
if a.inside(b.xyz, lengths, pbc).any() or b.inside(a.xyz, lengths, pbc).any():
return False
return _min_distance(a.xyz, b.xyz, lengths, pbc) >= gap
# Preview, apply, undo ------------------------------------------------------------
def _chain_estimate(
request: CompositeRequest, document: Document | None
) -> tuple[float, int, set[str]]:
"""Mass and site count of one chain (expected over a random composition), and its elements."""
spec = request.polymer.chain
fragments = {
label: pp._unit(document, label, request.polymer.units[label])
for label in sorted(spec.units_named())
if label in request.polymer.units
}
missing = spec.units_named() - set(request.polymer.units)
if missing:
raise pp.PolymerRefused("polymer.unit_unknown", f"undefined repeat units {sorted(missing)}")
ends = [pp._end(spec.head), pp._end(spec.tail)]
length = spec.chain_lengths()[0]
if spec.unit is not None:
weights = {spec.unit: 1.0}
elif spec.sequence is not None:
weights = {k: v / len(spec.sequence) for k, v in Counter(spec.sequence).items()}
else:
assert spec.composition is not None
total = sum(spec.composition.values())
weights = {k: v / total for k, v in spec.composition.items()}
mass = length * sum(w * fragments[k].mass for k, w in weights.items())
sites = length * sum(w * len(fragments[k].symbols) for k, w in weights.items())
mass += sum(e.mass for e in ends)
sites += sum(len(e.symbols) for e in ends)
symbols = {s for f in [*fragments.values(), *ends] for s in f.symbols}
return mass, int(math.ceil(sites)), symbols
[docs]
def preview(request: CompositeRequest, document: Document | None = None) -> dict[str, Any]:
"""The composite model, its tubes, chains, composition, checks and refusals; nothing stored."""
refusals: list[dict[str, Any]] = []
notices = [
_refusal("composite.unrelaxed", NOTE),
_refusal("composite.no_properties", CODES["composite.no_properties"]),
]
seeds = np.random.SeedSequence(request.seed).spawn(2)
polymer_seed = int(seeds[1].generate_state(1, np.uint64)[0]) % 2**63
record_base: dict[str, Any] = {
"operation": "build_cnt_composite",
"method": METHOD,
"references": REFERENCES,
"parameters": request.model_dump(mode="json", exclude={"identifier"}),
"status": STATUS,
"note": NOTE,
"seeds": {
"request": request.seed,
"tube_placement": "numpy SeedSequence(seed).spawn(2)[0], PCG64",
"polymer": polymer_seed,
},
"macroscopic": {
"dimensions": [
d.model_dump(mode="json", exclude_none=True) for d in request.macroscopic
],
"representation": "labelled metadata; the atomistic cell is a representative volume "
"element, not the macroscopic fibre",
"references": list(request.references),
},
"properties_inferred": [],
}
result: dict[str, Any] = {
"identifier": request.identifier,
"applicable": False,
"status": STATUS,
"refusals": refusals,
"notices": notices,
"tubes": [],
"bundle": {},
"composition": {},
"polymer": {},
"checks": {},
"cell": None,
"provenance": record_base,
"derived": None,
"codes": {**CODES, **pp.CODES},
"note": NOTE,
}
try:
tube = _template(request.tube)
chain_mass, chain_sites, chain_symbols = _chain_estimate(request, document)
except _Refused as error:
refusals.append(_refusal(error.code, str(error)))
return result
except pp.PolymerRefused as error:
refusals.append(_refusal(error.code, str(error)))
return result
gap = request.bundle.gap_angstrom
cell = request.cell
if tube.period is not None:
c = tube.period
elif cell.length_angstrom is None:
refusals.append(_refusal("composite.length_unstated", CODES["composite.length_unstated"]))
return result
else:
c = cell.length_angstrom
# The contact test during placement: periodic along c (and laterally for a matrix).
if cell.kind == "matrix":
assert cell.lateral_angstrom is not None
a, b = cell.lateral_angstrom
lengths = np.asarray([a, b, c], dtype=float)
pbc: tuple[bool, bool, bool] = (True, True, True)
else:
lengths = np.asarray([1e6, 1e6, c], dtype=float)
pbc = (False, False, True)
rng = np.random.Generator(np.random.PCG64(seeds[0]))
try:
placed, attempts = _bundle(request, tube, (lengths, pbc), rng)
except _Refused as error:
refusals.append(_refusal(error.code, str(error)))
return result
tube_xyz = np.vstack([p.xyz for p in placed])
if tube.period is None and float(np.ptp(tube_xyz[:, 2])) + gap > c:
refusals.append(
_refusal(
"composite.segment_too_long",
f"the tubes span {float(np.ptp(tube_xyz[:, 2])):.3f} A along c; with the "
f"{gap} A gap they need c >= {float(np.ptp(tube_xyz[:, 2])) + gap:.3f} A, "
f"not {c:.3f} A",
)
)
return result
envelope = float(np.hypot(tube_xyz[:, 0], tube_xyz[:, 1]).max())
if cell.kind == "matrix":
span = np.ptp(tube_xyz[:, :2], axis=0) + gap
if span[0] > lengths[0] or span[1] > lengths[1]:
refusals.append(
_refusal(
"composite.cell_too_small",
f"the bundle spans {span.round(3).tolist()} A with the {gap} A gap; the "
f"cell is {lengths[:2].round(3).tolist()} A",
)
)
return result
offset = np.asarray([lengths[0] / 2, lengths[1] / 2, c / 2])
lower, upper = np.zeros(3), lengths.copy()
volume = float(np.prod(lengths))
outer = None
else:
assert cell.coating_thickness_angstrom is not None
outer = envelope + cell.coating_thickness_angstrom
side = 2 * (outer + cell.vacuum_angstrom)
lengths = np.asarray([side, side, c], dtype=float)
offset = np.asarray([side / 2, side / 2, c / 2])
lower = np.asarray([side / 2 - outer, side / 2 - outer, 0.0])
upper = np.asarray([side / 2 + outer, side / 2 + outer, c])
volume = math.pi * outer**2 * c
if tube.period is not None:
offset[2] = 0.0
for p in placed:
p.centre = p.centre + offset
p.xyz = p.xyz + offset
tube_xyz = tube_xyz + offset
# Brute-force tube contacts in the final cell (periodic images included).
closest = math.inf
for i, first in enumerate(placed):
for second in placed[i + 1 :]:
closest = min(closest, _min_distance(first.xyz, second.xyz, lengths, pbc))
if closest < gap - 1e-6:
refusals.append(
_refusal(
"composite.tube_contact",
f"tube atoms come within {closest:.3f} A, closer than the {gap} A gap",
)
)
return result
tube_mass = tube.mass * len(placed)
composition = request.composition
if composition.chains is not None:
chains = composition.chains
elif composition.target_density_g_cm3 is not None:
total = composition.target_density_g_cm3 * volume * 1e-24 * AVOGADRO
if total <= tube_mass:
refusals.append(
_refusal(
"composite.density_below_inclusion",
f"the tubes alone give {tube_mass / (volume * 1e-24 * AVOGADRO):.4f} g/cm3, "
f"at or above the target {composition.target_density_g_cm3} g/cm3",
)
)
return result
chains = int((total - tube_mass) // chain_mass)
else:
w = composition.polymer_weight_fraction
assert w is not None
chains = int(round(w / (1 - w) * tube_mass / chain_mass))
sites_planned = len(tube.symbols) * len(placed) + chains * chain_sites
result["cell"] = {
"kind": cell.kind,
"lengths_angstrom": [round(float(x), 6) for x in lengths],
"pbc": list(pbc),
"fibre_axis": "c",
"volume_angstrom3": round(volume, 6),
"volume_basis": "the whole cell" if cell.kind == "matrix" else "the coated cylinder",
"bundle_envelope_radius_angstrom": round(envelope, 6),
**({"coating_outer_radius_angstrom": round(outer, 6)} if outer is not None else {}),
}
result["bundle"] = {
"count": len(placed),
"packing": request.bundle.packing,
"gap_angstrom": gap,
"pitch_angstrom": round(2 * tube.radius + gap, 6)
if request.bundle.packing == "hexagonal"
else None,
"placement_attempts": attempts,
"closest_intertube_atoms_angstrom": round(closest, 6) if len(placed) > 1 else None,
}
if chains < 1:
refusals.append(_refusal("composite.no_polymer", CODES["composite.no_polymer"]))
return result
if sites_planned > MAX_ATOMS:
refusals.append(
_refusal(
"composite.too_many_sites",
f"{len(tube.symbols) * len(placed)} tube and about {chains * chain_sites} polymer "
f"sites exceed {MAX_ATOMS}",
)
)
return result
def forbidden(points: np.ndarray) -> np.ndarray:
hit = np.zeros(len(points), dtype=bool)
for p in placed:
hit |= p.inside(points, lengths, pbc)
if outer is not None:
radial = np.hypot(points[:, 0] - offset[0], points[:, 1] - offset[1])
hit |= radial > outer
if not cell.infiltrate:
hit |= radial < envelope
return hit
inclusion = pp.Inclusion(
label=f"cnt {cell.kind}",
lengths=lengths,
pbc=pbc,
lower=lower,
upper=upper,
volume=volume,
symbols=tube.symbols * len(placed),
xyz=tube_xyz,
forbidden=forbidden,
)
polymer = request.polymer
packing = pp.PolymerPacking(
identifier=request.identifier,
units=polymer.units,
chains=[polymer.chain.model_copy(update={"count": chains})],
seed=polymer_seed,
cell=pp.Cell(lengths_angstrom=(float(lengths[0]), float(lengths[1]), float(lengths[2])))
if all(1 <= x <= 1000 for x in lengths)
else pp.Cell(lengths_angstrom=(10.0, 10.0, 10.0)),
torsion_states=polymer.torsion_states,
torsion_jitter_deg=polymer.torsion_jitter_deg,
radii=polymer.radii,
radius_overrides=polymer.radius_overrides,
collision_scale=polymer.collision_scale,
max_attempts=polymer.max_attempts,
step_retries=polymer.step_retries,
max_backtracks=polymer.max_backtracks,
max_regrowths=polymer.max_regrowths,
on_exhausted=polymer.on_exhausted,
)
grown = pp.preview(packing, document, inclusion=inclusion)
result["polymer"] = {
k: grown[k]
for k in (
"requested_chains",
"packed_chains",
"attempts",
"backtracks",
"regrowths",
"rejections",
"units",
)
}
notices += [n for n in grown["notices"] if n["code"] != "polymer.unrelaxed"]
if not grown["applicable"]:
for r in grown["refusals"]:
refusals.append(_refusal(r["code"], r["message"]))
refusals.append(_refusal("composite.polymer_refused", CODES["composite.polymer_refused"]))
result["checks"] = {"polymer": grown["checks"]}
return result
return _assemble(
request, result, record_base, placed, tube, grown, lengths, pbc, volume, forbidden
)
def _assemble(
request: CompositeRequest,
result: dict[str, Any],
record_base: dict[str, Any],
placed: list[_Placed],
tube: _Tube,
grown: dict[str, Any],
lengths: np.ndarray,
pbc: tuple[bool, bool, bool],
volume: float,
forbidden: Any,
) -> dict[str, Any]:
"""Join the tubes and the grown chains in one derived structure, and check it."""
refusals: list[dict[str, Any]] = result["refusals"]
polymer_made = PeriodicStructure.model_validate(grown["derived"])
counts: Counter[str] = Counter()
sites: list[dict[str, Any]] = []
bonds: list[dict[str, Any]] = []
tube_records = []
for number, p in enumerate(placed):
frac = p.xyz / lengths
wrapped = frac.copy()
for k in range(3):
if pbc[k]:
wrapped[:, k] -= np.floor(wrapped[:, k])
wrapped[:, k] = np.where(wrapped[:, k] >= 1 - 1e-12, 0.0, wrapped[:, k])
ids = []
for s, f in zip(tube.symbols, wrapped, strict=True):
counts[s] += 1
ids.append(f"{s}{counts[s]}")
sites.append({"id": ids[-1], "symbol": s, "fractional": [crystal._clean(x) for x in f]})
for i, j, order, vector in tube.bonds:
moved = p.rotation @ vector
image = np.round((wrapped[i] * lengths + moved) / lengths - wrapped[j]).astype(int)
image[~np.asarray(pbc)] = 0
bonds.append(
{
"a": ids[i],
"b": ids[j],
"image": [int(x) for x in image],
"order": order,
"kind": "authored",
"order_source": "builder",
"rule": f"nanotube {number + 1}",
}
)
tube_records.append(
{
"index": number,
"walls": tube.walls,
"form": request.tube.form,
"centre_angstrom": [round(float(x), 6) for x in p.centre],
"axis": [round(float(x), 6) for x in p.axis],
"tilt_deg": round(math.degrees(p.tilt), 6),
"azimuth_deg": round(math.degrees(p.azimuth), 6),
"axial_shift_angstrom": round(p.shift, 6),
"outer_radius_angstrom": round(tube.radius, 6),
"half_length_angstrom": None if p.periodic else round(tube.half_length, 6),
"sites": ids,
"parent_atoms": f"template tube atoms 0..{len(tube.symbols) - 1}, in order",
"formula": crystal._json(dict(sorted(Counter(tube.symbols).items()))),
}
)
tube_sites = len(sites)
rename: dict[str, str] = {}
for site in polymer_made.sites:
counts[site.symbol] += 1
rename[site.id] = f"{site.symbol}{counts[site.symbol]}"
sites.append(
{"id": rename[site.id], "symbol": site.symbol, "fractional": list(site.fractional)}
)
for bond in polymer_made.bonds:
dumped = bond.model_dump(mode="json", exclude_none=True)
bonds.append({**dumped, "a": rename[bond.a], "b": rename[bond.b]})
polymer_record = dict(grown["provenance"])
polymer_record.pop("derived_sha256", None)
polymer_record["chains"] = [
{
**chain,
"residues": [
{**r, "sites": [rename[s] for s in r["sites"]]} for r in chain["residues"]
],
}
for chain in polymer_record["chains"]
]
# Brute-force checks over the joined model.
problems: list[str] = []
all_frac = np.asarray([s["fractional"] for s in sites], dtype=float)
xyz = all_frac * lengths
tube_xyz, chain_xyz = xyz[:tube_sites], xyz[tube_sites:]
symbols = [s["symbol"] for s in sites]
polymer = request.polymer
radius = {
s: radius_of(s, polymer.radii, polymer.radius_overrides) for s in sorted(set(symbols))
}
tube_r = np.asarray([radius[s] for s in symbols[:tube_sites]])
chain_r = np.asarray([radius[s] for s in symbols[tube_sites:]])
lowest = math.inf
for start in range(0, len(chain_xyz), 256):
d = _delta(chain_xyz[start : start + 256, None, :] - tube_xyz[None, :, :], lengths, pbc)
dist = np.sqrt(np.einsum("ijk,ijk->ij", d, d))
ratio = dist / (chain_r[start : start + 256, None] + tube_r[None, :])
lowest = min(lowest, float(ratio.min()))
if lowest < polymer.collision_scale - 1e-9:
problems.append(f"a polymer atom overlaps a tube atom ({lowest:.4f} of the radius sum)")
inside = int(np.count_nonzero(forbidden(chain_xyz))) if len(chain_xyz) else 0
if inside:
problems.append(f"{inside} polymer atoms lie inside a tube or outside the coating")
tube_ids = {s["id"] for s in sites[:tube_sites]}
crossing = sum(1 for b in bonds if (b["a"] in tube_ids) != (b["b"] in tube_ids))
if crossing:
problems.append(f"{crossing} bonds join a tube and a chain")
expected = Counter(tube.symbols * len(placed)) + Counter(s.symbol for s in polymer_made.sites)
placed_counts = Counter(symbols)
if placed_counts != expected:
problems.append(f"element count {dict(placed_counts)} differs from {dict(expected)}")
tube_mass = tube.mass * len(placed)
polymer_mass = float(sum(_mass(s.symbol) for s in polymer_made.sites))
density = (tube_mass + polymer_mass) / (volume * 1e-24 * AVOGADRO)
composition = {
"tubes": len(placed),
"tube_formula": crystal._json(dict(sorted(Counter(tube.symbols).items()))),
"tube_mass_g_mol": round(tube_mass, 4),
"chains": grown["packed_chains"],
"requested_chains": grown["requested_chains"],
"polymer_mass_g_mol": round(polymer_mass, 4),
"cnt_weight_fraction": round(tube_mass / (tube_mass + polymer_mass), 6),
"polymer_weight_fraction": round(polymer_mass / (tube_mass + polymer_mass), 6),
"density_g_cm3_unrelaxed": round(density, 6),
"target": request.composition.model_dump(mode="json", exclude_none=True),
"formula": crystal._json(dict(sorted(placed_counts.items()))),
}
checks = {
"min_polymer_tube_ratio_to_radius_sum": round(lowest, 6),
"collision_scale": polymer.collision_scale,
"polymer_atoms_in_forbidden_interiors": inside,
"tube_chain_bonds": crossing,
"stoichiometry": composition["formula"],
"polymer": grown["checks"],
"problems": problems,
"relaxed": False,
}
result.update({"composition": composition, "checks": checks, "tubes": tube_records})
if problems:
refusals.append(_refusal("composite.check_failed", "; ".join(problems)[:2000]))
return result
record = {
**record_base,
"cell": result["cell"],
"bundle": result["bundle"],
"tubes": tube_records,
"polymer": polymer_record,
"composition": composition,
"checks": checks,
}
data: dict[str, Any] = {
"id": request.identifier,
"lattice_angstrom": np.diag(lengths).tolist(),
"pbc": list(pbc),
"sites": sites,
"bonds": bonds,
"charge": 0,
"multiplicity": 1,
"provenance": {"composite": crystal._json(record)},
}
made = PeriodicStructure.model_validate(data)
provenance: dict[str, Any] = dict(made.provenance)
provenance["composite"] = {**record, "derived_sha256": pp.content_digest(made)}
made = made.model_copy(update={"provenance": crystal._json(provenance)})
result.update(
{
"applicable": True,
"tubes": [{k: v for k, v in t.items() if k != "sites"} for t in tube_records],
"provenance": made.provenance["composite"],
"derived": made.model_dump(mode="json", exclude_none=True),
}
)
return result
[docs]
def apply(document: Document, request: CompositeRequest) -> Document:
"""Add the composite model to a copy of ``document``; refusals fail."""
from vibesketcher.document.periodic import with_periodic
if request.identifier in {s.id for s in document.periodic_structures}:
raise ValueError(f"periodic structure {request.identifier!r} already exists")
result = preview(request, document)
if not result["applicable"]:
reasons = "; ".join(r["message"] for r in result["refusals"]) or "nothing built"
raise ValueError(f"CNT composite refused: {reasons}")
return with_periodic(document, PeriodicStructure.model_validate(result["derived"]))
[docs]
def undo(document: Document, identifier: str) -> Document:
"""Remove a composite model again, if it is unchanged since it was built."""
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("composite")
if not isinstance(record, dict) or "derived_sha256" not in record:
raise ValueError(f"{identifier} is not a CNT composite model")
if record["derived_sha256"] != pp.content_digest(structure):
raise ValueError(f"{identifier} changed after it was built; 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)
# Representative examples -----------------------------------------------------------
_ILLUSTRATIVE = (
"illustrative atomistic parameters: the tube indices, bundle size, cell, chain length "
"and packing density are chosen to keep the model small; they are not taken from the "
"paper or its SI"
)
def _dimension(quantity: str, value: float, unit: str, source: str, **extra: Any) -> dict[str, Any]:
return {"quantity": quantity, "value": value, "unit": unit, "source": source, **extra}
#: Requests tied to the issue's sources. Macroscopic dimensions are quoted from the
#: papers' experimental sections; every atomistic parameter is illustrative.
EXAMPLES: dict[str, dict[str, Any]] = {
"hnbr-coated-microcable": {
"identifier": "hnbr-coated-cnt",
"label": "HNBR-coated MWCNT fibre section (coated microcable); " + _ILLUSTRATIVE,
"tube": {"n": 5, "m": 5, "outer_walls": [{"n": 10, "m": 10}], "periods": 4},
"bundle": {"count": 3, "packing": "hexagonal", "gap_angstrom": 3.4},
"cell": {"kind": "coated_fibre", "coating_thickness_angstrom": 7.0},
"polymer": {
# HNBR: hydrogenated 1,4-butadiene and acrylonitrile units; the 49 % ACN mass
# content quoted for Zetpol 2000 is about 0.50 as a unit fraction.
"units": {"HB": {"smiles": "*CCCC*"}, "ACN": {"smiles": "[*:1]CC([*:2])C#N"}},
"chain": {
"composition": {"HB": 0.5, "ACN": 0.5},
"arrangement": "random",
"length": 4,
"tacticity": "atactic",
},
},
"composition": {"chains": 6},
"seed": 2014,
"macroscopic": [
_dimension(
"coated fibre diameter",
26.54,
"um",
"doi:10.3390/nano4040879",
spread=3.15,
note="mean of 20 measurements along a 5 m fibre",
),
_dimension(
"as-spun fibre diameter", 27.81, "um", "doi:10.3390/nano4040879", spread=1.84
),
_dimension(
"polymer coating thickness",
4,
"um",
"doi:10.3390/nano4040879",
note="about 4 um, from the coating thickness measurements",
),
_dimension(
"CNT array height",
300,
"um",
"doi:10.3390/nano4040879",
note="typical spinnable array, about 300 um",
),
], # fmt: skip
"references": ["doi:10.3390/nano4040879"],
},
"resin-embedded-cross-section": {
"identifier": "resin-embedded-cnt",
"label": "densified MWCNT fibre bundle embedded in a resin matrix (cross section and "
"sidewall exposure); the cured EMBed-812/DDSA/NMA network is represented by a linear "
"phenoxy surrogate, since crosslinking is not built; " + _ILLUSTRATIVE,
"tube": {"n": 5, "m": 5, "outer_walls": [{"n": 10, "m": 10}], "periods": 4},
"bundle": {"count": 3, "packing": "hexagonal", "gap_angstrom": 3.4},
"cell": {"kind": "matrix", "lateral_angstrom": [42.0, 40.0]},
"polymer": {
"units": {"PHX": {"smiles": "[*:1]Oc1ccc(cc1)C(C)(C)c1ccc(cc1)OCC(O)C[*:2]"}},
"chain": {"unit": "PHX", "length": 2, "tacticity": "atactic"},
},
"composition": {"chains": 4},
"seed": 2019,
"macroscopic": [
_dimension("densified fibre diameter", 28.22, "um", "doi:10.1021/acsaem.9b01723"),
_dimension("densified fibre diameter", 49.14, "um", "doi:10.1021/acsaem.9b01723"),
_dimension("densified fibre diameter", 69.45, "um", "doi:10.1021/acsaem.9b01723"),
_dimension(
"embedded film thickness",
40,
"um",
"doi:10.1021/acsaem.9b01723",
note="microtomed resin film exposing the fibre cross section",
),
_dimension(
"CNT forest height",
450,
"um",
"doi:10.1021/acsaem.9b01723",
note="upper end of the stated 150-450 um range",
),
], # fmt: skip
"references": ["doi:10.1021/acsaem.9b01723"],
},
"epoxy-thread-disordered": {
"identifier": "epoxy-thread-cnt",
"label": "disordered MWCNT segments in an epoxy-infiltrated thread; the EDA/MBDGA "
"cross-linked network is represented by a linear phenoxy surrogate, since "
"crosslinking is not built; " + _ILLUSTRATIVE,
"tube": {
"n": 5,
"m": 5,
"outer_walls": [{"n": 10, "m": 10}],
"form": "segment",
"periods": 6,
}, # fmt: skip
"bundle": {
"count": 3,
"packing": "random",
"gap_angstrom": 3.4,
"radius_angstrom": 16.0,
"max_tilt_deg": 8.0,
},
"cell": {"kind": "matrix", "lateral_angstrom": [56.0, 56.0], "length_angstrom": 30.0},
"polymer": {
"units": {"PHX": {"smiles": "[*:1]Oc1ccc(cc1)C(C)(C)c1ccc(cc1)OCC(O)C[*:2]"}},
"chain": {"unit": "PHX", "length": 2, "tacticity": "atactic"},
},
"composition": {"polymer_weight_fraction": 0.2},
"seed": 2016,
"macroscopic": [
_dimension("MWCNT outer diameter (lower)", 6, "nm", "doi:10.3390/ma9020068"),
_dimension("MWCNT outer diameter (upper)", 20, "nm", "doi:10.3390/ma9020068"),
_dimension(
"MWCNT length",
450,
"um",
"doi:10.3390/ma9020068",
note="stated range 400-500 um; 2-10 walls",
),
_dimension(
"thread diameter threshold",
10,
"um",
"doi:10.3390/ma9020068",
note="the diameter above which cross-linked thread strength fell; "
"recorded only, no mechanical property is inferred",
),
], # fmt: skip
"references": ["doi:10.3390/ma9020068"],
},
}
[docs]
def example(name: str) -> dict[str, Any]:
"""A copy of a representative example request."""
if name not in EXAMPLES:
raise ValueError(f"unknown example {name!r}; choose one of {sorted(EXAMPLES)}")
return copy.deepcopy(EXAMPLES[name])