Skip to content

Nanoparticles

AutoPoly.nanoparticles.model

Nanoparticle: a first-class finite inorganic component.

A Nanoparticle is passed to generate() alongside Polymer/Molecule models. It is not an RDKit macromolecule and not a planar substrate: its geometry comes from the material's registered shape builder (or an imported structure), its surface termination from the material's chemistry adapter, and its interaction parameters -- attached only in stage 2 -- from a registered inorganic force-field adapter.

>>> from AutoPoly.nanoparticles import Nanoparticle, SilicaSurface
>>> np_ = Nanoparticle(material="SiO2", structure="beta_cristobalite",
...                    shape="sphere", radius=12.0, count=2,
...                    surface=SilicaSurface(), motion="rigid")
>>> generate(system, "ps_silica", [ps, np_], force_field="oplsaa")

Created on 2026-11-13 @author: zwu

Classes:

Name Description
Nanoparticle

A nanoparticle species (count identical instances).

Nanoparticle

A nanoparticle species (count identical instances).

Parameters:

Name Type Description Default
material Union[str, Material]

Material ID/formula/alias ("SiO2", "Al2O3", "TiO2", "C", "Au", "Ag") or a Material object.

'SiO2'
structure Optional[str]

Phase / structure source (e.g. "alpha_quartz", "beta_cristobalite", "alpha_corundum", "anatase", "rutile", "graphene", "cnt", "fcc"); None = material default (or the Material's crystal). phase is an alias.

None
shape Union[str, Shape]

"sphere", "sheet", "tube", "cuboctahedron", "octahedron", "wulff", or a Shape object (Sphere, Sheet, Tube, Polyhedron).

'sphere'
count int

Number of identical instances to place (>= 1).

1
motion str

"rigid" (default; one LAMMPS rigid body per instance), "frozen" (excluded from time integration), or "flexible" (only with a force field that provides validated bonded terms; none of the built-in sets do).

'rigid'
surface Union[str, Surface, None]

Termination ID or Surface object (e.g. SilicaSurface(oh_density=4.6)); None = material default.

None
force_field Optional[str]

Inorganic force-field adapter name or alias (e.g. "interface", "clayff"); None = material default. atom_types is an alias.

None
name Optional[str]

Component name (unique per system); default "_".

None
seed int

Seed for stochastic surface steps (condensation pairing).

42
allow_unqualified bool

Permit MD export although the exact combination is not in the qualification matrix (recorded as user-qualified).

False
grafts Optional[Any]

Optional Grafting specification (covalently grafted chains; silica, host OPLS-AA).

None
**shape_kwargs Any

Shape size arguments (A) when shape is a name: radius, center_offset (sphere, polyhedra), length, width, layers (sheet), n, m, length (tube).

{}

Methods:

Name Description
from_file

Nanoparticle from a validated atomistic cluster file.

from_structure

Nanoparticle from an in-memory AtomicStructure (validated).

build_structure

The force-field-agnostic structure (built once, cached).

graft_plan

Sites + anchor structure of the grafted particle (cached).

graft_models

Polymer models of the grafted chains (built in stage 1).

geometry_entry

The geometry.json inorganic entry of this species.

summary

Composition, size and surface report of one instance.

write_structure

Write the structure (.json AtomicStructure, .xyz or .pdb).

Attributes:

Name Type Description
cap_length Optional[float]

Termination cap (O-H / C-H) length from the selected adapter.

Source code in AutoPoly/nanoparticles/model.py
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
class Nanoparticle:
    """
    A nanoparticle species (``count`` identical instances).

    Args:
        material: Material ID/formula/alias ("SiO2", "Al2O3", "TiO2", "C",
            "Au", "Ag") or a Material object.
        structure: Phase / structure source (e.g. "alpha_quartz",
            "beta_cristobalite", "alpha_corundum", "anatase", "rutile",
            "graphene", "cnt", "fcc"); None = material default (or the
            Material's crystal).  ``phase`` is an alias.
        shape: "sphere", "sheet", "tube", "cuboctahedron", "octahedron",
            "wulff", or a Shape object (Sphere, Sheet, Tube, Polyhedron).
        count: Number of identical instances to place (>= 1).
        motion: "rigid" (default; one LAMMPS rigid body per instance),
            "frozen" (excluded from time integration), or "flexible"
            (only with a force field that provides validated bonded
            terms; none of the built-in sets do).
        surface: Termination ID or Surface object (e.g.
            SilicaSurface(oh_density=4.6)); None = material default.
        force_field: Inorganic force-field adapter name or alias (e.g.
            "interface", "clayff"); None = material default.
            ``atom_types`` is an alias.
        name: Component name (unique per system); default
            "<material>_<shape>".
        seed: Seed for stochastic surface steps (condensation pairing).
        allow_unqualified: Permit MD export although the exact combination
            is not in the qualification matrix (recorded as user-qualified).
        grafts: Optional Grafting specification (covalently grafted chains;
            silica, host OPLS-AA).
        **shape_kwargs: Shape size arguments (A) when ``shape`` is a name:
            radius, center_offset (sphere, polyhedra), length, width,
            layers (sheet), n, m, length (tube).
    """

    _is_inorganic_component = True

    def __init__(
        self,
        material: Union[str, Material] = "SiO2",
        structure: Optional[str] = None,
        shape: Union[str, Shape] = "sphere",
        count: int = 1,
        motion: str = "rigid",
        surface: Union[str, Surface, None] = None,
        force_field: Optional[str] = None,
        name: Optional[str] = None,
        seed: int = 42,
        allow_unqualified: bool = False,
        atom_types: Optional[str] = None,
        phase: Optional[str] = None,
        grafts: Optional[Any] = None,
        **shape_kwargs: Any,
    ) -> None:
        if isinstance(material, Material):
            spec = material.spec
            structure = structure or phase or material.crystal or material.phase
            force_field = force_field or atom_types or material.force_field
            if surface is None and material.surface is not None:
                surface = material.surface
        else:
            spec = get_material(material)
            structure = structure or phase
            force_field = force_field or atom_types
        self.material: MaterialSpec = spec
        self._imported: Optional[AtomicStructure] = None
        if isinstance(shape, Imported):
            self.shape = shape
        else:
            self.shape = make_shape(shape, **shape_kwargs)
        self.phase = (spec.resolve_phase(structure).name
                      if structure is not None or spec.default_phase
                      else None)
        self.surface: Surface = make_surface(surface)
        state = self.surface.state or spec.default_surface
        if state is not None:
            spec.resolve_surface(state)
        self.surface_state = state
        if not isinstance(count, int) or count < 1:
            raise ValidationError(
                f"Nanoparticle count must be a positive int, got {count!r}"
            )
        self.count = count
        if motion not in NANOPARTICLE_MOTIONS:
            raise ValidationError(
                f"Nanoparticle motion must be one of {NANOPARTICLE_MOTIONS}, "
                f"got '{motion}'"
            )
        self.motion = motion
        self.force_field = force_field or spec.default_force_field
        if self.force_field is not None and self.force_field != "custom":
            from ..materials.forcefields import get_inorganic_ff
            get_inorganic_ff(self.force_field, spec.id)  # validates name
        self.seed = int(seed)
        self.allow_unqualified = bool(allow_unqualified)
        self.component_id = _component_id(
            name or f"{spec.id}_{self.shape.name}")
        self._structure: Optional[AtomicStructure] = None
        self._validate_shape_for_phase()
        self.grafts = grafts
        self._graft_plan = None
        if grafts is not None:
            if spec.id != "sio2" or self.surface_state != "hydroxylated":
                raise ValidationError(
                    "Grafting is implemented for hydroxylated silica "
                    f"particles (silyl-ether linkage), not {spec.id} / "
                    f"'{self.surface_state}'"
                )
            if motion == "flexible":
                raise ValidationError("Grafted particles must be rigid or "
                                      "frozen")

    # ------------------------------------------------------------------
    @classmethod
    def from_file(
        cls,
        path: Union[str, Path],
        material: Union[str, Material] = "SiO2",
        name: Optional[str] = None,
        count: int = 1,
        motion: str = "rigid",
        surface=None,
        force_field: Optional[str] = None,
        atom_types: Optional[str] = None,
        structure: Optional[str] = None,
        perceive_bonds: Optional[bool] = None,
        allow_unqualified: bool = False,
        center: bool = True,
    ) -> "Nanoparticle":
        """
        Nanoparticle from a validated atomistic cluster file.

        Supported formats: ``.json`` (AtomicStructure dict, as written by
        Nanoparticle.write_structure), ``.pdb`` with CONECT records, and
        ``.xyz``.  XYZ files carry no bonds: pass ``perceive_bonds=True``
        to perceive them with the material's distance cutoffs (the result
        is then validated against the material's valence rules).  Charges
        and parameters always come from the inorganic force-field adapter
        through the roles the chemistry adapter assigns from connectivity.

        Args:
            path: Structure file.
            material: Material of the cluster.
            structure: Phase label (default: "amorphous" for silica if
                registered, else the material default).
            center: Translate the cluster so its centroid is at the origin.
        """
        from .io import read_structure

        spec = material.spec if isinstance(material, Material) \
            else get_material(material)
        s = read_structure(path, spec, perceive_bonds=perceive_bonds)
        if center:
            s.translate(-s.positions.mean(axis=0))
        phase = structure
        if phase is None:
            phase = "amorphous" if "amorphous" in spec.phases \
                else spec.default_phase
        obj = cls(
            material=material, structure=phase,
            shape=Imported(source=str(path)), count=count, motion=motion,
            surface=surface, force_field=force_field, atom_types=atom_types,
            name=name or Path(path).stem, allow_unqualified=allow_unqualified,
        )
        obj._imported = s
        return obj

    @classmethod
    def from_structure(cls, structure: AtomicStructure,
                       material: Union[str, Material] = "SiO2",
                       **kwargs) -> "Nanoparticle":
        """Nanoparticle from an in-memory AtomicStructure (validated)."""
        from .io import prepare_imported

        spec = material.spec if isinstance(material, Material) \
            else get_material(material)
        s = prepare_imported(structure.copy(), spec, perceive_bonds=None)
        phase = kwargs.pop("structure", None) or (
            "amorphous" if "amorphous" in spec.phases else spec.default_phase)
        obj = cls(material=material, structure=phase,
                  shape=Imported(source="in-memory"), **kwargs)
        obj._imported = s
        return obj

    # ------------------------------------------------------------------
    def _validate_shape_for_phase(self) -> None:
        if isinstance(self.shape, Imported):
            return
        spec = self.material
        phase = spec.phases.get(self.phase) if self.phase else None
        shape_name = self.shape.name if self.shape.name != "polyhedron" \
            else self.shape.kind
        if phase is None or shape_name not in phase.shapes:
            supported = {p.name: list(p.shapes) for p in spec.phases.values()}
            raise ValidationError(
                f"No built-in '{shape_name}' builder for {spec.id} phase "
                f"'{self.phase}'. Supported (phase: shapes): {supported}; "
                "imported structures: Nanoparticle.from_file()"
            )
        lo, hi = spec.radius_range
        size = getattr(self.shape, "radius", None) or \
            getattr(self.shape, "size", None)
        if size is not None and not (lo <= size <= hi):
            raise ValidationError(
                f"{spec.id} particle size {size} A outside the supported "
                f"range [{lo}, {hi}] A"
            )

    @property
    def geometry_type(self) -> str:
        return self.shape.geometry_type

    @property
    def cap_length(self) -> Optional[float]:
        """Termination cap (O-H / C-H) length from the selected adapter."""
        if self.force_field in (None, "custom"):
            return None
        from ..materials.forcefields import get_inorganic_ff
        return get_inorganic_ff(self.force_field, self.material.id).cap_bond_length

    def build_structure(self) -> AtomicStructure:
        """The force-field-agnostic structure (built once, cached)."""
        if self._structure is not None:
            return self._structure
        if self._imported is not None:
            s = self._imported
        else:
            builder = self.material.builder(
                self.shape.name if self.shape.name != "polyhedron"
                else self.shape.kind)
            s = builder(
                material=self.material,
                phase=self.material.phases[self.phase],
                shape=self.shape,
                surface=self.surface,
                surface_state=self.surface_state,
                seed=self.seed,
                cap_length=self.cap_length,
            )
        s.metadata.setdefault("material_id", self.material.id)
        s.metadata["phase"] = self.phase
        s.metadata.setdefault("termination", self.surface_state)
        self._structure = s
        return s

    # ------------------------------------------------------------------
    # Grafting
    # ------------------------------------------------------------------
    def graft_plan(self, exclude=()) -> Optional[Dict[str, Any]]:
        """Sites + anchor structure of the grafted particle (cached)."""
        if self.grafts is None:
            return None
        if self._graft_plan is None or exclude:
            from ..materials.chemistry.silica import (
                graft_anchor_structure,
                select_graft_sites,
            )
            s = self.build_structure()
            area = float(s.descriptors.get("accessible_area_nm2") or 0.0)
            n = self.grafts.n_grafts(area)
            sites = select_graft_sites(s, n, seed=self.grafts.seed,
                                       exclude=exclude)
            core, anchors = graft_anchor_structure(s, sites)
            # anchor index in the core -> original silanol O index
            kept = [i for i in range(s.n_atoms)
                    if not (s.elements[i] == "H" and any(
                        o in sites for o in s.neighbors()[i]))]
            original = {new: old for new, old in enumerate(kept)}
            self._graft_plan = {"n": n, "area_nm2": area, "core": core,
                                "anchors": anchors, "sites": sites,
                                "original": original,
                                "excluded": list(exclude)}
        return self._graft_plan

    def graft_models(self) -> List[Any]:
        """Polymer models of the grafted chains (built in stage 1)."""
        plan = self.graft_plan()
        if plan is None:
            return []
        return [self.grafts.chain_model(plan["n"])]

    def _grafted_entry(self, geometry: Dict[str, Any]) -> Dict[str, Any]:
        from ..pipeline.unit_coords import placement_from_transform
        from .grafting import grow_grafts, head_and_cap

        plan = self.graft_plan()
        chains = [c for c in geometry["chains"]
                  if c.get("graft_of") == self.component_id]
        if len(chains) != plan["n"]:
            raise ValidationError(
                f"Expected {plan['n']} graft chains for '{self.component_id}', "
                f"geometry has {len(chains)}"
            )
        if any(len(c["placements"]) < 2 for c in chains):
            raise ValidationError("Grafted chains need at least 2 monomers")
        variants = geometry["variants"]
        first = variants[chains[0]["placements"][0]["variant"]]
        tpl0 = {"elements": [a["element"] for a in first["atoms"]],
                "bonds": first["bonds"]}
        head, cap = head_and_cap(tpl0)
        from .grafting import GraftGrowthError
        excluded = list(plan.get("excluded", []))
        for _ in range(8):
            try:
                transforms = grow_grafts(plan["core"], plan["anchors"],
                                         chains, variants, self.grafts, cap)
                break
            except GraftGrowthError as e:
                # crowded site: exclude it and re-select the sites
                excluded.append(plan["original"][e.site])
                plan = self.graft_plan(exclude=excluded)
        else:
            raise ValidationError(
                f"Grafting '{self.component_id}': {len(excluded)} sites were "
                "too crowded to grow chains from; lower the grafting density "
                "or use shorter grafts"
            )
        for chain, tr in zip(chains, transforms):
            chain["placements"] = [
                placement_from_transform(p["variant"], R, t)
                for p, (R, t) in zip(chain["placements"], tr)]
            first_name = chain["placements"][0]["variant"]
            variants[first_name]["graft_cap_atom"] = cap
        return {
            "linker": self.grafts.linker,
            "n": plan["n"],
            "density_target": self.grafts.density,
            "density_achieved": plan["n"] / plan["area_nm2"]
            if plan["area_nm2"] else None,
            "anchors": [{"o": int(o), "si": int(info["si"])}
                        for o, info in plan["anchors"].items()],
            "excluded_sites": [int(x) for x in excluded],
            "chain_ids": [c["id"] for c in chains],
            "head_atom": int(head),
            "cap_atom": int(cap),
        }

    # ------------------------------------------------------------------
    def geometry_entry(self, component_id: Optional[str] = None,
                       geometry: Optional[Dict[str, Any]] = None
                       ) -> Dict[str, Any]:
        """The geometry.json inorganic entry of this species."""
        grafts = None
        if self.grafts is not None:
            if geometry is None:
                raise ValidationError("Grafted particles need the stage-1 "
                                      "geometry (graft chains)")
            grafts = self._grafted_entry(geometry)
            s = self._graft_plan["core"]
        else:
            s = self.build_structure()
        entry = {
            "id": self.component_id,
            "component": "nanoparticle",
            "role": "filler",
            "count": self.count,
            "motion": self.motion,
            "material": self.material.id,
            "phase": self.phase,
            "surface": self.surface_state,
            "surface_params": dict(self.surface.params),
            "geometry_type": s.geometry_type,
            "shape": _jsonable_shape(self.shape),
            "force_field": {"name": self.force_field},
            "allow_unqualified": self.allow_unqualified,
            "structure": s.to_dict(),
        }
        if grafts is not None:
            entry["grafts"] = grafts
        return entry

    def summary(self) -> Dict[str, Any]:
        """Composition, size and surface report of one instance."""
        s = self.build_structure()
        d = s.descriptors
        return {
            "id": self.component_id,
            "material": self.material.id,
            "phase": self.phase,
            "shape": _jsonable_shape(self.shape),
            "count": self.count,
            "motion": self.motion,
            "force_field": self.force_field,
            "n_atoms": s.n_atoms,
            "formula": s.formula(),
            "mass_amu": s.total_mass(),
            "envelope": d.get("envelope"),
            "core_volume_A3": d.get("core_volume"),
            "accessible_area_nm2": d.get("accessible_area_nm2"),
            "termination": s.metadata.get("termination"),
            "metadata": {k: v for k, v in s.metadata.items()},
        }

    def write_structure(self, path: Union[str, Path]) -> Path:
        """Write the structure (.json AtomicStructure, .xyz or .pdb)."""
        from .io import write_structure
        return write_structure(self.build_structure(), path)

    def __repr__(self) -> str:
        return (f"Nanoparticle({self.material.id}, phase={self.phase!r}, "
                f"shape={self.shape!r}, count={self.count}, "
                f"motion={self.motion!r}, force_field={self.force_field!r})")

cap_length: Optional[float] property

Termination cap (O-H / C-H) length from the selected adapter.

from_file(path: Union[str, Path], material: Union[str, Material] = 'SiO2', name: Optional[str] = None, count: int = 1, motion: str = 'rigid', surface=None, force_field: Optional[str] = None, atom_types: Optional[str] = None, structure: Optional[str] = None, perceive_bonds: Optional[bool] = None, allow_unqualified: bool = False, center: bool = True) -> Nanoparticle classmethod

Nanoparticle from a validated atomistic cluster file.

Supported formats: .json (AtomicStructure dict, as written by Nanoparticle.write_structure), .pdb with CONECT records, and .xyz. XYZ files carry no bonds: pass perceive_bonds=True to perceive them with the material's distance cutoffs (the result is then validated against the material's valence rules). Charges and parameters always come from the inorganic force-field adapter through the roles the chemistry adapter assigns from connectivity.

Parameters:

Name Type Description Default
path Union[str, Path]

Structure file.

required
material Union[str, Material]

Material of the cluster.

'SiO2'
structure Optional[str]

Phase label (default: "amorphous" for silica if registered, else the material default).

None
center bool

Translate the cluster so its centroid is at the origin.

True
Source code in AutoPoly/nanoparticles/model.py
@classmethod
def from_file(
    cls,
    path: Union[str, Path],
    material: Union[str, Material] = "SiO2",
    name: Optional[str] = None,
    count: int = 1,
    motion: str = "rigid",
    surface=None,
    force_field: Optional[str] = None,
    atom_types: Optional[str] = None,
    structure: Optional[str] = None,
    perceive_bonds: Optional[bool] = None,
    allow_unqualified: bool = False,
    center: bool = True,
) -> "Nanoparticle":
    """
    Nanoparticle from a validated atomistic cluster file.

    Supported formats: ``.json`` (AtomicStructure dict, as written by
    Nanoparticle.write_structure), ``.pdb`` with CONECT records, and
    ``.xyz``.  XYZ files carry no bonds: pass ``perceive_bonds=True``
    to perceive them with the material's distance cutoffs (the result
    is then validated against the material's valence rules).  Charges
    and parameters always come from the inorganic force-field adapter
    through the roles the chemistry adapter assigns from connectivity.

    Args:
        path: Structure file.
        material: Material of the cluster.
        structure: Phase label (default: "amorphous" for silica if
            registered, else the material default).
        center: Translate the cluster so its centroid is at the origin.
    """
    from .io import read_structure

    spec = material.spec if isinstance(material, Material) \
        else get_material(material)
    s = read_structure(path, spec, perceive_bonds=perceive_bonds)
    if center:
        s.translate(-s.positions.mean(axis=0))
    phase = structure
    if phase is None:
        phase = "amorphous" if "amorphous" in spec.phases \
            else spec.default_phase
    obj = cls(
        material=material, structure=phase,
        shape=Imported(source=str(path)), count=count, motion=motion,
        surface=surface, force_field=force_field, atom_types=atom_types,
        name=name or Path(path).stem, allow_unqualified=allow_unqualified,
    )
    obj._imported = s
    return obj

from_structure(structure: AtomicStructure, material: Union[str, Material] = 'SiO2', **kwargs) -> Nanoparticle classmethod

Nanoparticle from an in-memory AtomicStructure (validated).

Source code in AutoPoly/nanoparticles/model.py
@classmethod
def from_structure(cls, structure: AtomicStructure,
                   material: Union[str, Material] = "SiO2",
                   **kwargs) -> "Nanoparticle":
    """Nanoparticle from an in-memory AtomicStructure (validated)."""
    from .io import prepare_imported

    spec = material.spec if isinstance(material, Material) \
        else get_material(material)
    s = prepare_imported(structure.copy(), spec, perceive_bonds=None)
    phase = kwargs.pop("structure", None) or (
        "amorphous" if "amorphous" in spec.phases else spec.default_phase)
    obj = cls(material=material, structure=phase,
              shape=Imported(source="in-memory"), **kwargs)
    obj._imported = s
    return obj

build_structure() -> AtomicStructure

The force-field-agnostic structure (built once, cached).

Source code in AutoPoly/nanoparticles/model.py
def build_structure(self) -> AtomicStructure:
    """The force-field-agnostic structure (built once, cached)."""
    if self._structure is not None:
        return self._structure
    if self._imported is not None:
        s = self._imported
    else:
        builder = self.material.builder(
            self.shape.name if self.shape.name != "polyhedron"
            else self.shape.kind)
        s = builder(
            material=self.material,
            phase=self.material.phases[self.phase],
            shape=self.shape,
            surface=self.surface,
            surface_state=self.surface_state,
            seed=self.seed,
            cap_length=self.cap_length,
        )
    s.metadata.setdefault("material_id", self.material.id)
    s.metadata["phase"] = self.phase
    s.metadata.setdefault("termination", self.surface_state)
    self._structure = s
    return s

graft_plan(exclude=()) -> Optional[Dict[str, Any]]

Sites + anchor structure of the grafted particle (cached).

Source code in AutoPoly/nanoparticles/model.py
def graft_plan(self, exclude=()) -> Optional[Dict[str, Any]]:
    """Sites + anchor structure of the grafted particle (cached)."""
    if self.grafts is None:
        return None
    if self._graft_plan is None or exclude:
        from ..materials.chemistry.silica import (
            graft_anchor_structure,
            select_graft_sites,
        )
        s = self.build_structure()
        area = float(s.descriptors.get("accessible_area_nm2") or 0.0)
        n = self.grafts.n_grafts(area)
        sites = select_graft_sites(s, n, seed=self.grafts.seed,
                                   exclude=exclude)
        core, anchors = graft_anchor_structure(s, sites)
        # anchor index in the core -> original silanol O index
        kept = [i for i in range(s.n_atoms)
                if not (s.elements[i] == "H" and any(
                    o in sites for o in s.neighbors()[i]))]
        original = {new: old for new, old in enumerate(kept)}
        self._graft_plan = {"n": n, "area_nm2": area, "core": core,
                            "anchors": anchors, "sites": sites,
                            "original": original,
                            "excluded": list(exclude)}
    return self._graft_plan

graft_models() -> List[Any]

Polymer models of the grafted chains (built in stage 1).

Source code in AutoPoly/nanoparticles/model.py
def graft_models(self) -> List[Any]:
    """Polymer models of the grafted chains (built in stage 1)."""
    plan = self.graft_plan()
    if plan is None:
        return []
    return [self.grafts.chain_model(plan["n"])]

geometry_entry(component_id: Optional[str] = None, geometry: Optional[Dict[str, Any]] = None) -> Dict[str, Any]

The geometry.json inorganic entry of this species.

Source code in AutoPoly/nanoparticles/model.py
def geometry_entry(self, component_id: Optional[str] = None,
                   geometry: Optional[Dict[str, Any]] = None
                   ) -> Dict[str, Any]:
    """The geometry.json inorganic entry of this species."""
    grafts = None
    if self.grafts is not None:
        if geometry is None:
            raise ValidationError("Grafted particles need the stage-1 "
                                  "geometry (graft chains)")
        grafts = self._grafted_entry(geometry)
        s = self._graft_plan["core"]
    else:
        s = self.build_structure()
    entry = {
        "id": self.component_id,
        "component": "nanoparticle",
        "role": "filler",
        "count": self.count,
        "motion": self.motion,
        "material": self.material.id,
        "phase": self.phase,
        "surface": self.surface_state,
        "surface_params": dict(self.surface.params),
        "geometry_type": s.geometry_type,
        "shape": _jsonable_shape(self.shape),
        "force_field": {"name": self.force_field},
        "allow_unqualified": self.allow_unqualified,
        "structure": s.to_dict(),
    }
    if grafts is not None:
        entry["grafts"] = grafts
    return entry

summary() -> Dict[str, Any]

Composition, size and surface report of one instance.

Source code in AutoPoly/nanoparticles/model.py
def summary(self) -> Dict[str, Any]:
    """Composition, size and surface report of one instance."""
    s = self.build_structure()
    d = s.descriptors
    return {
        "id": self.component_id,
        "material": self.material.id,
        "phase": self.phase,
        "shape": _jsonable_shape(self.shape),
        "count": self.count,
        "motion": self.motion,
        "force_field": self.force_field,
        "n_atoms": s.n_atoms,
        "formula": s.formula(),
        "mass_amu": s.total_mass(),
        "envelope": d.get("envelope"),
        "core_volume_A3": d.get("core_volume"),
        "accessible_area_nm2": d.get("accessible_area_nm2"),
        "termination": s.metadata.get("termination"),
        "metadata": {k: v for k, v in s.metadata.items()},
    }

write_structure(path: Union[str, Path]) -> Path

Write the structure (.json AtomicStructure, .xyz or .pdb).

Source code in AutoPoly/nanoparticles/model.py
def write_structure(self, path: Union[str, Path]) -> Path:
    """Write the structure (.json AtomicStructure, .xyz or .pdb)."""
    from .io import write_structure
    return write_structure(self.build_structure(), path)

Shapes and surfaces

AutoPoly.nanoparticles.shapes

Shape and surface specifications for nanoparticles.

Shapes define which atoms belong to the object (carved from the bulk crystal of the selected phase); surfaces define how the exposed atoms are terminated (delegated to the material's chemistry adapter). Neither says anything about interactions.

Created on 2026-11-13 @author: zwu

Classes:

Name Description
Shape

Base class of shape specifications.

Sphere

Spherical particle.

Polyhedron

Faceted fcc metal cluster (optional ASE builders).

Sheet

Finite sheet (graphene flake) in the xy plane.

Tube

Single-wall carbon nanotube along z.

Imported

Shape of an imported structure (no carving).

Surface

Surface-termination request.

Functions:

Name Description
make_shape

Shape object from a name (+ size kwargs) or a Shape instance.

SilicaSurface

Silica termination: Q3/Q2 silanols on 4-coordinated Si.

Shape dataclass

Base class of shape specifications.

Source code in AutoPoly/nanoparticles/shapes.py
@dataclass(frozen=True)
class Shape:
    """Base class of shape specifications."""
    name: str = ""
    geometry_type: str = "cluster"

    def to_dict(self) -> Dict[str, Any]:
        out = {k: v for k, v in self.__dict__.items()}
        return out

Sphere dataclass

Bases: Shape

Spherical particle.

Parameters:

Name Type Description Default
radius float

Core cut radius (A): every framework cation (Si, Al, Ti, metal atom) within this distance of the center is kept.

10.0
center_offset Optional[Tuple[float, float, float]]

Optional shift of the particle center inside the crystal (A); varies which surface sites are exposed.

None
Source code in AutoPoly/nanoparticles/shapes.py
@dataclass(frozen=True)
class Sphere(Shape):
    """
    Spherical particle.

    Args:
        radius: Core cut radius (A): every framework cation (Si, Al, Ti,
            metal atom) within this distance of the center is kept.
        center_offset: Optional shift of the particle center inside the
            crystal (A); varies which surface sites are exposed.
    """
    radius: float = 10.0
    center_offset: Optional[Tuple[float, float, float]] = None
    name: str = "sphere"
    geometry_type: str = "cluster"

    def __post_init__(self) -> None:
        if not self.radius > 0:
            raise ValidationError(f"Sphere radius must be > 0, got {self.radius}")

Polyhedron dataclass

Bases: Shape

Faceted fcc metal cluster (optional ASE builders).

Parameters:

Name Type Description Default
kind str

"cuboctahedron", "octahedron" or "wulff".

'cuboctahedron'
size float

Approximate radius (A) used to choose the shell count / layer numbers.

10.0
surface_energies Optional[Dict[Tuple[int, int, int], float]]

Wulff construction only: {(h, k, l): energy} (relative values); defaults to (111) < (100) ratios for fcc.

None
Source code in AutoPoly/nanoparticles/shapes.py
@dataclass(frozen=True)
class Polyhedron(Shape):
    """
    Faceted fcc metal cluster (optional ASE builders).

    Args:
        kind: "cuboctahedron", "octahedron" or "wulff".
        size: Approximate radius (A) used to choose the shell count / layer
            numbers.
        surface_energies: Wulff construction only: {(h, k, l): energy}
            (relative values); defaults to (111) < (100) ratios for fcc.
    """
    kind: str = "cuboctahedron"
    size: float = 10.0
    surface_energies: Optional[Dict[Tuple[int, int, int], float]] = None
    name: str = "polyhedron"
    geometry_type: str = "cluster"

    def __post_init__(self) -> None:
        if self.kind not in ("cuboctahedron", "octahedron", "wulff"):
            raise ValidationError(
                f"Polyhedron kind must be cuboctahedron/octahedron/wulff, "
                f"got '{self.kind}'"
            )
        if not self.size > 0:
            raise ValidationError(f"Polyhedron size must be > 0")

Sheet dataclass

Bases: Shape

Finite sheet (graphene flake) in the xy plane.

Parameters:

Name Type Description Default
length float

Extent along x (A, zigzag direction).

30.0
width float

Extent along y (A, armchair direction).

30.0
layers int

Number of AB-stacked layers (3.35 A apart).

1
Source code in AutoPoly/nanoparticles/shapes.py
@dataclass(frozen=True)
class Sheet(Shape):
    """
    Finite sheet (graphene flake) in the xy plane.

    Args:
        length: Extent along x (A, zigzag direction).
        width: Extent along y (A, armchair direction).
        layers: Number of AB-stacked layers (3.35 A apart).
    """
    length: float = 30.0
    width: float = 30.0
    layers: int = 1
    name: str = "sheet"
    geometry_type: str = "sheet"

    def __post_init__(self) -> None:
        if not (self.length > 0 and self.width > 0):
            raise ValidationError("Sheet length and width must be > 0")
        if self.layers < 1:
            raise ValidationError("Sheet layers must be >= 1")

Tube dataclass

Bases: Shape

Single-wall carbon nanotube along z.

Parameters:

Name Type Description Default
n int

First chiral index (n > 0).

10
m int

Second chiral index (0 <= m <= n).

10
length float

Tube length (A).

30.0
Source code in AutoPoly/nanoparticles/shapes.py
@dataclass(frozen=True)
class Tube(Shape):
    """
    Single-wall carbon nanotube along z.

    Args:
        n: First chiral index (n > 0).
        m: Second chiral index (0 <= m <= n).
        length: Tube length (A).
    """
    n: int = 10
    m: int = 10
    length: float = 30.0
    name: str = "tube"
    geometry_type: str = "rod"

    def __post_init__(self) -> None:
        if not (self.n > 0 and 0 <= self.m <= self.n):
            raise ValidationError(
                f"Tube chiral indices need n > 0 and 0 <= m <= n, got "
                f"({self.n}, {self.m})"
            )
        if not self.length > 0:
            raise ValidationError("Tube length must be > 0")

Imported dataclass

Bases: Shape

Shape of an imported structure (no carving).

Source code in AutoPoly/nanoparticles/shapes.py
@dataclass(frozen=True)
class Imported(Shape):
    """Shape of an imported structure (no carving)."""
    source: str = ""
    name: str = "imported"
    geometry_type: str = "imported"

Surface dataclass

Surface-termination request.

Parameters:

Name Type Description Default
state Optional[str]

Termination ID registered for the material ("hydroxylated", "stoichiometric", "h_passivated", "bare"); None = material default.

None
params Dict[str, Any]

Termination parameters (material specific).

dict()
Source code in AutoPoly/nanoparticles/shapes.py
@dataclass(frozen=True)
class Surface:
    """
    Surface-termination request.

    Args:
        state: Termination ID registered for the material ("hydroxylated",
            "stoichiometric", "h_passivated", "bare"); None = material
            default.
        params: Termination parameters (material specific).
    """
    state: Optional[str] = None
    params: Dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        return {"state": self.state, "params": dict(self.params)}

make_shape(shape, **kwargs) -> Shape

Shape object from a name (+ size kwargs) or a Shape instance.

Source code in AutoPoly/nanoparticles/shapes.py
def make_shape(shape, **kwargs) -> Shape:
    """Shape object from a name (+ size kwargs) or a Shape instance."""
    if isinstance(shape, Shape):
        if kwargs:
            raise ValidationError(
                f"Size arguments {sorted(kwargs)} given together with a "
                f"{type(shape).__name__} object"
            )
        return shape
    name = str(shape).lower()
    if name == "sphere":
        if "radius" not in kwargs:
            raise ValidationError("shape='sphere' requires radius=...")
        return Sphere(radius=float(kwargs.pop("radius")),
                      center_offset=kwargs.pop("center_offset", None),
                      **_no_more(kwargs, name))
    if name in ("cuboctahedron", "octahedron", "wulff"):
        size = kwargs.pop("size", kwargs.pop("radius", None))
        if size is None:
            raise ValidationError(f"shape='{name}' requires radius=...")
        return Polyhedron(kind=name, size=float(size),
                          surface_energies=kwargs.pop("surface_energies", None),
                          **_no_more(kwargs, name))
    if name == "sheet":
        return Sheet(length=float(kwargs.pop("length", 30.0)),
                     width=float(kwargs.pop("width", 30.0)),
                     layers=int(kwargs.pop("layers", 1)),
                     **_no_more(kwargs, name))
    if name in ("tube", "cnt", "rod"):
        return Tube(n=int(kwargs.pop("n", 10)), m=int(kwargs.pop("m", 10)),
                    length=float(kwargs.pop("length", 30.0)),
                    **_no_more(kwargs, name))
    raise ValidationError(
        f"Unknown nanoparticle shape '{shape}'; use 'sphere', 'sheet', "
        "'tube', 'cuboctahedron', 'octahedron', 'wulff', or a Shape object "
        "(imported structures: Nanoparticle.from_file)"
    )

SilicaSurface(oh_density: Optional[float] = None, state: str = 'hydroxylated') -> Surface

Silica termination: Q3/Q2 silanols on 4-coordinated Si.

Parameters:

Name Type Description Default
oh_density Optional[float]

Target silanol density (sites/nm^2). Applied by Si-O-Si condensation where geometrically possible; the achieved density is reported (crystal-derived spheres are intrinsically at ~5-6 (cristobalite) or ~7-8 (quartz) /nm^2). For imported structures the value is the expected density, checked within tolerance.

None
Source code in AutoPoly/nanoparticles/shapes.py
def SilicaSurface(oh_density: Optional[float] = None,
                  state: str = "hydroxylated") -> Surface:
    """
    Silica termination: Q3/Q2 silanols on 4-coordinated Si.

    Args:
        oh_density: Target silanol density (sites/nm^2).  Applied by Si-O-Si
            condensation where geometrically possible; the achieved density
            is reported (crystal-derived spheres are intrinsically at ~5-6
            (cristobalite) or ~7-8 (quartz) /nm^2).  For imported
            structures the value is the expected density, checked within
            tolerance.
    """
    if oh_density is not None and oh_density < 0:
        raise ValidationError(f"oh_density must be >= 0, got {oh_density}")
    return Surface(state=state, params={"oh_density": oh_density})

Grafting

AutoPoly.nanoparticles.grafting

Covalent polymer grafting onto nanoparticle surface sites.

>>> from AutoPoly.nanoparticles import Nanoparticle, Grafting
>>> brush = Grafting(polymer=Polymer(chain_num=1, sequence=PE10),
...                  density=0.8)                 # chains / nm^2
>>> np_ = Nanoparticle(material="SiO2", radius=12.0, grafts=brush)

Model (silica, linker "silyl_ether"):

  • Sites: N_g = round(sigma_g * A_accessible) silanol oxygens (or an explicit count), spread by farthest-point sampling, at most one per silicon.
  • Chemistry: Si-OH + H-C(head) -> Si-O-C(head): the silanol H and one H of the chain's head atom (the first heavy atom of the first monomer, which must carry H) are removed and the surface O bonds to the head atom. The grafted O ("OG") keeps the silanol-O Lennard-Jones parameters and carries the silanol group charge q(OH) + q(HO) plus the charge of the removed organic H, so the total charge of particle + grafts is conserved exactly.
  • Conformations: every graft grows monomer by monomer from its anchor with the obstacle-aware grower (packing.chain_regrowth): the head atom sits on the anchor's vacated O-H direction at the O-C bond length, every atom clears the core (core_clearance) and earlier grafts; grafted chains are part of the particle class, not free matrix molecules.
  • Bonded linkage terms (host OPLS-AA only): bond O-C (OPLS CT-OS), angle Si-O-C (CT-OS-Si, wlj silyl ether), angles O-C-X (X-CT-OS) and dihedrals O-C-C-X (X-CT-CT-OS), with coefficients read from the bundled oplsaa.lt by the OPLS bonded classes of the typed atoms -- never invented. Si-O-C-X torsions are not defined for silica-bound ethers in OPLS-AA and are omitted (documented: low barrier); terms whose atoms all belong to the rigid core are irrelevant and omitted.

Created on 2026-11-13 @author: zwu

Classes:

Name Description
GraftGrowthError

A graft could not be grown from one surface site.

Grafting

Grafted-chain specification of a nanoparticle species.

Functions:

Name Description
head_and_cap

(head heavy-atom index, index of one H on it) of a first monomer.

grow_grafts

Anchored growth of one chain per anchor around a rigid core.

opls_coefficients

Coefficient tokens of an OPLS bonded term by class names (either

opls_class

Bonded class ('b', 'a', 'd') of an OPLS @atom type (e.g. '81').

GraftGrowthError

Bases: ValidationError

A graft could not be grown from one surface site.

Source code in AutoPoly/nanoparticles/grafting.py
class GraftGrowthError(ValidationError):
    """A graft could not be grown from one surface site."""

    def __init__(self, message: str, site: int = -1) -> None:
        super().__init__(message)
        self.site = site

Grafting dataclass

Grafted-chain specification of a nanoparticle species.

Parameters:

Name Type Description Default
polymer Any

Polymer model of one grafted chain (its chain_num is replaced by the number of grafts). The head atom -- first heavy atom of the first monomer -- must carry at least one H.

required
density Optional[float]

Target grafting density (chains/nm^2 of accessible area).

None
count Optional[int]

Explicit number of grafts per particle (overrides density).

None
linker str

Linkage template ("silyl_ether").

'silyl_ether'
seed int

Site-selection and growth seed.

0
core_clearance float

Minimum distance (A) of graft atoms from core atoms other than the anchor O and its Si.

2.0
attempts int

Independent anchored growth attempts per graft.

60

Methods:

Name Description
chain_model

Copy of the graft polymer with chain_num = n.

Source code in AutoPoly/nanoparticles/grafting.py
@dataclass
class Grafting:
    """
    Grafted-chain specification of a nanoparticle species.

    Args:
        polymer: Polymer model of one grafted chain (its ``chain_num`` is
            replaced by the number of grafts).  The head atom -- first heavy
            atom of the first monomer -- must carry at least one H.
        density: Target grafting density (chains/nm^2 of accessible area).
        count: Explicit number of grafts per particle (overrides density).
        linker: Linkage template ("silyl_ether").
        seed: Site-selection and growth seed.
        core_clearance: Minimum distance (A) of graft atoms from core atoms
            other than the anchor O and its Si.
        attempts: Independent anchored growth attempts per graft.
    """
    polymer: Any
    density: Optional[float] = None
    count: Optional[int] = None
    linker: str = "silyl_ether"
    seed: int = 0
    core_clearance: float = 2.0
    attempts: int = 60

    def __post_init__(self) -> None:
        if (self.density is None) == (self.count is None):
            raise ValidationError(
                "Grafting needs exactly one of density= (chains/nm^2) or "
                "count="
            )
        if self.density is not None and self.density <= 0:
            raise ValidationError("Grafting density must be > 0")
        if self.count is not None and self.count < 1:
            raise ValidationError("Grafting count must be >= 1")
        if self.linker not in LINKERS:
            raise ValidationError(
                f"Unknown linker '{self.linker}'; available: {sorted(LINKERS)}"
            )
        if getattr(self.polymer, "topology", "linear") != "linear":
            raise ValidationError("Grafted chains must be linear polymers")

    def n_grafts(self, area_nm2: float) -> int:
        if self.count is not None:
            return int(self.count)
        n = int(round(self.density * area_nm2))
        if n < 1:
            raise ValidationError(
                f"Grafting density {self.density}/nm^2 on {area_nm2:.2f} nm^2 "
                "gives no chain; raise the density or use count="
            )
        return n

    def chain_model(self, n: int):
        """Copy of the graft polymer with chain_num = n."""
        model = object.__new__(type(self.polymer))
        model.__dict__.update(copy.deepcopy(self.polymer.__dict__))
        model.chain_num = int(n)
        model.set_Sequence()
        return model

chain_model(n: int)

Copy of the graft polymer with chain_num = n.

Source code in AutoPoly/nanoparticles/grafting.py
def chain_model(self, n: int):
    """Copy of the graft polymer with chain_num = n."""
    model = object.__new__(type(self.polymer))
    model.__dict__.update(copy.deepcopy(self.polymer.__dict__))
    model.chain_num = int(n)
    model.set_Sequence()
    return model

head_and_cap(template: Dict[str, Any]) -> Tuple[int, int]

(head heavy-atom index, index of one H on it) of a first monomer.

Source code in AutoPoly/nanoparticles/grafting.py
def head_and_cap(template: Dict[str, Any]) -> Tuple[int, int]:
    """(head heavy-atom index, index of one H on it) of a first monomer."""
    el = template["elements"]
    head = next((i for i, e in enumerate(el) if e != "H"), None)
    if head is None:
        raise ValidationError("Graft head monomer has no heavy atom")
    for i, j in template["bonds"]:
        for a, b in ((i, j), (j, i)):
            if a == head and el[b] == "H":
                return head, b
    raise ValidationError(
        "The graft head atom (first heavy atom of the first monomer) carries "
        "no hydrogen; the silyl-ether linker needs an H to replace"
    )

grow_grafts(core: AtomicStructure, anchors: Dict[int, Dict], chains: List[Dict], variants: Dict[str, Any], grafting: Grafting, cap_index: int) -> List[List[Tuple[np.ndarray, np.ndarray]]]

Anchored growth of one chain per anchor around a rigid core.

Parameters:

Name Type Description Default
core AtomicStructure

Core AtomicStructure (anchor O already without H).

required
anchors Dict[int, Dict]

new-O index -> {"si", "direction", ...}.

required
chains List[Dict]

geometry.json chain entries (one per anchor, same order).

required
variants Dict[str, Any]

geometry.json variants.

required
cap_index int

Head-H index (in the first monomer) removed at grafting.

required

Returns:

Type Description
List[List[Tuple[ndarray, ndarray]]]

Per graft, the list of monomer transforms (R, t) in the particle

List[List[Tuple[ndarray, ndarray]]]

frame.

Source code in AutoPoly/nanoparticles/grafting.py
def grow_grafts(core: "AtomicStructure", anchors: Dict[int, Dict],
                chains: List[Dict],
                variants: Dict[str, Any], grafting: Grafting,
                cap_index: int) -> List[List[Tuple[np.ndarray, np.ndarray]]]:
    """
    Anchored growth of one chain per anchor around a rigid core.

    Args:
        core: Core AtomicStructure (anchor O already without H).
        anchors: new-O index -> {"si", "direction", ...}.
        chains: geometry.json chain entries (one per anchor, same order).
        variants: geometry.json variants.
        cap_index: Head-H index (in the first monomer) removed at grafting.

    Returns:
        Per graft, the list of monomer transforms (R, t) in the particle
        frame.
    """
    from ..packing.chain_regrowth import ChainTemplate, ObstacleAwareGrower
    from ..packing.collision_geometry import PeriodicVoxelGrid
    from ..pipeline.unit_coords import chain_template_data

    pos = core.positions
    templates = [ChainTemplate(chain_template_data(c.get("id", "g"), c,
                                                   variants))
                 for c in chains]
    # finite cluster in a periodic grid large enough to never wrap
    reach = templates[0].n * 3.0 + 10.0
    half = float(np.linalg.norm(pos, axis=1).max()) + reach
    L = np.full(3, 2.0 * half)
    grid = PeriodicVoxelGrid(-0.5 * L, L, 0.3)
    exclude = set()
    for o, info in anchors.items():
        exclude.add(o)
        exclude.add(info["si"])
    mask = np.array([i not in exclude for i in range(core.n_atoms)])
    is_h = np.array([e == "H" for e in core.elements])
    grid.mark(pos[mask & ~is_h], grafting.core_clearance)
    grid.mark(pos[mask & is_h], min(grafting.core_clearance, 1.6))
    rng = np.random.default_rng(grafting.seed)
    grower = ObstacleAwareGrower(grid, L)
    out = []
    head = None
    for k, ((o, info), tpl) in enumerate(zip(anchors.items(), templates)):
        if head is None:
            head, cap = head_and_cap(tpl.info(0))
            if cap != cap_index:
                raise ValidationError("inconsistent graft cap atom")
        anchor = {"position": pos[o], "direction": info["direction"],
                  "length": SILYL_ETHER_OC, "head": head, "cap": cap_index,
                  # head substituents vs the anchor O (1-3) and Si (1-4)
                  "partners": ((pos[o], 1.85), (pos[info["si"]], 2.4)),
                  "partners_far": ((pos[o], 2.0), (pos[info["si"]], 2.4)),
                  "max_tilt": 15.0}
        # this graft must also clear every *other* anchor O / Si (they
        # are absent from the shared grid so their own grafts can attach)
        others = [x for oo, inf in anchors.items() if oo != o
                  for x in (oo, inf["si"])]
        grower.grid = grid.copy()
        if others:
            grower.grid.mark(pos[others], grafting.core_clearance)
        transforms = None
        for _ in range(grafting.attempts):
            transforms = grower.grow(tpl, rng, anchor=anchor)
            if transforms is not None:
                break
        if transforms is None:
            raise GraftGrowthError(
                f"Could not grow graft {k + 1}/{len(anchors)} from its surface "
                "site without overlaps (crowded brush or too short spacing): "
                "lower the grafting density, use shorter chains, or reduce "
                "core_clearance", site=o
            )
        world = np.vstack([tpl.local(m) @ R.T + t
                           for m, (R, t) in enumerate(transforms)])
        # mark this graft (minus the removed cap H) for the next ones
        cap_global = cap_index
        keep = np.ones(len(world), dtype=bool)
        keep[cap_global] = False
        els = np.concatenate([tpl.info(m)["elements"]
                              for m in range(tpl.n)])
        is_h = els == "H"
        grid.mark(world[keep & ~is_h], 1.7)
        grid.mark(world[keep & is_h], 1.2)
        out.append(transforms)
    logger.info(f"Grew {len(out)} grafted chains from surface anchors")
    return out

opls_coefficients(kind: str, names: Sequence[str], ff_lt: Path)

Coefficient tokens of an OPLS bonded term by class names (either direction); None if undefined.

Source code in AutoPoly/nanoparticles/grafting.py
def opls_coefficients(kind: str, names: Sequence[str], ff_lt: Path):
    """Coefficient tokens of an OPLS bonded term by class names (either
    direction); None if undefined."""
    _, coeffs = _opls_tables(str(ff_lt))
    for key in ("_".join(names), "_".join(reversed(names))):
        if key in coeffs[kind]:
            return coeffs[kind][key]
    return None

opls_class(atom_type: str, slot: str, ff_lt: Path) -> str

Bonded class ('b', 'a', 'd') of an OPLS @atom type (e.g. '81').

Source code in AutoPoly/nanoparticles/grafting.py
def opls_class(atom_type: str, slot: str, ff_lt: Path) -> str:
    """Bonded class ('b', 'a', 'd') of an OPLS @atom type (e.g. '81')."""
    classes, _ = _opls_tables(str(ff_lt))
    t = atom_type.split(":")[-1]
    if t not in classes:
        raise ValidationError(f"OPLS-AA type {atom_type} has no bonded classes")
    return classes[t]["bad".index(slot)]

Coarse-grained fillers (bead-spring)

AutoPoly.nanoparticles.cg

Coarse-grained (CG) spherical fillers for the bead-spring backend.

A CG filler is a rigid (or frozen) particle made of LJ beads -- a solid FCC cut ("fcc") or a Fibonacci surface shell ("shell") of one filler bead type -- in the reduced LJ units of the bead-spring models:

>>> from AutoPoly.models.bead_spring import BeadType
>>> from AutoPoly.nanoparticles import CGFiller
>>> bss = BeadSpringSystem("nc", system, bead_types=[BeadType("A"),
...                        BeadType("F", epsilon=1.0)], pair_style="lj",
...                        density=0.5)
>>> bss.add_species(arch.linear([("A", 50)]), n_chains=40)
>>> bss.add_filler(CGFiller(radius=4.0, count=2, bead_type="F"))
>>> bss.generate(backend="direct")

Construction: fillers are placed first (random positions and orientations, periodic minimum-image gap min_gap between particle envelopes), then the chains grow by SAW around them (beads may not enter the filler envelope, radius + half a filler bead). The run script holds the fillers during minimization, integrates each rigid filler as one body (fix rigid/nvt molecule) or keeps frozen fillers in place, skips intra-filler pair forces, and reports a matrix-only temperature.

CG fillers are generic LJ particles: their mapping onto a real material (bead size, polymer-filler attraction epsilon, see BeadSpringSystem.set_pair_coeff) is the user's modelling choice and is not part of the atomistic material qualification matrix.

Created on 2026-11-13 @author: zwu

Classes:

Name Description
CGFiller

Coarse-grained spherical filler species (LJ units).

PlacedFiller

One placed CG particle.

Functions:

Name Description
fcc_sphere

FCC lattice sites (nearest-neighbor distance spacing) within

sphere_shell

Near-uniform beads on a sphere of radius, about spacing

place_fillers

Random sequential placement of all CG particles in the periodic cubic

filler_volume

Total envelope volume of all CG particles (sigma^3).

motion_groups

motion -> filler bead-type names (each type has one motion).

group_lines

LAMMPS group commands; type tokens are numeric ids (direct backend)

production_lines

Integrators: matrix NVT, one rigid body per rigid particle, frozen

compression_hint

Commented NPT block: the filler-aware SAW packs below melt density

summary

Filler block of BeadSpringSystem.get_system_info().

CGFiller dataclass

Coarse-grained spherical filler species (LJ units).

Parameters:

Name Type Description Default
radius float

Particle radius (sigma); every bead center lies within it.

required
count int

Number of particles.

1
bead_type str

Filler BeadType name; must be in the system's bead types and not used by any chain species.

'F'
structure str

"fcc" (solid FCC cut, default) or "shell" (beads on the sphere surface only).

'fcc'
spacing float

Nearest-neighbor bead distance (sigma).

1.0
motion str

"rigid" (one rigid body per particle) or "frozen".

'rigid'
name str

Species label.

'filler'

Methods:

Name Description
bead_positions

(n, 3) bead centers of one particle, centered at the origin.

Source code in AutoPoly/nanoparticles/cg.py
@dataclass
class CGFiller:
    """
    Coarse-grained spherical filler species (LJ units).

    Args:
        radius: Particle radius (sigma); every bead center lies within it.
        count: Number of particles.
        bead_type: Filler BeadType name; must be in the system's bead types
            and not used by any chain species.
        structure: "fcc" (solid FCC cut, default) or "shell" (beads on the
            sphere surface only).
        spacing: Nearest-neighbor bead distance (sigma).
        motion: "rigid" (one rigid body per particle) or "frozen".
        name: Species label.
    """
    radius: float
    count: int = 1
    bead_type: str = "F"
    structure: str = "fcc"
    spacing: float = 1.0
    motion: str = "rigid"
    name: str = "filler"

    def __post_init__(self) -> None:
        if self.radius <= 0:
            raise ValueError(f"CGFiller radius must be > 0, got {self.radius}")
        if self.count < 1:
            raise ValueError(f"CGFiller count must be >= 1, got {self.count}")
        if self.spacing <= 0:
            raise ValueError("CGFiller spacing must be > 0")
        if self.radius < self.spacing:
            raise ValueError(
                f"CGFiller radius ({self.radius}) is smaller than the bead "
                f"spacing ({self.spacing}): the particle would be a single "
                "bead; use a plain bead type (or a smaller spacing) instead")
        if self.structure not in STRUCTURES:
            raise ValueError(
                f"CGFiller structure must be one of {STRUCTURES}, "
                f"got '{self.structure}'")
        if self.motion not in MOTIONS:
            raise ValueError(
                f"CGFiller motion must be one of {MOTIONS}, got "
                f"'{self.motion}' (flexible CG fillers are not supported)")

    def bead_positions(self) -> np.ndarray:
        """(n, 3) bead centers of one particle, centered at the origin."""
        if self.structure == "fcc":
            pos = fcc_sphere(self.radius, self.spacing)
        else:
            pos = sphere_shell(self.radius, self.spacing)
        return pos

    @property
    def n_beads(self) -> int:
        return len(self.bead_positions())

bead_positions() -> np.ndarray

(n, 3) bead centers of one particle, centered at the origin.

Source code in AutoPoly/nanoparticles/cg.py
def bead_positions(self) -> np.ndarray:
    """(n, 3) bead centers of one particle, centered at the origin."""
    if self.structure == "fcc":
        pos = fcc_sphere(self.radius, self.spacing)
    else:
        pos = sphere_shell(self.radius, self.spacing)
    return pos

PlacedFiller dataclass

One placed CG particle.

Source code in AutoPoly/nanoparticles/cg.py
@dataclass
class PlacedFiller:
    """One placed CG particle."""
    filler: CGFiller
    center: np.ndarray
    positions: np.ndarray      # world bead centers
    envelope: float            # outermost bead distance + half a bead

fcc_sphere(radius: float, spacing: float) -> np.ndarray

FCC lattice sites (nearest-neighbor distance spacing) within radius of a lattice site at the origin.

Source code in AutoPoly/nanoparticles/cg.py
def fcc_sphere(radius: float, spacing: float) -> np.ndarray:
    """FCC lattice sites (nearest-neighbor distance ``spacing``) within
    ``radius`` of a lattice site at the origin."""
    a = spacing * np.sqrt(2.0)
    n = int(np.ceil(radius / a)) + 1
    r = np.arange(-n, n + 1)
    cells = np.stack(np.meshgrid(r, r, r, indexing="ij"), axis=-1).reshape(-1, 3)
    basis = np.array([[0, 0, 0], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]])
    pos = (cells[:, None, :] + basis[None, :, :]).reshape(-1, 3) * a
    keep = np.linalg.norm(pos, axis=1) <= radius + 1e-9
    return pos[keep]

sphere_shell(radius: float, spacing: float) -> np.ndarray

Near-uniform beads on a sphere of radius, about spacing apart (hexagonal area per bead, Fibonacci lattice).

Source code in AutoPoly/nanoparticles/cg.py
def sphere_shell(radius: float, spacing: float) -> np.ndarray:
    """Near-uniform beads on a sphere of ``radius``, about ``spacing``
    apart (hexagonal area per bead, Fibonacci lattice)."""
    from ..materials.topology import fibonacci_sphere
    area = 4.0 * np.pi * radius * radius
    n = max(1, int(round(area / (np.sqrt(3.0) / 2.0 * spacing * spacing))))
    return radius * fibonacci_sphere(n)

place_fillers(fillers: Sequence[CGFiller], box_size: float, bead_sigma: Dict[str, float], min_gap: float = 1.0, max_attempts: int = 5000) -> List[PlacedFiller]

Random sequential placement of all CG particles in the periodic cubic box [-L/2, L/2)^3 with envelope gaps >= min_gap (minimum image).

Raises:

Type Description
ValueError

A particle does not fit the box or no free position was found (box too small for the requested count).

Source code in AutoPoly/nanoparticles/cg.py
def place_fillers(fillers: Sequence[CGFiller], box_size: float,
                  bead_sigma: Dict[str, float], min_gap: float = 1.0,
                  max_attempts: int = 5000) -> List[PlacedFiller]:
    """
    Random sequential placement of all CG particles in the periodic cubic
    box [-L/2, L/2)^3 with envelope gaps >= ``min_gap`` (minimum image).

    Raises:
        ValueError: A particle does not fit the box or no free position
            was found (box too small for the requested count).
    """
    placed: List[PlacedFiller] = []
    for spec in fillers:
        local = spec.bead_positions()
        r_out = float(np.linalg.norm(local, axis=1).max())
        envelope = r_out + 0.5 * bead_sigma[spec.bead_type]
        if 2.0 * envelope + min_gap > box_size:
            raise ValueError(
                f"CG filler '{spec.name}' (envelope diameter "
                f"{2 * envelope:.2f} sigma + gap {min_gap}) does not fit the "
                f"periodic box ({box_size:.2f} sigma): use a larger box or a "
                "smaller radius")
        for k in range(spec.count):
            for _ in range(max_attempts):
                c = np.random.uniform(-box_size / 2, box_size / 2, 3)
                ok = True
                for other in placed:
                    d = c - other.center
                    d -= box_size * np.round(d / box_size)
                    if np.linalg.norm(d) < envelope + other.envelope + min_gap:
                        ok = False
                        break
                if ok:
                    break
            else:
                raise ValueError(
                    f"Could not place CG filler '{spec.name}' {k + 1}/"
                    f"{spec.count} without overlap after {max_attempts} "
                    "attempts: lower the filler count or enlarge the box")
            pos = local @ _random_rotation().T + c
            placed.append(PlacedFiller(spec, c, pos, envelope))
    return placed

filler_volume(fillers: Sequence[CGFiller], bead_sigma: Dict[str, float]) -> float

Total envelope volume of all CG particles (sigma^3).

Source code in AutoPoly/nanoparticles/cg.py
def filler_volume(fillers: Sequence[CGFiller],
                  bead_sigma: Dict[str, float]) -> float:
    """Total envelope volume of all CG particles (sigma^3)."""
    v = 0.0
    for f in fillers:
        r = f.radius + 0.5 * bead_sigma[f.bead_type]
        v += f.count * 4.0 / 3.0 * np.pi * r ** 3
    return v

motion_groups(fillers: Sequence[CGFiller]) -> Dict[str, List[str]]

motion -> filler bead-type names (each type has one motion).

Source code in AutoPoly/nanoparticles/cg.py
def motion_groups(fillers: Sequence[CGFiller]) -> Dict[str, List[str]]:
    """motion -> filler bead-type names (each type has one motion)."""
    by_type: Dict[str, str] = {}
    for f in fillers:
        prev = by_type.setdefault(f.bead_type, f.motion)
        if prev != f.motion:
            raise ValueError(
                f"CG filler bead type '{f.bead_type}' is used with motions "
                f"'{prev}' and '{f.motion}': give each motion its own bead "
                "type")
    groups: Dict[str, List[str]] = {}
    for t, m in by_type.items():
        groups.setdefault(m, []).append(t)
    return groups

group_lines(groups: Dict[str, List[str]]) -> List[str]

LAMMPS group commands; type tokens are numeric ids (direct backend) or @atom: names (moltemplate In Settings).

Source code in AutoPoly/nanoparticles/cg.py
def group_lines(groups: Dict[str, List[str]]) -> List[str]:
    """LAMMPS group commands; type tokens are numeric ids (direct backend)
    or @atom: names (moltemplate In Settings)."""
    every = [t for m in MOTIONS for t in groups.get(m, [])]
    lines = [f"group fillers type {' '.join(every)}"]
    for m in MOTIONS:
        if m in groups:
            lines.append(f"group {m}_fillers type {' '.join(groups[m])}")
    lines.append("group matrix subtract all fillers")
    return lines

production_lines(groups: Dict[str, List[str]]) -> str

Integrators: matrix NVT, one rigid body per rigid particle, frozen particles at rest.

Source code in AutoPoly/nanoparticles/cg.py
def production_lines(groups: Dict[str, List[str]]) -> str:
    """Integrators: matrix NVT, one rigid body per rigid particle, frozen
    particles at rest."""
    out = "fix             1 matrix nvt temp 1.0 1.0 0.1 tchain 3\n"
    if "rigid" in groups:
        # rigid/nvt, not rigid/nvt/small: the /small variant combined with
        # "neigh_modify exclude molecule/intra" aborts in LAMMPS 29Aug2024
        out += ("fix             2 rigid_fillers rigid/nvt molecule "
                "temp 1.0 1.0 1.0\n")
    if "frozen" in groups:
        out += ("velocity        frozen_fillers set 0.0 0.0 0.0\n"
                "fix             3 frozen_fillers setforce 0.0 0.0 0.0\n")
    return out

compression_hint(groups: Dict[str, List[str]]) -> str

Commented NPT block: the filler-aware SAW packs below melt density (periodic overlap checks), so the box is usually compressed first.

Source code in AutoPoly/nanoparticles/cg.py
def compression_hint(groups: Dict[str, List[str]]) -> str:
    """Commented NPT block: the filler-aware SAW packs below melt density
    (periodic overlap checks), so the box is usually compressed first."""
    if "rigid" in groups:
        baro = ("# fix             2 rigid_fillers rigid/npt molecule temp 1.0 "
                "1.0 1.0 iso 0.0 5.0 10.0 dilate all\n")
        undo = "# unfix           2\n"
    else:
        baro = ("# fix             1 matrix npt temp 1.0 1.0 0.1 iso 0.0 5.0 "
                "1.0 dilate all\n")
        undo = "# unfix           1\n"
    return ("\n# (optional) compression toward melt density before production:\n"
            "# one barostat controls the box and dilates all beads (rigid\n"
            "# fillers by their centers of mass); P ~ 5 suits a Kremer-Grest\n"
            "# melt at T = 1. Uncomment and place before the production run.\n"
            + undo + baro + "# run             50000\n")

summary(placed: Sequence[PlacedFiller], box_size: float) -> Dict

Filler block of BeadSpringSystem.get_system_info().

Source code in AutoPoly/nanoparticles/cg.py
def summary(placed: Sequence[PlacedFiller], box_size: float) -> Dict:
    """Filler block of BeadSpringSystem.get_system_info()."""
    species: Dict[str, Dict] = {}
    for p in placed:
        s = species.setdefault(p.filler.name, {
            "count": 0, "radius": p.filler.radius,
            "structure": p.filler.structure, "bead_type": p.filler.bead_type,
            "motion": p.filler.motion, "beads_per_particle": len(p.positions),
            "envelope_radius": p.envelope})
        s["count"] += 1
    v = sum(4.0 / 3.0 * np.pi * p.envelope ** 3 for p in placed)
    return {"species": species, "n_particles": len(placed),
            "n_beads": int(sum(len(p.positions) for p in placed)),
            "volume_fraction": v / box_size ** 3 if box_size else None}

Materials

AutoPoly.materials.registry

Material registry: the single source of truth for inorganic materials.

Every inorganic component (built-in substrate slab or nanoparticle) resolves its material through this registry. A MaterialSpec records identity and provenance -- phases/structure sources, shape builders, surface-termination models, the inorganic force-field adapters defined for it -- and where each builder lives (dotted "module:function" references resolved lazily), so the pipeline never branches on material names.

Registration is not a promise of simulation readiness. Capability is tracked per stage:

  • registered: metadata/selection exists,
  • geometry_ready: a built-in (or import) path produces structures that pass topology checks and can be exported,
  • surface_ready: a surface-termination model with chemical validation (valence, stoichiometry, charge) exists,
  • md_ready: at least one exact combination (material + phase + surface + inorganic FF + polymer FF + motion) is listed in the qualification matrix (AutoPoly.materials.qualification) with passing smoke-test evidence.

Five material families are registered as six IDs: sio2, al2o3, tio2, c, au, ag.

Created on 2026-11-13 @author: zwu

Classes:

Name Description
PhaseSpec

One phase / structure source of a material.

SurfaceStateSpec

One surface-termination model.

MaterialSpec

Registry entry of one inorganic material (see module docstring).

Functions:

Name Description
resolve_callable

Import a "package.module:function" reference.

register_material

Register a material (IDs and aliases must be unique).

get_material

Resolve a material by ID, formula or alias (case-insensitive):

PhaseSpec dataclass

One phase / structure source of a material.

Attributes:

Name Type Description
name str

Stable phase ID (e.g. "alpha_quartz").

description str

Human-readable description.

space_group str

Space group (crystalline phases) or "" (amorphous).

crystal Optional[str]

Key into AutoPoly.materials.crystals.CRYSTALS (bulk cell used by the built-in shape builders), or None when the phase is only available as an imported structure.

shapes Tuple[str, ...]

Shapes with a built-in builder for this phase.

aliases Tuple[str, ...]

Alternative names.

citation str

Structure reference.

Source code in AutoPoly/materials/registry.py
@dataclass(frozen=True)
class PhaseSpec:
    """
    One phase / structure source of a material.

    Attributes:
        name: Stable phase ID (e.g. "alpha_quartz").
        description: Human-readable description.
        space_group: Space group (crystalline phases) or "" (amorphous).
        crystal: Key into AutoPoly.materials.crystals.CRYSTALS (bulk cell
                 used by the built-in shape builders), or None when the
                 phase is only available as an imported structure.
        shapes: Shapes with a built-in builder for this phase.
        aliases: Alternative names.
        citation: Structure reference.
    """
    name: str
    description: str
    space_group: str = ""
    crystal: Optional[str] = None
    shapes: Tuple[str, ...] = ()
    aliases: Tuple[str, ...] = ()
    citation: str = ""

SurfaceStateSpec dataclass

One surface-termination model.

Attributes:

Name Type Description
name str

Stable ID ("hydroxylated", "stoichiometric", "h_passivated", "bare", "periodic").

description str

What the termination does.

site_types Tuple[str, ...]

Surface-site labels it produces.

validated bool

True when chemical validation (valence, stoichiometry, charge) is implemented and tested.

Source code in AutoPoly/materials/registry.py
@dataclass(frozen=True)
class SurfaceStateSpec:
    """
    One surface-termination model.

    Attributes:
        name: Stable ID ("hydroxylated", "stoichiometric", "h_passivated",
              "bare", "periodic").
        description: What the termination does.
        site_types: Surface-site labels it produces.
        validated: True when chemical validation (valence, stoichiometry,
                   charge) is implemented and tested.
    """
    name: str
    description: str
    site_types: Tuple[str, ...] = ()
    validated: bool = True

MaterialSpec dataclass

Registry entry of one inorganic material (see module docstring).

Attributes:

Name Type Description
id str

Stable material ID ("sio2", ...).

name str

Display name.

formula str

Chemical formula.

family str

"oxide", "carbon", or "metal".

elements Tuple[str, ...]

Elements a structure of this material may contain (including termination atoms).

aliases Tuple[str, ...]

Accepted alternative names (case-insensitive).

phases Dict[str, PhaseSpec]

phase ID -> PhaseSpec.

default_phase Optional[str]

Phase used when none is given.

surface_states Dict[str, SurfaceStateSpec]

termination ID -> SurfaceStateSpec.

default_surface Optional[str]

Termination used when none is given.

chemistry Optional[str]

Module implementing the chemistry adapter (assign_roles/validate/bond_cutoffs).

builders Dict[str, str]

shape -> "module:function" geometry builder.

force_fields Tuple[str, ...]

Inorganic FF adapter names defined for the material.

default_force_field Optional[str]

Adapter used when none is requested.

radius_range Tuple[float, float]

Allowed built-in particle radius range (A).

capabilities Dict[str, bool]

Declared stage -> bool for registered / geometry_ready / surface_ready (cross-checked by tests); md_ready is derived from the qualification matrix.

citations / notes

Provenance.

Methods:

Name Description
resolve_phase

Phase by ID or alias (None = default phase).

resolve_surface

Surface termination by ID (None = default).

builder

Geometry builder callable for a shape.

chemistry_module

The chemistry adapter module (None if not implemented).

capability

Capability of one stage. md_ready is derived from the

Source code in AutoPoly/materials/registry.py
@dataclass
class MaterialSpec:
    """
    Registry entry of one inorganic material (see module docstring).

    Attributes:
        id: Stable material ID ("sio2", ...).
        name: Display name.
        formula: Chemical formula.
        family: "oxide", "carbon", or "metal".
        elements: Elements a structure of this material may contain
                  (including termination atoms).
        aliases: Accepted alternative names (case-insensitive).
        phases: phase ID -> PhaseSpec.
        default_phase: Phase used when none is given.
        surface_states: termination ID -> SurfaceStateSpec.
        default_surface: Termination used when none is given.
        chemistry: Module implementing the chemistry adapter
                   (``assign_roles``/``validate``/``bond_cutoffs``).
        builders: shape -> "module:function" geometry builder.
        force_fields: Inorganic FF adapter names defined for the material.
        default_force_field: Adapter used when none is requested.
        radius_range: Allowed built-in particle radius range (A).
        capabilities: Declared stage -> bool for registered /
                      geometry_ready / surface_ready (cross-checked by
                      tests); md_ready is derived from the qualification
                      matrix.
        citations / notes: Provenance.
    """
    id: str
    name: str
    formula: str
    family: str
    elements: Tuple[str, ...]
    aliases: Tuple[str, ...] = ()
    phases: Dict[str, PhaseSpec] = field(default_factory=dict)
    default_phase: Optional[str] = None
    surface_states: Dict[str, SurfaceStateSpec] = field(default_factory=dict)
    default_surface: Optional[str] = None
    chemistry: Optional[str] = None
    builders: Dict[str, str] = field(default_factory=dict)
    force_fields: Tuple[str, ...] = ()
    default_force_field: Optional[str] = None
    radius_range: Tuple[float, float] = (5.0, 60.0)
    capabilities: Dict[str, bool] = field(default_factory=dict)
    citations: Tuple[str, ...] = ()
    notes: str = ""

    # ------------------------------------------------------------------
    def resolve_phase(self, phase: Optional[str]) -> PhaseSpec:
        """Phase by ID or alias (None = default phase)."""
        if phase is None:
            if self.default_phase is None:
                raise ValidationError(
                    f"Material '{self.id}' has no default phase; choose "
                    f"one of {sorted(self.phases)}"
                )
            return self.phases[self.default_phase]
        key = phase.lower()
        for p in self.phases.values():
            if key == p.name or key in (a.lower() for a in p.aliases):
                return p
        raise ValidationError(
            f"Unknown phase/structure '{phase}' for material '{self.id}'; "
            f"available: {sorted(self.phases)}"
        )

    def resolve_surface(self, surface: Optional[str]) -> SurfaceStateSpec:
        """Surface termination by ID (None = default)."""
        name = surface or self.default_surface
        if name is None or name not in self.surface_states:
            raise ValidationError(
                f"Unknown surface state '{surface}' for material "
                f"'{self.id}'; available: {sorted(self.surface_states)}"
            )
        return self.surface_states[name]

    def builder(self, shape: str) -> Callable:
        """Geometry builder callable for a shape."""
        if shape not in self.builders:
            raise ValidationError(
                f"Material '{self.id}' has no built-in '{shape}' builder; "
                f"available shapes: {sorted(self.builders)} (or import a "
                "structure with Nanoparticle.from_file)"
            )
        return resolve_callable(self.builders[shape])

    def chemistry_module(self):
        """The chemistry adapter module (None if not implemented)."""
        if self.chemistry is None:
            return None
        return importlib.import_module(self.chemistry)

    def capability(self, stage: str) -> bool:
        """
        Capability of one stage.  ``md_ready`` is derived from the
        qualification matrix (never declared); the other stages are
        declared here and cross-checked by the test suite.
        """
        if stage not in CAPABILITY_STAGES:
            raise ValidationError(f"Unknown capability stage '{stage}'")
        if stage == "md_ready":
            from .qualification import material_md_ready
            return material_md_ready(self.id)
        return bool(self.capabilities.get(stage, stage == "registered"))

    def capability_report(self) -> Dict[str, bool]:
        return {stage: self.capability(stage) for stage in CAPABILITY_STAGES}

resolve_phase(phase: Optional[str]) -> PhaseSpec

Phase by ID or alias (None = default phase).

Source code in AutoPoly/materials/registry.py
def resolve_phase(self, phase: Optional[str]) -> PhaseSpec:
    """Phase by ID or alias (None = default phase)."""
    if phase is None:
        if self.default_phase is None:
            raise ValidationError(
                f"Material '{self.id}' has no default phase; choose "
                f"one of {sorted(self.phases)}"
            )
        return self.phases[self.default_phase]
    key = phase.lower()
    for p in self.phases.values():
        if key == p.name or key in (a.lower() for a in p.aliases):
            return p
    raise ValidationError(
        f"Unknown phase/structure '{phase}' for material '{self.id}'; "
        f"available: {sorted(self.phases)}"
    )

resolve_surface(surface: Optional[str]) -> SurfaceStateSpec

Surface termination by ID (None = default).

Source code in AutoPoly/materials/registry.py
def resolve_surface(self, surface: Optional[str]) -> SurfaceStateSpec:
    """Surface termination by ID (None = default)."""
    name = surface or self.default_surface
    if name is None or name not in self.surface_states:
        raise ValidationError(
            f"Unknown surface state '{surface}' for material "
            f"'{self.id}'; available: {sorted(self.surface_states)}"
        )
    return self.surface_states[name]

builder(shape: str) -> Callable

Geometry builder callable for a shape.

Source code in AutoPoly/materials/registry.py
def builder(self, shape: str) -> Callable:
    """Geometry builder callable for a shape."""
    if shape not in self.builders:
        raise ValidationError(
            f"Material '{self.id}' has no built-in '{shape}' builder; "
            f"available shapes: {sorted(self.builders)} (or import a "
            "structure with Nanoparticle.from_file)"
        )
    return resolve_callable(self.builders[shape])

chemistry_module()

The chemistry adapter module (None if not implemented).

Source code in AutoPoly/materials/registry.py
def chemistry_module(self):
    """The chemistry adapter module (None if not implemented)."""
    if self.chemistry is None:
        return None
    return importlib.import_module(self.chemistry)

capability(stage: str) -> bool

Capability of one stage. md_ready is derived from the qualification matrix (never declared); the other stages are declared here and cross-checked by the test suite.

Source code in AutoPoly/materials/registry.py
def capability(self, stage: str) -> bool:
    """
    Capability of one stage.  ``md_ready`` is derived from the
    qualification matrix (never declared); the other stages are
    declared here and cross-checked by the test suite.
    """
    if stage not in CAPABILITY_STAGES:
        raise ValidationError(f"Unknown capability stage '{stage}'")
    if stage == "md_ready":
        from .qualification import material_md_ready
        return material_md_ready(self.id)
    return bool(self.capabilities.get(stage, stage == "registered"))

resolve_callable(ref: str) -> Callable

Import a "package.module:function" reference.

Source code in AutoPoly/materials/registry.py
def resolve_callable(ref: str) -> Callable:
    """Import a "package.module:function" reference."""
    module, _, name = ref.partition(":")
    try:
        return getattr(importlib.import_module(module), name)
    except (ImportError, AttributeError) as e:
        raise ValidationError(f"Cannot resolve builder '{ref}': {e}") from e

register_material(spec: MaterialSpec) -> None

Register a material (IDs and aliases must be unique).

Source code in AutoPoly/materials/registry.py
def register_material(spec: MaterialSpec) -> None:
    """Register a material (IDs and aliases must be unique)."""
    if spec.id in MATERIAL_REGISTRY:
        raise ValidationError(f"Material '{spec.id}' is already registered")
    taken = {a.lower() for m in MATERIAL_REGISTRY.values()
             for a in (m.id, m.formula, *m.aliases)}
    for alias in (spec.id, spec.formula, *spec.aliases):
        if alias.lower() in taken:
            raise ValidationError(
                f"Material alias '{alias}' of '{spec.id}' is already used"
            )
    MATERIAL_REGISTRY[spec.id] = spec

get_material(name: str) -> MaterialSpec

Resolve a material by ID, formula or alias (case-insensitive): get_material("SiO2") is get_material("silica").

Source code in AutoPoly/materials/registry.py
def get_material(name: str) -> MaterialSpec:
    """
    Resolve a material by ID, formula or alias (case-insensitive):
    ``get_material("SiO2") is get_material("silica")``.
    """
    key = str(name).strip().lower()
    for spec in MATERIAL_REGISTRY.values():
        if key in {spec.id.lower(), spec.formula.lower(),
                   *(a.lower() for a in spec.aliases)}:
            return spec
    raise ValidationError(
        f"Unknown material '{name}'. Registered materials: "
        f"{sorted(MATERIAL_REGISTRY)}"
    )

Qualification matrix

AutoPoly.materials.qualification

Material qualification matrix: which exact combinations are md_ready.

A combination is md_ready only when all of the following were independently tested for exactly that model:

(A) registry metadata       (B) geometry/topology
(C) surface termination     (D) inorganic parameterization
(E) polymer cross terms     (F) LAMMPS smoke test

QUALIFIED_COMBINATIONS lists those combinations together with the test evidence that exercises them (tests/test_nanocomposite_lammps_smoke.py and friends). Anything not listed is not md_ready: MD preparation of a nanoparticle fails with an actionable error instead of falling back to generic organic typing or guessed mixing. Material-level capability (md_ready in the registry) is derived from this table, never declared.

Built-in substrate slabs (SubstrateSpec(builder=...)) keep their legacy behavior: they are reported against this matrix but never blocked.

Created on 2026-11-13 @author: zwu

Classes:

Name Description
QualifiedCombination

One md_ready combination.

Functions:

Name Description
register_qualification

Add a qualified combination (IDs must be unique).

find_qualification

The qualified combination covering these settings, or None.

require_md_ready

Return the qualified combination or raise an actionable error naming

qualification_matrix

Per-material stage table (A-F) for docs/CI.

qualification_markdown

The qualification matrix as a Markdown table.

QualifiedCombination dataclass

One md_ready combination.

Attributes:

Name Type Description
id str

Stable identifier (reported in units.json / the FF report).

material str

Material ID.

phases Tuple[str, ...]

Phase IDs covered (structure sources).

geometry_types Tuple[str, ...]

Geometry types covered ("cluster", "sheet", ...).

surface str

Surface-termination ID.

inorganic_ff str

Inorganic adapter name.

polymer_ffs Tuple[str, ...]

Organic host force fields covered.

motions Tuple[str, ...]

Motion treatments covered.

cross_rule str

Rule for organic-inorganic pairs ("host" = follow the host force field's mixing rule; otherwise explicit).

evidence Tuple[str, ...]

Test node IDs exercising (B)-(F).

grafting Tuple[str, ...]

Grafting linkers covered ("silyl_ether"); empty = only ungrafted particles.

notes str

Caveats.

Source code in AutoPoly/materials/qualification.py
@dataclass(frozen=True)
class QualifiedCombination:
    """
    One md_ready combination.

    Attributes:
        id: Stable identifier (reported in units.json / the FF report).
        material: Material ID.
        phases: Phase IDs covered (structure sources).
        geometry_types: Geometry types covered ("cluster", "sheet", ...).
        surface: Surface-termination ID.
        inorganic_ff: Inorganic adapter name.
        polymer_ffs: Organic host force fields covered.
        motions: Motion treatments covered.
        cross_rule: Rule for organic-inorganic pairs ("host" = follow the
            host force field's mixing rule; otherwise explicit).
        evidence: Test node IDs exercising (B)-(F).
        grafting: Grafting linkers covered ("silyl_ether"); empty = only
            ungrafted particles.
        notes: Caveats.
    """
    id: str
    material: str
    phases: Tuple[str, ...]
    geometry_types: Tuple[str, ...]
    surface: str
    inorganic_ff: str
    polymer_ffs: Tuple[str, ...]
    motions: Tuple[str, ...]
    cross_rule: str
    evidence: Tuple[str, ...] = ()
    grafting: Tuple[str, ...] = ()
    notes: str = ""

    def covers(self, material, phase, geometry_type, surface, inorganic_ff,
               polymer_ff, motion, linker=None) -> bool:
        return (
            material == self.material
            and (phase in self.phases or "*" in self.phases)
            and geometry_type in self.geometry_types
            and surface == self.surface
            and inorganic_ff == self.inorganic_ff
            and polymer_ff in self.polymer_ffs
            and motion in self.motions
            and (linker is None) == (not self.grafting)
            and (linker is None or linker in self.grafting)
        )

    def to_dict(self) -> Dict[str, object]:
        return {
            "id": self.id,
            "material": self.material,
            "phases": list(self.phases),
            "geometry_types": list(self.geometry_types),
            "surface": self.surface,
            "inorganic_ff": self.inorganic_ff,
            "polymer_ffs": list(self.polymer_ffs),
            "motions": list(self.motions),
            "cross_rule": self.cross_rule,
            "evidence": list(self.evidence),
            "grafting": list(self.grafting),
            "notes": self.notes,
        }

register_qualification(q: QualifiedCombination) -> None

Add a qualified combination (IDs must be unique).

Source code in AutoPoly/materials/qualification.py
def register_qualification(q: QualifiedCombination) -> None:
    """Add a qualified combination (IDs must be unique)."""
    if any(x.id == q.id for x in QUALIFIED_COMBINATIONS):
        raise ValidationError(f"Qualification '{q.id}' already registered")
    QUALIFIED_COMBINATIONS.append(q)

find_qualification(material: str, phase: Optional[str], geometry_type: str, surface: str, inorganic_ff: str, polymer_ff: str, motion: str, linker: Optional[str] = None) -> Optional[QualifiedCombination]

The qualified combination covering these settings, or None.

Source code in AutoPoly/materials/qualification.py
def find_qualification(material: str, phase: Optional[str],
                       geometry_type: str, surface: str, inorganic_ff: str,
                       polymer_ff: str, motion: str,
                       linker: Optional[str] = None
                       ) -> Optional[QualifiedCombination]:
    """The qualified combination covering these settings, or None."""
    for q in QUALIFIED_COMBINATIONS:
        if q.covers(material, phase or "*", geometry_type, surface,
                    inorganic_ff, polymer_ff, motion, linker):
            return q
    return None

require_md_ready(material: str, phase: Optional[str], geometry_type: str, surface: str, inorganic_ff: str, polymer_ff: str, motion: str, linker: Optional[str] = None) -> QualifiedCombination

Return the qualified combination or raise an actionable error naming what is missing.

Source code in AutoPoly/materials/qualification.py
def require_md_ready(material: str, phase: Optional[str],
                     geometry_type: str, surface: str, inorganic_ff: str,
                     polymer_ff: str, motion: str,
                     linker: Optional[str] = None) -> QualifiedCombination:
    """
    Return the qualified combination or raise an actionable error naming
    what is missing.
    """
    q = find_qualification(material, phase, geometry_type, surface,
                           inorganic_ff, polymer_ff, motion, linker)
    if q is not None:
        return q
    near = [x for x in QUALIFIED_COMBINATIONS if x.material == material]
    hint = ""
    if near:
        hint = " Qualified combinations for this material:\n" + "\n".join(
            f"  - {x.id}: phases {list(x.phases)}, geometry "
            f"{list(x.geometry_types)}, surface '{x.surface}', FF "
            f"'{x.inorganic_ff}', polymer FFs {list(x.polymer_ffs)}, "
            f"motions {list(x.motions)}"
            + (f", grafting {list(x.grafting)}" if x.grafting else "")
            for x in near
        )
    else:
        hint = (" No combination of this material is qualified for MD "
                "yet; geometry export (xyz/structure JSON) is still "
                "available.")
    raise ValidationError(
        f"Combination not md_ready: material '{material}', phase "
        f"'{phase}', geometry '{geometry_type}', surface '{surface}', "
        f"inorganic FF '{inorganic_ff}', polymer FF '{polymer_ff}', "
        f"motion '{motion}'"
        + (f", grafting linker '{linker}'" if linker else "") + "." + hint
        + "\nTo proceed with an unvalidated model, supply explicit "
          "parameters and pass allow_unqualified=True (recorded as "
          "'user-qualified' in the force-field report)."
    )

qualification_matrix() -> List[Dict[str, object]]

Per-material stage table (A-F) for docs/CI.

A: registered; B: geometry_ready; C: surface_ready; D: an inorganic adapter is registered; E/F: a qualified combination exists.

Source code in AutoPoly/materials/qualification.py
def qualification_matrix() -> List[Dict[str, object]]:
    """
    Per-material stage table (A-F) for docs/CI.

    A: registered; B: geometry_ready; C: surface_ready; D: an inorganic
    adapter is registered; E/F: a qualified combination exists.
    """
    from .registry import MATERIAL_REGISTRY
    from .forcefields import registered_inorganic_ffs

    rows = []
    for mid, spec in MATERIAL_REGISTRY.items():
        quals = [q for q in QUALIFIED_COMBINATIONS if q.material == mid]
        rows.append({
            "material": mid,
            "A": True,
            "B": spec.capability("geometry_ready"),
            "C": spec.capability("surface_ready"),
            "D": bool(registered_inorganic_ffs(mid)),
            "E": bool(quals),
            "F": bool(quals) and all(q.evidence for q in quals),
            "md_ready_combinations": [q.id for q in quals],
        })
    return rows

qualification_markdown() -> str

The qualification matrix as a Markdown table.

Source code in AutoPoly/materials/qualification.py
def qualification_markdown() -> str:
    """The qualification matrix as a Markdown table."""
    head = ("| material | (A) registry | (B) geometry | (C) surface | "
            "(D) inorganic FF | (E) cross terms | (F) LAMMPS smoke | "
            "md_ready combinations |")
    sep = "|" + "---|" * 8
    lines = [head, sep]
    for r in qualification_matrix():
        mark = {True: "yes", False: "no"}
        lines.append(
            f"| `{r['material']}` | " + " | ".join(
                mark[bool(r[k])] for k in "ABCDEF")
            + " | " + (", ".join(f"`{c}`" for c in
                                 r["md_ready_combinations"]) or "-")
            + " |"
        )
    return "\n".join(lines)

Atomic structures

AutoPoly.materials.structure

Force-field-agnostic atomic structure for inorganic components.

AtomicStructure is the shared representation behind built-in substrate slabs and finite nanoparticles (clusters, sheets, rods, imported structures). It holds what a structure is -- elements, coordinates, cell/periodicity, bond topology with periodic image shifts, chemical-role and surface-site annotations, geometry descriptors and provenance -- and deliberately nothing about how it interacts: charges and Lennard-Jones parameters are attached later, after force-field selection, as a ParameterAssignment (see AutoPoly.materials.forcefields).

Conventions:

  • bonds[k] = (i, j) with images[k] = (nx, ny, nz): atom j is bonded to the periodic image of atom j shifted by n . cell (i.e. the bond vector is r_j + n . cell - r_i). Finite structures have all-zero images.
  • cell rows are the lattice vectors (A). Only axes with pbc=True are periodic; non-periodic axes may still carry an (informational) cell extent.
  • Per-atom annotations (roles, surface, site_types, component_ids) are optional lists aligned with elements.

Created on 2026-11-13 @author: zwu

Classes:

Name Description
AtomicStructure

Force-field-agnostic atomic structure (see module docstring).

Functions:

Name Description
element_mass

Atomic mass (amu) of an element symbol (RDKit table as fallback).

AtomicStructure dataclass

Force-field-agnostic atomic structure (see module docstring).

Attributes:

Name Type Description
elements List[str]

Element symbol per atom.

positions ndarray

(N, 3) Cartesian coordinates in Angstrom.

bonds List[Tuple[int, int]]

Bonded atom index pairs.

images ndarray

(M, 3) integer periodic image shift per bond (zeros for finite structures).

cell Optional[ndarray]

Optional (3, 3) lattice vectors (rows), Angstrom.

pbc Tuple[bool, bool, bool]

Per-axis periodicity flags.

roles Optional[List[str]]

Optional chemical role per atom (e.g. "Si", "OB", "OH", "HO" for silica), assigned by a chemistry adapter.

surface Optional[List[bool]]

Optional per-atom surface flag.

site_types Optional[List[Optional[str]]]

Optional per-atom surface-site label (e.g. "silanol").

normals Optional[ndarray]

Optional (N, 3) outward surface normals (zero for bulk).

component_ids Optional[List[int]]

Optional connected-component index per atom.

geometry_type str

"slab", "cluster", "sheet", "rod", or "imported".

descriptors Dict[str, Any]

Geometry descriptors (envelope, core volume, accessible area, ...) -- never force-field data.

provenance Dict[str, Any]

Source/builder/parameters/citations/seed record.

metadata Dict[str, Any]

Material identity and chemistry bookkeeping (material id, phase, termination, silanol counts, ...).

Methods:

Name Description
element_counts

Element -> count, in first-appearance order.

formula

Hill-like formula string (counts in first-appearance order).

masses

Per-atom masses (amu).

total_mass

Total mass (amu).

validate

Check internal consistency (array shapes, bond indices, PBC).

bond_vectors

(M, 3) bond vectors r_j + image.cell - r_i.

bond_lengths

(M,) bond lengths (A), periodic images applied.

neighbors

Per-atom bonded neighbor index lists (bond order preserved).

coordination

Per-atom bonded coordination number.

connected_components

Connected-component index per atom (largest component = 0).

annotate_components

Fill component_ids from the bond graph.

rotate

Rotate coordinates (and normals) about center (default origin).

bounding_radius

Max distance of any atom from center (default: centroid).

subset

New structure with only the atoms in keep (sorted, bonds whose

to_dict

JSON-serializable dict (round-trips through from_dict).

Source code in AutoPoly/materials/structure.py
@dataclass
class AtomicStructure:
    """
    Force-field-agnostic atomic structure (see module docstring).

    Attributes:
        elements: Element symbol per atom.
        positions: (N, 3) Cartesian coordinates in Angstrom.
        bonds: Bonded atom index pairs.
        images: (M, 3) integer periodic image shift per bond (zeros for
                finite structures).
        cell: Optional (3, 3) lattice vectors (rows), Angstrom.
        pbc: Per-axis periodicity flags.
        roles: Optional chemical role per atom (e.g. "Si", "OB", "OH",
               "HO" for silica), assigned by a chemistry adapter.
        surface: Optional per-atom surface flag.
        site_types: Optional per-atom surface-site label (e.g. "silanol").
        normals: Optional (N, 3) outward surface normals (zero for bulk).
        component_ids: Optional connected-component index per atom.
        geometry_type: "slab", "cluster", "sheet", "rod", or "imported".
        descriptors: Geometry descriptors (envelope, core volume,
                     accessible area, ...) -- never force-field data.
        provenance: Source/builder/parameters/citations/seed record.
        metadata: Material identity and chemistry bookkeeping (material
                  id, phase, termination, silanol counts, ...).
    """
    elements: List[str]
    positions: np.ndarray
    bonds: List[Tuple[int, int]] = field(default_factory=list)
    images: np.ndarray = None  # type: ignore[assignment]  # set in __post_init__
    cell: Optional[np.ndarray] = None
    pbc: Tuple[bool, bool, bool] = (False, False, False)
    roles: Optional[List[str]] = None
    surface: Optional[List[bool]] = None
    site_types: Optional[List[Optional[str]]] = None
    normals: Optional[np.ndarray] = None
    component_ids: Optional[List[int]] = None
    geometry_type: str = "cluster"
    descriptors: Dict[str, Any] = field(default_factory=dict)
    provenance: Dict[str, Any] = field(default_factory=dict)
    metadata: Dict[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        self.elements = [str(e) for e in self.elements]
        self.positions = np.asarray(self.positions, dtype=float).reshape(-1, 3)
        self.bonds = [(int(i), int(j)) for i, j in self.bonds]
        if self.images is None:
            self.images = np.zeros((len(self.bonds), 3), dtype=int)
        else:
            self.images = np.asarray(self.images, dtype=int).reshape(-1, 3)
        if self.cell is not None:
            self.cell = np.asarray(self.cell, dtype=float).reshape(3, 3)
        p = tuple(self.pbc)
        self.pbc = (bool(p[0]), bool(p[1]), bool(p[2]))
        if self.normals is not None:
            self.normals = np.asarray(self.normals, dtype=float).reshape(-1, 3)
        self.validate()

    # ------------------------------------------------------------------
    # Basic properties
    # ------------------------------------------------------------------
    @property
    def n_atoms(self) -> int:
        return len(self.elements)

    @property
    def n_bonds(self) -> int:
        return len(self.bonds)

    @property
    def is_periodic(self) -> bool:
        return any(self.pbc)

    def element_counts(self) -> Dict[str, int]:
        """Element -> count, in first-appearance order."""
        counts: Dict[str, int] = {}
        for e in self.elements:
            counts[e] = counts.get(e, 0) + 1
        return counts

    def formula(self) -> str:
        """Hill-like formula string (counts in first-appearance order)."""
        return "".join(
            f"{e}{n if n > 1 else ''}" for e, n in self.element_counts().items()
        )

    def masses(self) -> np.ndarray:
        """Per-atom masses (amu)."""
        return np.array([element_mass(e) for e in self.elements])

    def total_mass(self) -> float:
        """Total mass (amu)."""
        return float(self.masses().sum())

    def center_of_mass(self) -> np.ndarray:
        m = self.masses()
        return (self.positions * m[:, None]).sum(axis=0) / m.sum()

    def indices_of(self, element: str) -> np.ndarray:
        return np.array(
            [i for i, e in enumerate(self.elements) if e == element], dtype=int
        )

    # ------------------------------------------------------------------
    # Validation
    # ------------------------------------------------------------------
    def validate(self) -> None:
        """
        Check internal consistency (array shapes, bond indices, PBC).

        Raises:
            ValidationError: On any inconsistency.
        """
        n = self.n_atoms
        if self.positions.shape != (n, 3):
            raise ValidationError(
                f"AtomicStructure: positions shape {self.positions.shape} "
                f"does not match {n} elements"
            )
        if not np.all(np.isfinite(self.positions)):
            raise ValidationError("AtomicStructure: non-finite coordinates")
        if self.images.shape != (len(self.bonds), 3):
            raise ValidationError(
                f"AtomicStructure: {len(self.bonds)} bonds but images shape "
                f"{self.images.shape}"
            )
        seen = set()
        for k, (i, j) in enumerate(self.bonds):
            if not (0 <= i < n and 0 <= j < n):
                raise ValidationError(
                    f"AtomicStructure: bond {k} ({i}, {j}) references an "
                    f"atom outside 0..{n - 1}"
                )
            img = tuple(int(x) for x in self.images[k])
            if i == j and img == (0, 0, 0):
                raise ValidationError(
                    f"AtomicStructure: bond {k} bonds atom {i} to itself"
                )
            key = (min(i, j), max(i, j),
                   img if i <= j else tuple(-x for x in img))
            if key in seen:
                raise ValidationError(
                    f"AtomicStructure: duplicate bond ({i}, {j}) image {img}"
                )
            seen.add(key)
        if any(self.pbc):
            if self.cell is None:
                raise ValidationError(
                    "AtomicStructure: periodic axes require a cell"
                )
            for axis, periodic in enumerate(self.pbc):
                if not periodic and np.any(self.images[:, axis] != 0):
                    raise ValidationError(
                        f"AtomicStructure: bond image shifts along "
                        f"non-periodic axis {'xyz'[axis]}"
                    )
        elif np.any(self.images != 0):
            raise ValidationError(
                "AtomicStructure: finite structure has non-zero bond images"
            )
        for name in ("roles", "surface", "site_types", "component_ids"):
            values = getattr(self, name)
            if values is not None and len(values) != n:
                raise ValidationError(
                    f"AtomicStructure: '{name}' has {len(values)} entries "
                    f"for {n} atoms"
                )
        if self.normals is not None and self.normals.shape != (n, 3):
            raise ValidationError(
                f"AtomicStructure: normals shape {self.normals.shape} does "
                f"not match {n} atoms"
            )
        if self.geometry_type not in GEOMETRY_TYPES:
            raise ValidationError(
                f"AtomicStructure: unknown geometry_type "
                f"'{self.geometry_type}'; choose from {GEOMETRY_TYPES}"
            )

    # ------------------------------------------------------------------
    # Geometry helpers
    # ------------------------------------------------------------------
    def bond_vectors(self) -> np.ndarray:
        """(M, 3) bond vectors r_j + image.cell - r_i."""
        if not self.bonds:
            return np.zeros((0, 3))
        b = np.asarray(self.bonds, dtype=int)
        vec = self.positions[b[:, 1]] - self.positions[b[:, 0]]
        if self.cell is not None and np.any(self.images):
            vec = vec + self.images @ self.cell
        return vec

    def bond_lengths(self) -> np.ndarray:
        """(M,) bond lengths (A), periodic images applied."""
        return np.linalg.norm(self.bond_vectors(), axis=1)

    def neighbors(self) -> List[List[int]]:
        """Per-atom bonded neighbor index lists (bond order preserved)."""
        nbrs: List[List[int]] = [[] for _ in range(self.n_atoms)]
        for i, j in self.bonds:
            nbrs[i].append(j)
            nbrs[j].append(i)
        return nbrs

    def coordination(self) -> np.ndarray:
        """Per-atom bonded coordination number."""
        coord = np.zeros(self.n_atoms, dtype=int)
        for i, j in self.bonds:
            coord[i] += 1
            coord[j] += 1
        return coord

    def connected_components(self) -> List[int]:
        """Connected-component index per atom (largest component = 0)."""
        from .topology import connected_components
        return connected_components(self.n_atoms, self.bonds)

    def annotate_components(self) -> None:
        """Fill ``component_ids`` from the bond graph."""
        self.component_ids = self.connected_components()

    def translate(self, vector: Sequence[float]) -> None:
        self.positions = self.positions + np.asarray(vector, dtype=float)

    def rotate(self, matrix: np.ndarray, center: Optional[Sequence[float]] = None) -> None:
        """Rotate coordinates (and normals) about ``center`` (default origin)."""
        r = np.asarray(matrix, dtype=float).reshape(3, 3)
        c = np.zeros(3) if center is None else np.asarray(center, dtype=float)
        self.positions = (self.positions - c) @ r.T + c
        if self.normals is not None:
            self.normals = self.normals @ r.T

    def radius_of_gyration(self) -> float:
        com = self.center_of_mass()
        m = self.masses()
        d2 = ((self.positions - com) ** 2).sum(axis=1)
        return float(np.sqrt((m * d2).sum() / m.sum()))

    def bounding_radius(self, center: Optional[Sequence[float]] = None) -> float:
        """Max distance of any atom from ``center`` (default: centroid)."""
        c = (self.positions.mean(axis=0) if center is None
             else np.asarray(center, dtype=float))
        return float(np.linalg.norm(self.positions - c, axis=1).max())

    # ------------------------------------------------------------------
    # Subsetting / editing
    # ------------------------------------------------------------------
    def subset(self, keep: Iterable[int]) -> "AtomicStructure":
        """
        New structure with only the atoms in ``keep`` (sorted, bonds whose
        both ends survive are kept with their images).
        """
        keep_idx = sorted(set(int(k) for k in keep))
        remap = {old: new for new, old in enumerate(keep_idx)}
        bonds, images = [], []
        for (i, j), img in zip(self.bonds, self.images):
            if i in remap and j in remap:
                bonds.append((remap[i], remap[j]))
                images.append(img)

        def pick(values):
            if values is None:
                return None
            return [values[k] for k in keep_idx]

        return AtomicStructure(
            elements=[self.elements[k] for k in keep_idx],
            positions=self.positions[keep_idx] if keep_idx
            else np.zeros((0, 3)),
            bonds=bonds,
            images=np.array(images, dtype=int).reshape(-1, 3),
            cell=None if self.cell is None else self.cell.copy(),
            pbc=self.pbc,
            roles=pick(self.roles),
            surface=pick(self.surface),
            site_types=pick(self.site_types),
            normals=None if self.normals is None
            else self.normals[keep_idx].copy(),
            component_ids=pick(self.component_ids),
            geometry_type=self.geometry_type,
            descriptors=copy.deepcopy(self.descriptors),
            provenance=copy.deepcopy(self.provenance),
            metadata=copy.deepcopy(self.metadata),
        )

    def copy(self) -> "AtomicStructure":
        return copy.deepcopy(self)

    # ------------------------------------------------------------------
    # Serialization (JSON-compatible)
    # ------------------------------------------------------------------
    def to_dict(self) -> Dict[str, Any]:
        """JSON-serializable dict (round-trips through from_dict)."""
        return {
            "elements": list(self.elements),
            "positions": [[float(x) for x in p] for p in self.positions],
            "bonds": [[int(i), int(j)] for i, j in self.bonds],
            "images": [[int(x) for x in img] for img in self.images],
            "cell": None if self.cell is None
            else [[float(x) for x in row] for row in self.cell],
            "pbc": [bool(p) for p in self.pbc],
            "roles": None if self.roles is None else list(self.roles),
            "surface": None if self.surface is None
            else [bool(s) for s in self.surface],
            "site_types": None if self.site_types is None
            else list(self.site_types),
            "normals": None if self.normals is None
            else [[float(x) for x in n] for n in self.normals],
            "component_ids": None if self.component_ids is None
            else [int(c) for c in self.component_ids],
            "geometry_type": self.geometry_type,
            "descriptors": _jsonable(self.descriptors),
            "provenance": _jsonable(self.provenance),
            "metadata": _jsonable(self.metadata),
        }

    @staticmethod
    def from_dict(data: Dict[str, Any]) -> "AtomicStructure":
        bonds = [tuple(b) for b in data.get("bonds", [])]
        images = data.get("images")
        return AtomicStructure(
            elements=list(data["elements"]),
            positions=np.array(data["positions"], dtype=float).reshape(-1, 3),
            bonds=bonds,
            images=None if images is None
            else np.array(images, dtype=int).reshape(-1, 3),
            cell=None if data.get("cell") is None
            else np.array(data["cell"], dtype=float),
            pbc=tuple(data.get("pbc", (False, False, False))),
            roles=data.get("roles"),
            surface=data.get("surface"),
            site_types=data.get("site_types"),
            normals=None if data.get("normals") is None
            else np.array(data["normals"], dtype=float),
            component_ids=data.get("component_ids"),
            geometry_type=data.get("geometry_type", "cluster"),
            descriptors=dict(data.get("descriptors", {})),
            provenance=dict(data.get("provenance", {})),
            metadata=dict(data.get("metadata", {})),
        )

element_counts() -> Dict[str, int]

Element -> count, in first-appearance order.

Source code in AutoPoly/materials/structure.py
def element_counts(self) -> Dict[str, int]:
    """Element -> count, in first-appearance order."""
    counts: Dict[str, int] = {}
    for e in self.elements:
        counts[e] = counts.get(e, 0) + 1
    return counts

formula() -> str

Hill-like formula string (counts in first-appearance order).

Source code in AutoPoly/materials/structure.py
def formula(self) -> str:
    """Hill-like formula string (counts in first-appearance order)."""
    return "".join(
        f"{e}{n if n > 1 else ''}" for e, n in self.element_counts().items()
    )

masses() -> np.ndarray

Per-atom masses (amu).

Source code in AutoPoly/materials/structure.py
def masses(self) -> np.ndarray:
    """Per-atom masses (amu)."""
    return np.array([element_mass(e) for e in self.elements])

total_mass() -> float

Total mass (amu).

Source code in AutoPoly/materials/structure.py
def total_mass(self) -> float:
    """Total mass (amu)."""
    return float(self.masses().sum())

validate() -> None

Check internal consistency (array shapes, bond indices, PBC).

Raises:

Type Description
ValidationError

On any inconsistency.

Source code in AutoPoly/materials/structure.py
def validate(self) -> None:
    """
    Check internal consistency (array shapes, bond indices, PBC).

    Raises:
        ValidationError: On any inconsistency.
    """
    n = self.n_atoms
    if self.positions.shape != (n, 3):
        raise ValidationError(
            f"AtomicStructure: positions shape {self.positions.shape} "
            f"does not match {n} elements"
        )
    if not np.all(np.isfinite(self.positions)):
        raise ValidationError("AtomicStructure: non-finite coordinates")
    if self.images.shape != (len(self.bonds), 3):
        raise ValidationError(
            f"AtomicStructure: {len(self.bonds)} bonds but images shape "
            f"{self.images.shape}"
        )
    seen = set()
    for k, (i, j) in enumerate(self.bonds):
        if not (0 <= i < n and 0 <= j < n):
            raise ValidationError(
                f"AtomicStructure: bond {k} ({i}, {j}) references an "
                f"atom outside 0..{n - 1}"
            )
        img = tuple(int(x) for x in self.images[k])
        if i == j and img == (0, 0, 0):
            raise ValidationError(
                f"AtomicStructure: bond {k} bonds atom {i} to itself"
            )
        key = (min(i, j), max(i, j),
               img if i <= j else tuple(-x for x in img))
        if key in seen:
            raise ValidationError(
                f"AtomicStructure: duplicate bond ({i}, {j}) image {img}"
            )
        seen.add(key)
    if any(self.pbc):
        if self.cell is None:
            raise ValidationError(
                "AtomicStructure: periodic axes require a cell"
            )
        for axis, periodic in enumerate(self.pbc):
            if not periodic and np.any(self.images[:, axis] != 0):
                raise ValidationError(
                    f"AtomicStructure: bond image shifts along "
                    f"non-periodic axis {'xyz'[axis]}"
                )
    elif np.any(self.images != 0):
        raise ValidationError(
            "AtomicStructure: finite structure has non-zero bond images"
        )
    for name in ("roles", "surface", "site_types", "component_ids"):
        values = getattr(self, name)
        if values is not None and len(values) != n:
            raise ValidationError(
                f"AtomicStructure: '{name}' has {len(values)} entries "
                f"for {n} atoms"
            )
    if self.normals is not None and self.normals.shape != (n, 3):
        raise ValidationError(
            f"AtomicStructure: normals shape {self.normals.shape} does "
            f"not match {n} atoms"
        )
    if self.geometry_type not in GEOMETRY_TYPES:
        raise ValidationError(
            f"AtomicStructure: unknown geometry_type "
            f"'{self.geometry_type}'; choose from {GEOMETRY_TYPES}"
        )

bond_vectors() -> np.ndarray

(M, 3) bond vectors r_j + image.cell - r_i.

Source code in AutoPoly/materials/structure.py
def bond_vectors(self) -> np.ndarray:
    """(M, 3) bond vectors r_j + image.cell - r_i."""
    if not self.bonds:
        return np.zeros((0, 3))
    b = np.asarray(self.bonds, dtype=int)
    vec = self.positions[b[:, 1]] - self.positions[b[:, 0]]
    if self.cell is not None and np.any(self.images):
        vec = vec + self.images @ self.cell
    return vec

bond_lengths() -> np.ndarray

(M,) bond lengths (A), periodic images applied.

Source code in AutoPoly/materials/structure.py
def bond_lengths(self) -> np.ndarray:
    """(M,) bond lengths (A), periodic images applied."""
    return np.linalg.norm(self.bond_vectors(), axis=1)

neighbors() -> List[List[int]]

Per-atom bonded neighbor index lists (bond order preserved).

Source code in AutoPoly/materials/structure.py
def neighbors(self) -> List[List[int]]:
    """Per-atom bonded neighbor index lists (bond order preserved)."""
    nbrs: List[List[int]] = [[] for _ in range(self.n_atoms)]
    for i, j in self.bonds:
        nbrs[i].append(j)
        nbrs[j].append(i)
    return nbrs

coordination() -> np.ndarray

Per-atom bonded coordination number.

Source code in AutoPoly/materials/structure.py
def coordination(self) -> np.ndarray:
    """Per-atom bonded coordination number."""
    coord = np.zeros(self.n_atoms, dtype=int)
    for i, j in self.bonds:
        coord[i] += 1
        coord[j] += 1
    return coord

connected_components() -> List[int]

Connected-component index per atom (largest component = 0).

Source code in AutoPoly/materials/structure.py
def connected_components(self) -> List[int]:
    """Connected-component index per atom (largest component = 0)."""
    from .topology import connected_components
    return connected_components(self.n_atoms, self.bonds)

annotate_components() -> None

Fill component_ids from the bond graph.

Source code in AutoPoly/materials/structure.py
def annotate_components(self) -> None:
    """Fill ``component_ids`` from the bond graph."""
    self.component_ids = self.connected_components()

rotate(matrix: np.ndarray, center: Optional[Sequence[float]] = None) -> None

Rotate coordinates (and normals) about center (default origin).

Source code in AutoPoly/materials/structure.py
def rotate(self, matrix: np.ndarray, center: Optional[Sequence[float]] = None) -> None:
    """Rotate coordinates (and normals) about ``center`` (default origin)."""
    r = np.asarray(matrix, dtype=float).reshape(3, 3)
    c = np.zeros(3) if center is None else np.asarray(center, dtype=float)
    self.positions = (self.positions - c) @ r.T + c
    if self.normals is not None:
        self.normals = self.normals @ r.T

bounding_radius(center: Optional[Sequence[float]] = None) -> float

Max distance of any atom from center (default: centroid).

Source code in AutoPoly/materials/structure.py
def bounding_radius(self, center: Optional[Sequence[float]] = None) -> float:
    """Max distance of any atom from ``center`` (default: centroid)."""
    c = (self.positions.mean(axis=0) if center is None
         else np.asarray(center, dtype=float))
    return float(np.linalg.norm(self.positions - c, axis=1).max())

subset(keep: Iterable[int]) -> AtomicStructure

New structure with only the atoms in keep (sorted, bonds whose both ends survive are kept with their images).

Source code in AutoPoly/materials/structure.py
def subset(self, keep: Iterable[int]) -> "AtomicStructure":
    """
    New structure with only the atoms in ``keep`` (sorted, bonds whose
    both ends survive are kept with their images).
    """
    keep_idx = sorted(set(int(k) for k in keep))
    remap = {old: new for new, old in enumerate(keep_idx)}
    bonds, images = [], []
    for (i, j), img in zip(self.bonds, self.images):
        if i in remap and j in remap:
            bonds.append((remap[i], remap[j]))
            images.append(img)

    def pick(values):
        if values is None:
            return None
        return [values[k] for k in keep_idx]

    return AtomicStructure(
        elements=[self.elements[k] for k in keep_idx],
        positions=self.positions[keep_idx] if keep_idx
        else np.zeros((0, 3)),
        bonds=bonds,
        images=np.array(images, dtype=int).reshape(-1, 3),
        cell=None if self.cell is None else self.cell.copy(),
        pbc=self.pbc,
        roles=pick(self.roles),
        surface=pick(self.surface),
        site_types=pick(self.site_types),
        normals=None if self.normals is None
        else self.normals[keep_idx].copy(),
        component_ids=pick(self.component_ids),
        geometry_type=self.geometry_type,
        descriptors=copy.deepcopy(self.descriptors),
        provenance=copy.deepcopy(self.provenance),
        metadata=copy.deepcopy(self.metadata),
    )

to_dict() -> Dict[str, Any]

JSON-serializable dict (round-trips through from_dict).

Source code in AutoPoly/materials/structure.py
def to_dict(self) -> Dict[str, Any]:
    """JSON-serializable dict (round-trips through from_dict)."""
    return {
        "elements": list(self.elements),
        "positions": [[float(x) for x in p] for p in self.positions],
        "bonds": [[int(i), int(j)] for i, j in self.bonds],
        "images": [[int(x) for x in img] for img in self.images],
        "cell": None if self.cell is None
        else [[float(x) for x in row] for row in self.cell],
        "pbc": [bool(p) for p in self.pbc],
        "roles": None if self.roles is None else list(self.roles),
        "surface": None if self.surface is None
        else [bool(s) for s in self.surface],
        "site_types": None if self.site_types is None
        else list(self.site_types),
        "normals": None if self.normals is None
        else [[float(x) for x in n] for n in self.normals],
        "component_ids": None if self.component_ids is None
        else [int(c) for c in self.component_ids],
        "geometry_type": self.geometry_type,
        "descriptors": _jsonable(self.descriptors),
        "provenance": _jsonable(self.provenance),
        "metadata": _jsonable(self.metadata),
    }

element_mass(element: str) -> float

Atomic mass (amu) of an element symbol (RDKit table as fallback).

Source code in AutoPoly/materials/structure.py
def element_mass(element: str) -> float:
    """Atomic mass (amu) of an element symbol (RDKit table as fallback)."""
    if element in ATOMIC_MASSES:
        return ATOMIC_MASSES[element]
    try:
        from rdkit import Chem
        return float(Chem.GetPeriodicTable().GetAtomicWeight(element))
    except Exception:
        raise ValidationError(
            f"No atomic mass tabulated for element '{element}'"
        ) from None

Inorganic force fields

AutoPoly.materials.forcefields.registry

Versioned inorganic force-field (parameter) adapters.

An InorganicForceField maps the chemical roles assigned by a material's chemistry adapter (e.g. silica "Si"/"OB"/"OH"/"HO") onto moltemplate atom types, masses, charges and 12-6 Lennard-Jones parameters, and records what the parameter set may be used for:

  • which materials it is defined for,
  • the combining rule it was parameterized with (explicit cross terms are generated with it; see compatibility.py),
  • the allowed motion treatments (built-in sets are nonbonded-only, so only "frozen" and "rigid" are permitted -- never "flexible"),
  • the O-H (or other cap) bond length used when terminating surfaces,
  • citations and provenance.

Applying an adapter to an AtomicStructure yields a ParameterAssignment (the "typed structure"); the structure itself is never modified, so one geometry can be typed under several compatible force fields.

Created on 2026-11-13 @author: zwu

Classes:

Name Description
RoleParameters

Nonbonded parameters of one chemical role.

ParameterAssignment

Force-field parameters attached to an AtomicStructure (typed structure).

InorganicForceField

One named, versioned inorganic parameter set (see module docstring).

Functions:

Name Description
register_inorganic_ff

Register an inorganic force-field adapter (and its aliases).

get_inorganic_ff

Resolve an inorganic force field by registry name, or by alias in the

registered_inorganic_ffs

Sorted adapter names (optionally only those for one material).

RoleParameters dataclass

Nonbonded parameters of one chemical role.

Source code in AutoPoly/materials/forcefields/registry.py
@dataclass(frozen=True)
class RoleParameters:
    """Nonbonded parameters of one chemical role."""
    type_name: str
    mass: float
    charge: float
    epsilon: float
    sigma: float

    @staticmethod
    def from_table(entry: Mapping) -> "RoleParameters":
        return RoleParameters(
            type_name=str(entry["type"]),
            mass=float(entry["mass"]),
            charge=float(entry["charge"]),
            epsilon=float(entry["epsilon"]),
            sigma=float(entry["sigma"]),
        )

ParameterAssignment dataclass

Force-field parameters attached to an AtomicStructure (typed structure).

Attributes:

Name Type Description
force_field str

Adapter name (e.g. "interface_silica").

version str

Adapter version string.

roles List[str]

Role per atom (copied from the structure).

type_names List[str]

Moltemplate @atom type per atom.

charges ndarray

(N,) per-atom charges (e).

type_masses Dict[str, float]

type -> mass (amu).

type_lj Dict[str, Tuple[float, float]]

type -> (epsilon kcal/mol, sigma A).

combining_rule str

Rule for explicit cross terms.

motions Tuple[str, ...]

Motion treatments the parameters are valid for.

notes List[str]

Free-form provenance notes (overrides applied, ...).

Methods:

Name Description
type_table

type -> {mass, epsilon, sigma, charges...} summary (sorted).

Source code in AutoPoly/materials/forcefields/registry.py
@dataclass
class ParameterAssignment:
    """
    Force-field parameters attached to an AtomicStructure (typed structure).

    Attributes:
        force_field: Adapter name (e.g. "interface_silica").
        version: Adapter version string.
        roles: Role per atom (copied from the structure).
        type_names: Moltemplate @atom type per atom.
        charges: (N,) per-atom charges (e).
        type_masses: type -> mass (amu).
        type_lj: type -> (epsilon kcal/mol, sigma A).
        combining_rule: Rule for explicit cross terms.
        motions: Motion treatments the parameters are valid for.
        notes: Free-form provenance notes (overrides applied, ...).
    """
    force_field: str
    version: str
    roles: List[str]
    type_names: List[str]
    charges: np.ndarray
    type_masses: Dict[str, float]
    type_lj: Dict[str, Tuple[float, float]]
    combining_rule: str = "host"
    motions: Tuple[str, ...] = ("frozen", "rigid")
    notes: List[str] = field(default_factory=list)

    @property
    def net_charge(self) -> float:
        return float(np.sum(self.charges))

    def per_atom_lj(self) -> List[Tuple[float, float]]:
        return [self.type_lj[t] for t in self.type_names]

    def type_table(self) -> Dict[str, Dict[str, float]]:
        """type -> {mass, epsilon, sigma, charges...} summary (sorted)."""
        out = {}
        for t in sorted(self.type_lj):
            qs = sorted({round(float(q), 6) for q, tn in
                         zip(self.charges, self.type_names) if tn == t})
            eps, sig = self.type_lj[t]
            out[t] = {"mass": self.type_masses[t], "epsilon": eps,
                      "sigma": sig, "charges": qs,
                      "count": sum(tn == t for tn in self.type_names)}
        return out

type_table() -> Dict[str, Dict[str, float]]

type -> {mass, epsilon, sigma, charges...} summary (sorted).

Source code in AutoPoly/materials/forcefields/registry.py
def type_table(self) -> Dict[str, Dict[str, float]]:
    """type -> {mass, epsilon, sigma, charges...} summary (sorted)."""
    out = {}
    for t in sorted(self.type_lj):
        qs = sorted({round(float(q), 6) for q, tn in
                     zip(self.charges, self.type_names) if tn == t})
        eps, sig = self.type_lj[t]
        out[t] = {"mass": self.type_masses[t], "epsilon": eps,
                  "sigma": sig, "charges": qs,
                  "count": sum(tn == t for tn in self.type_names)}
    return out

InorganicForceField dataclass

One named, versioned inorganic parameter set (see module docstring).

Attributes:

Name Type Description
name str

Registry name (e.g. "interface_silica").

version str

Parameter-set version.

label str

Short human-readable label.

material_ids Tuple[str, ...]

Material IDs the set is defined for.

roles Dict[str, RoleParameters]

role -> RoleParameters.

combining_rule str

"arithmetic" (Lorentz-Berthelot), "geometric", or "host" (follow the organic host force field's rule).

motions Tuple[str, ...]

Allowed motion treatments.

cap_bond_length Optional[float]

Cap (e.g. O-H) bond length used for termination.

aliases Tuple[str, ...]

Alternative names (e.g. "interface").

citations Tuple[str, ...]

Literature references.

notes str

Provenance and usage notes.

Methods:

Name Description
with_overrides

Role table with per-role overrides applied (unknown roles ignored).

assign

Type a structure from its per-atom roles.

Source code in AutoPoly/materials/forcefields/registry.py
@dataclass
class InorganicForceField:
    """
    One named, versioned inorganic parameter set (see module docstring).

    Attributes:
        name: Registry name (e.g. "interface_silica").
        version: Parameter-set version.
        label: Short human-readable label.
        material_ids: Material IDs the set is defined for.
        roles: role -> RoleParameters.
        combining_rule: "arithmetic" (Lorentz-Berthelot), "geometric", or
            "host" (follow the organic host force field's rule).
        motions: Allowed motion treatments.
        cap_bond_length: Cap (e.g. O-H) bond length used for termination.
        aliases: Alternative names (e.g. "interface").
        citations: Literature references.
        notes: Provenance and usage notes.
    """
    name: str
    version: str
    label: str
    material_ids: Tuple[str, ...]
    roles: Dict[str, RoleParameters]
    combining_rule: str = "host"
    motions: Tuple[str, ...] = ("frozen", "rigid")
    cap_bond_length: Optional[float] = None
    aliases: Tuple[str, ...] = ()
    citations: Tuple[str, ...] = ()
    notes: str = ""

    def __post_init__(self) -> None:
        if self.combining_rule not in COMBINING_RULES:
            raise ValidationError(
                f"Inorganic force field '{self.name}': unknown combining "
                f"rule '{self.combining_rule}'"
            )
        bad = [m for m in self.motions if m not in MOTIONS]
        if bad:
            raise ValidationError(
                f"Inorganic force field '{self.name}': unknown motions {bad}"
            )

    @property
    def role_names(self) -> Tuple[str, ...]:
        return tuple(self.roles)

    def with_overrides(
        self,
        types: Optional[Mapping[str, str]] = None,
        charges: Optional[Mapping[str, float]] = None,
        lj: Optional[Mapping[str, Sequence[float]]] = None,
    ) -> Dict[str, RoleParameters]:
        """Role table with per-role overrides applied (unknown roles ignored)."""
        table = dict(self.roles)
        for role, params in list(table.items()):
            type_name, q = params.type_name, params.charge
            eps, sig = params.epsilon, params.sigma
            if types and role in types:
                type_name = str(types[role])
            if charges and role in charges:
                q = float(charges[role])
            if lj and role in lj:
                eps, sig = float(lj[role][0]), float(lj[role][1])
            table[role] = RoleParameters(type_name, params.mass, q, eps, sig)
        return table

    def assign(
        self,
        roles: Sequence[str],
        table: Optional[Mapping[str, RoleParameters]] = None,
        notes: Optional[List[str]] = None,
    ) -> ParameterAssignment:
        """
        Type a structure from its per-atom roles.

        Args:
            roles: Chemical role per atom.
            table: Optional role table (e.g. from with_overrides()).

        Raises:
            ValidationError: If a role is not covered by the table, or two
                roles map one type name onto different parameters.
        """
        table = dict(table or self.roles)
        missing = sorted({r for r in roles if r not in table})
        if missing:
            raise ValidationError(
                f"Inorganic force field '{self.name}' has no parameters for "
                f"role(s) {missing}; covered roles: {sorted(table)}"
            )
        type_masses: Dict[str, float] = {}
        type_lj: Dict[str, Tuple[float, float]] = {}
        for role in dict.fromkeys(roles):
            p = table[role]
            lj = (p.epsilon, p.sigma)
            if p.type_name in type_lj and (
                    type_lj[p.type_name] != lj
                    or type_masses[p.type_name] != p.mass):
                raise ValidationError(
                    f"Inorganic force field '{self.name}': type "
                    f"'{p.type_name}' is used by roles with different "
                    "mass/LJ parameters"
                )
            type_masses[p.type_name] = p.mass
            type_lj[p.type_name] = lj
        return ParameterAssignment(
            force_field=self.name,
            version=self.version,
            roles=list(roles),
            type_names=[table[r].type_name for r in roles],
            charges=np.array([table[r].charge for r in roles], dtype=float),
            type_masses=type_masses,
            type_lj=type_lj,
            combining_rule=self.combining_rule,
            motions=self.motions,
            notes=list(notes or []),
        )

with_overrides(types: Optional[Mapping[str, str]] = None, charges: Optional[Mapping[str, float]] = None, lj: Optional[Mapping[str, Sequence[float]]] = None) -> Dict[str, RoleParameters]

Role table with per-role overrides applied (unknown roles ignored).

Source code in AutoPoly/materials/forcefields/registry.py
def with_overrides(
    self,
    types: Optional[Mapping[str, str]] = None,
    charges: Optional[Mapping[str, float]] = None,
    lj: Optional[Mapping[str, Sequence[float]]] = None,
) -> Dict[str, RoleParameters]:
    """Role table with per-role overrides applied (unknown roles ignored)."""
    table = dict(self.roles)
    for role, params in list(table.items()):
        type_name, q = params.type_name, params.charge
        eps, sig = params.epsilon, params.sigma
        if types and role in types:
            type_name = str(types[role])
        if charges and role in charges:
            q = float(charges[role])
        if lj and role in lj:
            eps, sig = float(lj[role][0]), float(lj[role][1])
        table[role] = RoleParameters(type_name, params.mass, q, eps, sig)
    return table

assign(roles: Sequence[str], table: Optional[Mapping[str, RoleParameters]] = None, notes: Optional[List[str]] = None) -> ParameterAssignment

Type a structure from its per-atom roles.

Parameters:

Name Type Description Default
roles Sequence[str]

Chemical role per atom.

required
table Optional[Mapping[str, RoleParameters]]

Optional role table (e.g. from with_overrides()).

None

Raises:

Type Description
ValidationError

If a role is not covered by the table, or two roles map one type name onto different parameters.

Source code in AutoPoly/materials/forcefields/registry.py
def assign(
    self,
    roles: Sequence[str],
    table: Optional[Mapping[str, RoleParameters]] = None,
    notes: Optional[List[str]] = None,
) -> ParameterAssignment:
    """
    Type a structure from its per-atom roles.

    Args:
        roles: Chemical role per atom.
        table: Optional role table (e.g. from with_overrides()).

    Raises:
        ValidationError: If a role is not covered by the table, or two
            roles map one type name onto different parameters.
    """
    table = dict(table or self.roles)
    missing = sorted({r for r in roles if r not in table})
    if missing:
        raise ValidationError(
            f"Inorganic force field '{self.name}' has no parameters for "
            f"role(s) {missing}; covered roles: {sorted(table)}"
        )
    type_masses: Dict[str, float] = {}
    type_lj: Dict[str, Tuple[float, float]] = {}
    for role in dict.fromkeys(roles):
        p = table[role]
        lj = (p.epsilon, p.sigma)
        if p.type_name in type_lj and (
                type_lj[p.type_name] != lj
                or type_masses[p.type_name] != p.mass):
            raise ValidationError(
                f"Inorganic force field '{self.name}': type "
                f"'{p.type_name}' is used by roles with different "
                "mass/LJ parameters"
            )
        type_masses[p.type_name] = p.mass
        type_lj[p.type_name] = lj
    return ParameterAssignment(
        force_field=self.name,
        version=self.version,
        roles=list(roles),
        type_names=[table[r].type_name for r in roles],
        charges=np.array([table[r].charge for r in roles], dtype=float),
        type_masses=type_masses,
        type_lj=type_lj,
        combining_rule=self.combining_rule,
        motions=self.motions,
        notes=list(notes or []),
    )

register_inorganic_ff(ff: InorganicForceField) -> None

Register an inorganic force-field adapter (and its aliases).

Source code in AutoPoly/materials/forcefields/registry.py
def register_inorganic_ff(ff: InorganicForceField) -> None:
    """Register an inorganic force-field adapter (and its aliases)."""
    if ff.name in _FF_REGISTRY:
        raise ValidationError(
            f"Inorganic force field '{ff.name}' is already registered"
        )
    _FF_REGISTRY[ff.name] = ff
    for material_id in ff.material_ids:
        for alias in ff.aliases:
            _FF_ALIASES[(material_id, alias.lower())] = ff.name

get_inorganic_ff(name: str, material_id: Optional[str] = None) -> InorganicForceField

Resolve an inorganic force field by registry name, or by alias in the context of a material (e.g. ("interface", "sio2") -> interface_silica).

Raises:

Type Description
ValidationError

Unknown name, or the set is not defined for the material.

Source code in AutoPoly/materials/forcefields/registry.py
def get_inorganic_ff(name: str,
                     material_id: Optional[str] = None) -> InorganicForceField:
    """
    Resolve an inorganic force field by registry name, or by alias in the
    context of a material (e.g. ("interface", "sio2") -> interface_silica).

    Raises:
        ValidationError: Unknown name, or the set is not defined for the
            material.
    """
    key = name
    if key not in _FF_REGISTRY and material_id is not None:
        key = _FF_ALIASES.get((material_id, name.lower()), name)
    if key not in _FF_REGISTRY:
        available = (
            sorted(n for n, ff in _FF_REGISTRY.items()
                   if material_id in ff.material_ids)
            if material_id else sorted(_FF_REGISTRY)
        )
        raise ValidationError(
            f"Unknown inorganic force field '{name}'"
            + (f" for material '{material_id}'" if material_id else "")
            + f"; available: {available}"
        )
    ff = _FF_REGISTRY[key]
    if material_id is not None and material_id not in ff.material_ids:
        raise ValidationError(
            f"Inorganic force field '{ff.name}' is not defined for material "
            f"'{material_id}' (defined for {list(ff.material_ids)})"
        )
    return ff

registered_inorganic_ffs(material_id: Optional[str] = None) -> List[str]

Sorted adapter names (optionally only those for one material).

Source code in AutoPoly/materials/forcefields/registry.py
def registered_inorganic_ffs(material_id: Optional[str] = None) -> List[str]:
    """Sorted adapter names (optionally only those for one material)."""
    return sorted(
        n for n, ff in _FF_REGISTRY.items()
        if material_id is None or material_id in ff.material_ids
    )

AutoPoly.materials.forcefields.compatibility

Organic-inorganic force-field compatibility checks and cross terms.

Three responsibilities:

  1. Host (organic) force-field style introspection: read the pair/bond style, mixing rule, special_bonds and kspace settings from the moltemplate force-field .lt the film/matrix is typed with (host_styles()). Inorganic .lt classes must carry the host's hybrid sub-style keywords, and class2 / many-body hosts are refused.

  2. Explicit cross interactions: after moltemplate has numbered the atom types, write an explicit pair_coeff i j for every pair involving an inorganic type, computed with the declared combining rule of the inorganic adapter (or the host rule when the adapter declares "host"). The resulting system no longer depends on pair_modify mix for any organic-inorganic pair (write_explicit_cross_terms()).

  3. A machine-readable record of every decision for the force-field compatibility report.

Created on 2026-11-13 @author: zwu

Classes:

Name Description
HostStyles

Style settings of the organic host force field.

InorganicClassPolicy

Cross-interaction policy of one inorganic moltemplate class.

CrossTermReport

What write_explicit_cross_terms() did.

Functions:

Name Description
host_styles

Parse the host force-field style lines from its moltemplate .lt.

combine

(epsilon, sigma) cross parameters for a 12-6 LJ pair.

resolve_rule

Concrete rule for a declared adapter rule ("host" -> host rule).

read_type_assignments

Atom type id -> (namespace path, type name) from

read_instance_assignments

(mol ids, atom ids) from ttree_assignments.txt:

read_self_pair_coeffs

type id -> (epsilon, sigma) from pair_coeff i i ... lines.

write_explicit_cross_terms

Append explicit pair_coeff lines for every pair involving an

HostStyles dataclass

Style settings of the organic host force field.

Attributes:

Name Type Description
pair_substyle Optional[str]

LJ sub-style for hybrid pair styles (None for plain styles).

bond_substyle Optional[str]

'harmonic' if the host uses a hybrid bond style.

lj_style Optional[str]

The 12-6 LJ pair (sub-)style in use, or None.

mixing_rule str

'geometric', 'arithmetic', 'sixthpower' (LAMMPS default geometric).

Source code in AutoPoly/materials/forcefields/compatibility.py
@dataclass
class HostStyles:
    """Style settings of the organic host force field."""
    force_field: str
    pair_style: str = ""
    bond_style: str = ""
    pair_modify: str = ""
    special_bonds: str = ""
    kspace_style: str = ""

    @property
    def is_class2(self) -> bool:
        return "class2" in self.pair_style or "class2" in self.bond_style

    @property
    def is_hybrid_pair(self) -> bool:
        return self.pair_style.split()[1:2] in (["hybrid"],
                                                 ["hybrid/overlay"])

    @property
    def pair_substyle(self) -> Optional[str]:
        """LJ sub-style for hybrid pair styles (None for plain styles)."""
        if not self.is_hybrid_pair:
            return None
        for token in self.pair_style.split()[2:]:
            if token.startswith("lj/"):
                return token
        return None

    @property
    def bond_substyle(self) -> Optional[str]:
        """'harmonic' if the host uses a hybrid bond style."""
        return "harmonic" if "hybrid" in self.bond_style else None

    @property
    def lj_style(self) -> Optional[str]:
        """The 12-6 LJ pair (sub-)style in use, or None."""
        tokens = self.pair_style.split()[1:]
        for token in tokens:
            if token in LJ_12_6_STYLES:
                return token
        return None

    @property
    def mixing_rule(self) -> str:
        """'geometric', 'arithmetic', 'sixthpower' (LAMMPS default geometric)."""
        m = re.search(r"\bmix\s+(\w+)", self.pair_modify)
        return m.group(1) if m else "geometric"

    def to_dict(self) -> Dict[str, object]:
        return {
            "force_field": self.force_field,
            "pair_style": self.pair_style,
            "bond_style": self.bond_style,
            "pair_modify": self.pair_modify,
            "special_bonds": self.special_bonds,
            "kspace_style": self.kspace_style,
            "pair_substyle": self.pair_substyle,
            "bond_substyle": self.bond_substyle,
            "mixing_rule": self.mixing_rule,
        }

pair_substyle: Optional[str] property

LJ sub-style for hybrid pair styles (None for plain styles).

bond_substyle: Optional[str] property

'harmonic' if the host uses a hybrid bond style.

lj_style: Optional[str] property

The 12-6 LJ pair (sub-)style in use, or None.

mixing_rule: str property

'geometric', 'arithmetic', 'sixthpower' (LAMMPS default geometric).

InorganicClassPolicy dataclass

Cross-interaction policy of one inorganic moltemplate class.

Source code in AutoPoly/materials/forcefields/compatibility.py
@dataclass
class InorganicClassPolicy:
    """Cross-interaction policy of one inorganic moltemplate class."""
    class_name: str
    adapter: str
    native_rule: str          # adapter's declared rule (may be "host")
    organic_rule: str         # rule for pairs with organic types
    qualification: Optional[str] = None

CrossTermReport dataclass

What write_explicit_cross_terms() did.

Source code in AutoPoly/materials/forcefields/compatibility.py
@dataclass
class CrossTermReport:
    """What write_explicit_cross_terms() did."""
    n_pairs: int = 0
    rules: Dict[str, str] = field(default_factory=dict)
    lines: List[str] = field(default_factory=list)

    def to_dict(self) -> Dict[str, object]:
        return {"n_pairs": self.n_pairs, "rules": dict(self.rules)}

host_styles(force_field: str, ff_lt: Optional[Path]) -> HostStyles

Parse the host force-field style lines from its moltemplate .lt.

Parameters:

Name Type Description Default
force_field str

Host force-field name.

required
ff_lt Optional[Path]

Path of the force-field .lt (None = not available, only allowed for "openff", whose generated file always uses the same styles).

required
Source code in AutoPoly/materials/forcefields/compatibility.py
def host_styles(force_field: str, ff_lt: Optional[Path]) -> HostStyles:
    """
    Parse the host force-field style lines from its moltemplate .lt.

    Args:
        force_field: Host force-field name.
        ff_lt: Path of the force-field .lt (None = not available, only
               allowed for "openff", whose generated file always uses the
               same styles).
    """
    if ff_lt is None or not Path(ff_lt).is_file():
        if force_field == "openff":
            return HostStyles(force_field, **_OPENFF_DEFAULT)
        raise ValidationError(
            f"Force-field file for '{force_field}' not found: {ff_lt}"
        )
    found: Dict[str, str] = {}
    _collect_styles(Path(ff_lt), found, depth=0)
    return HostStyles(force_field, **found)

combine(rule: str, a: Tuple[float, float], b: Tuple[float, float]) -> Tuple[float, float]

(epsilon, sigma) cross parameters for a 12-6 LJ pair.

Source code in AutoPoly/materials/forcefields/compatibility.py
def combine(rule: str, a: Tuple[float, float],
            b: Tuple[float, float]) -> Tuple[float, float]:
    """(epsilon, sigma) cross parameters for a 12-6 LJ pair."""
    ea, sa = a
    eb, sb = b
    eps = math.sqrt(max(ea, 0.0) * max(eb, 0.0))
    if rule == "arithmetic":
        sig = 0.5 * (sa + sb)
    elif rule == "geometric":
        sig = math.sqrt(max(sa, 0.0) * max(sb, 0.0))
    else:
        raise ValidationError(
            f"Unsupported combining rule '{rule}' for explicit cross terms "
            "(use 'arithmetic' or 'geometric')"
        )
    return eps, sig

resolve_rule(rule: str, host: HostStyles) -> str

Concrete rule for a declared adapter rule ("host" -> host rule).

Source code in AutoPoly/materials/forcefields/compatibility.py
def resolve_rule(rule: str, host: HostStyles) -> str:
    """Concrete rule for a declared adapter rule ("host" -> host rule)."""
    if rule == "host":
        host_rule = host.mixing_rule
        if host_rule not in ("arithmetic", "geometric"):
            raise ValidationError(
                f"Host force field '{host.force_field}' uses mixing rule "
                f"'{host_rule}', which cannot be combined with 12-6 "
                "inorganic parameters"
            )
        return host_rule
    return rule

read_type_assignments(moltemplate_dir: Path) -> Dict[int, Tuple[str, str]]

Atom type id -> (namespace path, type name) from output_ttree/ttree_assignments.txt (e.g. 6 -> ("QuartzSlab", "i15_sc4"), 1 -> ("GAFF", "c3")).

Source code in AutoPoly/materials/forcefields/compatibility.py
def read_type_assignments(moltemplate_dir: Path) -> Dict[int, Tuple[str, str]]:
    """
    Atom type id -> (namespace path, type name) from
    output_ttree/ttree_assignments.txt (e.g. 6 -> ("QuartzSlab",
    "i15_sc4"), 1 -> ("GAFF", "c3")).
    """
    path = _ttree_file(moltemplate_dir)
    out: Dict[int, Tuple[str, str]] = {}
    for line in path.read_text().splitlines():
        m = re.match(r"^@/atom:(\S+)\s+(\d+)", line)
        if m:
            full = m.group(1)
            ns, _, name = full.rpartition("/")
            out[int(m.group(2))] = (ns, name)
    return out

read_instance_assignments(moltemplate_dir: Path)

(mol ids, atom ids) from ttree_assignments.txt:

  • mols: instance path -> molecule id ($/mol:np_1 -> 2),
  • atoms: instance path -> sorted atom ids of that instance subtree.
Source code in AutoPoly/materials/forcefields/compatibility.py
def read_instance_assignments(moltemplate_dir: Path):
    """
    (mol ids, atom ids) from ttree_assignments.txt:

    - mols: instance path -> molecule id (``$/mol:np_1`` -> 2),
    - atoms: instance path -> sorted atom ids of that instance subtree.
    """
    path = _ttree_file(moltemplate_dir)
    mols: Dict[str, int] = {}
    atoms: Dict[str, List[int]] = {}
    for line in path.read_text().splitlines():
        m = re.match(r"^\$/mol:(\S+)\s+(\d+)", line)
        if m:
            mols[m.group(1)] = int(m.group(2))
            continue
        m = re.match(r"^\$/atom:(\S+)\s+(\d+)", line)
        if m:
            instance = m.group(1).split("/", 1)[0]
            atoms.setdefault(instance, []).append(int(m.group(2)))
    for key in atoms:
        atoms[key].sort()
    return mols, atoms

read_self_pair_coeffs(settings: Path) -> Dict[int, Tuple[float, float]]

type id -> (epsilon, sigma) from pair_coeff i i ... lines.

Source code in AutoPoly/materials/forcefields/compatibility.py
def read_self_pair_coeffs(settings: Path) -> Dict[int, Tuple[float, float]]:
    """type id -> (epsilon, sigma) from ``pair_coeff i i ...`` lines."""
    out: Dict[int, Tuple[float, float]] = {}
    for line in Path(settings).read_text().splitlines():
        parts = line.split("#", 1)[0].split()
        if len(parts) < 5 or parts[0] != "pair_coeff":
            continue
        if not (parts[1].isdigit() and parts[2].isdigit()):
            continue
        i, j = int(parts[1]), int(parts[2])
        if i != j:
            continue
        nums = []
        for tok in parts[3:]:
            try:
                nums.append(float(tok))
            except ValueError:
                if nums:
                    break
                continue  # sub-style keyword
        if len(nums) >= 2:
            out[i] = (nums[0], nums[1])
    return out

write_explicit_cross_terms(moltemplate_dir: Path, policies: Dict[str, InorganicClassPolicy], host: HostStyles, settings_file: str = 'system.in.settings') -> CrossTermReport

Append explicit pair_coeff lines for every pair involving an inorganic type to system.in.settings.

Rules: - inorganic x organic: the class's organic_rule ("host" resolves to the host mixing rule), - inorganic x inorganic of the same adapter: the adapter's native rule ("host" resolves to the host rule), - inorganic x inorganic of different adapters: refused (no validated policy).

Raises:

Type Description
ValidationError

Missing self coefficients, unsupported host pair style, or an unqualified inorganic-inorganic pair.

Source code in AutoPoly/materials/forcefields/compatibility.py
def write_explicit_cross_terms(
    moltemplate_dir: Path,
    policies: Dict[str, InorganicClassPolicy],
    host: HostStyles,
    settings_file: str = "system.in.settings",
) -> CrossTermReport:
    """
    Append explicit pair_coeff lines for every pair involving an
    inorganic type to system.in.settings.

    Rules:
    - inorganic x organic: the class's ``organic_rule`` ("host" resolves
      to the host mixing rule),
    - inorganic x inorganic of the same adapter: the adapter's native
      rule ("host" resolves to the host rule),
    - inorganic x inorganic of different adapters: refused (no validated
      policy).

    Raises:
        ValidationError: Missing self coefficients, unsupported host pair
            style, or an unqualified inorganic-inorganic pair.
    """
    d = Path(moltemplate_dir)
    report = CrossTermReport()
    if not policies:
        return report
    lj = host.lj_style
    if lj is None or host.is_class2:
        raise ValidationError(
            f"Host force field '{host.force_field}' pair style "
            f"'{host.pair_style}' is not a supported 12-6 LJ style for "
            "inorganic cross interactions"
        )
    types = read_type_assignments(d)
    selfc = read_self_pair_coeffs(d / settings_file)
    inorganic = {t: ns for t, (ns, _) in types.items() if ns in policies}
    unmatched = sorted(set(policies) - set(inorganic.values()))
    if unmatched:
        raise ValidationError(
            f"No atom types found in class namespace(s) {unmatched}: "
            "explicit cross interactions cannot be written for them"
        )
    missing = [t for t in types if t not in selfc]
    if missing:
        names = [f"{types[t][0]}/{types[t][1]}" for t in missing[:5]]
        raise ValidationError(
            f"No pair_coeff i i found for atom type(s) {names}; cannot "
            "build explicit cross interactions"
        )
    sub = f" {host.pair_substyle}" if host.is_hybrid_pair else ""
    lines = [
        "",
        "# --- AutoPoly: explicit organic-inorganic cross interactions ---",
    ]
    for cls, pol in sorted(policies.items()):
        organic = resolve_rule(pol.organic_rule, host)
        native = resolve_rule(pol.native_rule, host)
        report.rules[cls] = f"{pol.adapter}: {organic} rule with organic " \
                            f"types, {native} rule within the adapter"
        lines.append(
            f"# {cls} ({pol.adapter}): with organic types -> {organic} "
            f"rule; within adapter -> {native} rule"
            + (f"; qualification {pol.qualification}"
               if pol.qualification else "")
        )
    ids = sorted(types)
    for a_idx, i in enumerate(ids):
        for j in ids[a_idx:]:
            if i == j:
                continue
            ci, cj = inorganic.get(i), inorganic.get(j)
            if ci is None and cj is None:
                continue
            if ci is not None and cj is not None:
                pi, pj = policies[ci], policies[cj]
                if pi.adapter != pj.adapter:
                    raise ValidationError(
                        f"No validated cross-interaction policy between "
                        f"inorganic adapters '{pi.adapter}' ({ci}) and "
                        f"'{pj.adapter}' ({cj})"
                    )
                rule = resolve_rule(pi.native_rule, host)
            else:
                pol = policies[ci if ci is not None else str(cj)]
                rule = resolve_rule(pol.organic_rule, host)
            eps, sig = combine(rule, selfc[i], selfc[j])
            lines.append(
                f"pair_coeff {i} {j}{sub} {eps:.6g} {sig:.6g}"
                f"  # {types[i][0]}/{types[i][1]} - "
                f"{types[j][0]}/{types[j][1]} ({rule})"
            )
            report.n_pairs += 1
    lines.append("")
    with open(d / settings_file, "a") as f:
        f.write("\n".join(lines))
    report.lines = lines
    return report

Nanocomposite packing

AutoPoly.packing.nanocomposite

Nanocomposite packing: fillers first, then an obstacle-aware matrix.

Strategy "nanocomposite_mc" (stage 3; reads only units.json + the per-unit class-local coordinate files written by stage 2):

  1. Box: explicit box_dims / box_size win; otherwise a cubic box sized for the matrix at initial_density plus the nominal filler core volume: V_box = M_matrix / rho_init + sum(V_core). (Atomistic estimate only: build at modest density, compress/equilibrate in MD.)
  2. Fillers: every instance of every filler unit gets a random position and orientation under full 3D periodic boundaries; its atoms must keep min_gap from every atom of every other filler including periodic images. A particle must also be smaller than the box (no self-image contact).
  3. Matrix: every polymer chain / molecule instance gets a random rigid-body placement (orientation + an anchor atom dropped into a free voxel); all its atoms must keep filler_clearance from filler atoms and polymer_clearance from atoms of other matrix instances (minimum image). Coils interpenetrate freely as long as atoms do not clash -- whole-chain bounding spheres are never used. When rigid placement of a pre-grown chain fails ("auto" mode, default) -- or always ("regrow") -- the chain is regrown monomer by monomer inside the box around the obstacles (packing/chain_regrowth.py) and written as a per-instance class with the new monomer transforms (typing untouched).
  4. No silent fallback: an instance that cannot be placed raises a PackingError with the free-volume diagnostics and concrete suggestions.
  5. An exact minimum-image neighbor search over all atoms verifies every clearance before the lt commands are emitted; the achieved minimum distances, nominal loading and box are returned in the result report.

Created on 2026-11-13 @author: zwu

Classes:

Name Description
PackingError

Raised when the nanocomposite packing cannot place an instance.

NanocompositePacking

Configuration of the "nanocomposite_mc" strategy.

NanocompositeMCStrategy

Filler-first, obstacle-aware atom-level random packing.

PackingError

Bases: ValidationError

Raised when the nanocomposite packing cannot place an instance.

Source code in AutoPoly/packing/nanocomposite.py
class PackingError(ValidationError):
    """Raised when the nanocomposite packing cannot place an instance."""

NanocompositePacking dataclass

Configuration of the "nanocomposite_mc" strategy.

Attributes:

Name Type Description
initial_density float

Matrix mass density (g/cm^3) used to size the box when no explicit box is given. Building pre-grown chains at the final melt density is rarely possible; the generated run script compresses toward target_polymer_density.

target_polymer_density Optional[float]

Final matrix density (g/cm^3) recorded in the report and used by the compression stage of in.run; None = no compression stage.

min_gap float

Minimum atom-atom distance between two fillers (A), periodic images included (surface-to-surface gap).

filler_clearance float

Minimum matrix-atom to filler-atom distance (A).

polymer_clearance float

Minimum distance (A) between atoms of different matrix instances (heavy atoms).

hydrogen_clearance float

Same, for contacts with matrix hydrogen atoms (A); smaller because H atoms are small.

max_initial_overlap float

Allowed penetration below the clearances (A); 0.0 = strict. The exact final check uses clearance - this.

max_attempts int

Placement attempts per instance before PackingError ("rigid" mode).

matrix_placement str

"auto" (rigid placement, regrow the chain in place when that fails), "rigid" (pre-grown conformations only), or "regrow" (always regrow polymer chains in the box).

rigid_attempts int

"auto" mode: rigid attempts before regrowing.

regrow_starts int

Independent in-box regrowth attempts per chain.

intra_clearance float

Minimum distance between atoms of the same chain more than three bonds apart (regrown chains) (A).

intra14_clearance float

Same for 1-4 pairs across a junction (A).

voxel_size float

Collision-grid resolution (A).

seed Optional[int]

RNG seed (None = nondeterministic; the BoxPacker rng_seed is used when unset).

packing_failure str

Only "raise" (never fall back to overlapping positions).

Source code in AutoPoly/packing/nanocomposite.py
@dataclass
class NanocompositePacking:
    """
    Configuration of the "nanocomposite_mc" strategy.

    Attributes:
        initial_density: Matrix mass density (g/cm^3) used to size the box
            when no explicit box is given.  Building pre-grown chains at
            the final melt density is rarely possible; the generated run
            script compresses toward target_polymer_density.
        target_polymer_density: Final matrix density (g/cm^3) recorded in
            the report and used by the compression stage of in.run;
            None = no compression stage.
        min_gap: Minimum atom-atom distance between two fillers (A),
            periodic images included (surface-to-surface gap).
        filler_clearance: Minimum matrix-atom to filler-atom distance (A).
        polymer_clearance: Minimum distance (A) between atoms of different
            matrix instances (heavy atoms).
        hydrogen_clearance: Same, for contacts with matrix hydrogen atoms
            (A); smaller because H atoms are small.
        max_initial_overlap: Allowed penetration below the clearances (A);
            0.0 = strict.  The exact final check uses clearance - this.
        max_attempts: Placement attempts per instance before PackingError
            ("rigid" mode).
        matrix_placement: "auto" (rigid placement, regrow the chain in
            place when that fails), "rigid" (pre-grown conformations
            only), or "regrow" (always regrow polymer chains in the box).
        rigid_attempts: "auto" mode: rigid attempts before regrowing.
        regrow_starts: Independent in-box regrowth attempts per chain.
        intra_clearance: Minimum distance between atoms of the same chain
            more than three bonds apart (regrown chains) (A).
        intra14_clearance: Same for 1-4 pairs across a junction (A).
        voxel_size: Collision-grid resolution (A).
        seed: RNG seed (None = nondeterministic; the BoxPacker rng_seed is
            used when unset).
        packing_failure: Only "raise" (never fall back to overlapping
            positions).
    """
    initial_density: float = 0.35
    target_polymer_density: Optional[float] = None
    min_gap: float = 3.0
    filler_clearance: float = 2.5
    polymer_clearance: float = 1.7
    hydrogen_clearance: float = 1.2
    max_initial_overlap: float = 0.0
    max_attempts: int = 4000
    matrix_placement: str = "auto"
    rigid_attempts: int = 300
    regrow_starts: int = 40
    intra_clearance: float = 1.3
    intra14_clearance: float = 1.4
    voxel_size: float = 0.25
    seed: Optional[int] = None
    packing_failure: str = "raise"

    def __post_init__(self) -> None:
        if self.packing_failure != "raise":
            raise ValidationError(
                "NanocompositePacking.packing_failure must be 'raise' (silent "
                "fallback to overlapping positions is not supported)"
            )
        for name in ("initial_density", "min_gap", "filler_clearance",
                     "polymer_clearance", "hydrogen_clearance", "voxel_size"):
            if not getattr(self, name) > 0:
                raise ValidationError(f"NanocompositePacking.{name} must be > 0")
        if self.max_initial_overlap < 0:
            raise ValidationError("max_initial_overlap must be >= 0")
        if self.target_polymer_density is not None:
            if self.target_polymer_density <= 0:
                raise ValidationError("target_polymer_density must be > 0")
            if self.initial_density > self.target_polymer_density:
                raise ValidationError(
                    f"initial_density ({self.initial_density}) exceeds "
                    f"target_polymer_density ({self.target_polymer_density})"
                )
        if self.max_attempts < 1:
            raise ValidationError("max_attempts must be >= 1")
        if self.matrix_placement not in ("auto", "rigid", "regrow"):
            raise ValidationError(
                "matrix_placement must be 'auto', 'rigid' or 'regrow', got "
                f"'{self.matrix_placement}'"
            )
        if not (self.intra_clearance > 0 and self.intra14_clearance > 0):
            raise ValidationError("intra clearances must be > 0")

    def to_dict(self) -> Dict[str, object]:
        return asdict(self)

NanocompositeMCStrategy

Bases: PlacementStrategy

Filler-first, obstacle-aware atom-level random packing.

Source code in AutoPoly/packing/nanocomposite.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
class NanocompositeMCStrategy(PlacementStrategy):
    """Filler-first, obstacle-aware atom-level random packing."""

    name = "nanocomposite_mc"

    def place(self, ctx: PackingContext) -> PlacementResult:
        cfg = ctx.nanocomposite or NanocompositePacking()
        if ctx.substrate is not None:
            raise ValidationError(
                "Strategy 'nanocomposite_mc' does not combine fillers with a "
                "substrate yet ('nanocomposite_on_substrate' is a later "
                "milestone): it would have to respect both the slab region "
                "and the filler obstacles"
            )
        if ctx.subtract:
            raise ValidationError(
                "subtract=... is not supported by 'nanocomposite_mc'"
            )
        units = ctx.units
        bad = [u.id for u in units.units if getattr(u, "kind", None) ==
               "inorganic" and u.role != "filler"]
        if bad:
            raise ValidationError(
                f"'nanocomposite_mc' places filler units only; got inorganic "
                f"non-filler unit(s) {bad}"
            )
        seed = cfg.seed if cfg.seed is not None else ctx.rng_seed
        rng = np.random.default_rng(seed)
        build_dir = Path(units.source_dir) if units.source_dir else None

        fillers, matrix = self._bodies(units, build_dir)
        lo, lengths, sizing = self._box(ctx, cfg, units)
        self._check_box(fillers, matrix, lengths, cfg)

        # --- 2. fillers -------------------------------------------------
        gap_grid = PeriodicVoxelGrid(lo, lengths, cfg.voxel_size)
        soft_grid = None
        if any(not b.core_mask.all() for b in fillers):
            # grafted shells: shell atoms of different fillers keep the
            # polymer clearance (cores keep min_gap via gap_grid)
            soft_grid = PeriodicVoxelGrid(lo, lengths, cfg.voxel_size)
        matrix_grid = PeriodicVoxelGrid(lo, lengths, cfg.voxel_size)
        for k, body in enumerate(fillers):
            self._place_filler(body, k, fillers, gap_grid, lo, lengths,
                               cfg, rng, soft_grid)
            world = body.world()
            core = body.core_mask
            is_h = np.array([e == "H" for e in body.elements])
            matrix_grid.mark(world[core], cfg.filler_clearance)
            matrix_grid.mark(world[~core & ~is_h], cfg.polymer_clearance)
            matrix_grid.mark(world[~core & is_h], cfg.hydrogen_clearance)
        # --- 3. matrix --------------------------------------------------
        for k, body in enumerate(matrix):
            self._place_matrix(body, k, matrix, fillers, matrix_grid, lo,
                               lengths, cfg, rng)
            world = body.world()
            is_h = np.array([e == "H" for e in body.elements])
            matrix_grid.mark(world[~is_h], cfg.polymer_clearance)
            matrix_grid.mark(world[is_h], cfg.hydrogen_clearance)

        bounds = tuple((float(lo[a]), float(lo[a] + lengths[a]))
                       for a in range(3))
        report = self._verify(fillers, matrix, lengths, cfg)
        report.update(sizing)
        report["config"] = cfg.to_dict()
        report["regrown_chains"] = [b.instance for b in matrix if b.regrown]
        report["intrachain"] = self._verify_intrachain(matrix, lengths, cfg)
        records = [self._record(b) for b in fillers + matrix]
        extra = {}
        for b in matrix:
            if b.regrown:
                from .chain_regrowth import regrown_class_text
                extra[f"{b.regrown_class}.lt"] = regrown_class_text(
                    b.lt_path, b.regrown_class, b.regrown)
        logger.info(
            f"Nanocomposite placement complete: {len(fillers)} filler and "
            f"{len(matrix)} matrix instances in a "
            f"{lengths[0]:.2f} x {lengths[1]:.2f} x {lengths[2]:.2f} A box; "
            f"min filler-filler {report['min_distance']['filler_filler']}, "
            f"filler-matrix {report['min_distance']['filler_matrix']}, "
            f"matrix-matrix {report['min_distance']['matrix_matrix']} A"
        )
        return PlacementResult(records=records, box_bounds=bounds,
                               report=report, extra_lt_files=extra)

    # ------------------------------------------------------------------
    # Setup
    # ------------------------------------------------------------------
    @staticmethod
    def _bodies(units, build_dir) -> Tuple[List[_Body], List[_Body]]:
        if build_dir is None:
            raise ValidationError(
                "'nanocomposite_mc' needs the build directory of the units "
                "(per-unit coordinate files)"
            )
        fillers: List[_Body] = []
        matrix: List[_Body] = []
        poly_k = mol_k = 0
        for u in units.units:
            if u.role == "graft":
                continue   # instantiated by its filler's composite class
            if not u.coords_file:
                raise ValidationError(
                    f"Unit '{u.id}' has no coords_file (pre-v2 build): re-run "
                    "stage 2 (UnitTyper) to write unit coordinates"
                )
            el, xyz = read_xyz(build_dir / u.coords_file)
            if u.kind == "inorganic":
                n_core = (u.envelope or {}).get("n_core_atoms")
                for k in range(u.count):
                    fillers.append(_Body(u.id, f"{u.id}_{k + 1}",
                                         u.class_name, xyz, el, True,
                                         n_core=n_core))
            elif u.kind == "polymer":
                chain = None
                clash = 0
                if u.chain_file:
                    from .chain_regrowth import (
                        ChainTemplate,
                        intrachain_contacts,
                    )
                    chain = ChainTemplate.load(build_dir / u.chain_file)
                    # pre-grown (stage-1) conformations may contain
                    # atom-level self-overlaps; such chains are regrown
                    clash, _ = intrachain_contacts(
                        xyz, chain.chain_bonds(), INTRA_CHECK_CUTOFF,
                        cutoff14=INTRA_CHECK_CUTOFF_14)
                for _ in range(u.count):
                    poly_k += 1
                    matrix.append(_Body(u.id, f"polymer_{poly_k}",
                                        u.class_name, xyz, el, False,
                                        chain=chain,
                                        lt_path=build_dir / u.lt_file,
                                        intra_clash=clash))
            else:
                for _ in range(u.count):
                    mol_k += 1
                    matrix.append(_Body(u.id, f"molecule_{mol_k}",
                                        u.class_name, xyz, el, False))
        if not fillers:
            raise ValidationError(
                "'nanocomposite_mc' found no filler units; pass a "
                "Nanoparticle to generate() or use 'mc_random'"
            )
        # place large instances first (better acceptance)
        matrix.sort(key=lambda b: -len(b.elements))
        return fillers, matrix

    @staticmethod
    def _box(ctx, cfg, units):
        from ..materials.structure import element_mass

        matrix_mass = 0.0
        for u in units.units:
            if u.kind != "inorganic" and u.role != "graft":
                m = u.mass
                if m is None:
                    raise ValidationError(f"Unit '{u.id}' has no mass")
                matrix_mass += m * u.count
        filler_core = sum((u.envelope or {}).get("core_volume") or 0.0
                          for u in units.filler_units for _ in range(u.count))
        filler_mass = sum((u.mass or 0.0) * u.count
                          for u in units.filler_units)
        graft_mass = sum(((u.material or {}).get("grafts") or {}).get(
            "graft_mass", 0.0) * u.count for u in units.filler_units)
        dims = ctx.box.box_dims or (None, None, None)
        cubic = ctx.box.requested_box_size
        if any(d is not None for d in dims) or cubic is not None:
            auto = None
            lengths = []
            for d in dims:
                if d is not None:
                    lengths.append(float(d))
                elif cubic is not None:
                    lengths.append(float(cubic))
                else:
                    if auto is None:
                        auto = NanocompositeMCStrategy._auto_side(
                            matrix_mass, filler_core, cfg)
                    lengths.append(auto)
            how = "explicit"
        else:
            side = NanocompositeMCStrategy._auto_side(matrix_mass,
                                                      filler_core, cfg)
            lengths = [side, side, side]
            how = f"initial_density {cfg.initial_density} g/cm^3"
        lengths = np.array(lengths, dtype=float)
        volume = float(np.prod(lengths))
        matrix_volume = volume - filler_core
        sizing = {
            "box": {"lengths": lengths.tolist(), "volume_A3": volume,
                    "sizing": how},
            "loading": {
                "n_fillers": {u.id: u.count for u in units.filler_units},
                "filler_core_volume_A3": filler_core,
                "nominal_filler_volume_fraction": filler_core / volume,
                "filler_mass_amu": filler_mass,
                "graft_shell_mass_amu": graft_mass,
                "core_mass_amu": filler_mass - graft_mass,
                "matrix_mass_amu": matrix_mass,
                "filler_weight_fraction": filler_mass /
                (filler_mass + matrix_mass) if filler_mass + matrix_mass
                else 0.0,
                "initial_matrix_density_gcm3": (
                    matrix_mass / (matrix_volume / AMU_PER_GCM3_TO_A3)
                    if matrix_volume > 0 and matrix_mass > 0 else 0.0),
                "target_polymer_density_gcm3": cfg.target_polymer_density,
                "note": "nominal geometric loading (filler core volume / "
                        "box); weight fraction includes surface groups; "
                        "measure the apparent loading after equilibration",
            },
        }
        _ = element_mass  # (masses come from units.json)
        lo = -0.5 * lengths
        return lo, lengths, sizing

    @staticmethod
    def _auto_side(matrix_mass, filler_core, cfg) -> float:
        v_matrix = matrix_mass / cfg.initial_density * AMU_PER_GCM3_TO_A3
        return float((v_matrix + filler_core) ** (1.0 / 3.0))

    @staticmethod
    def _check_box(fillers, matrix, lengths, cfg) -> None:
        """
        Flag bodies that may touch their own periodic image.

        A body whose diameter bound 2*max|r - centroid| plus its clearance
        is below the smallest box side can never meet its own image (fast
        path).  Larger bodies (long chains in small boxes) get an exact
        per-trial self-image contact test; fillers must always fit
        (a nanoparticle wider than the box is not a dispersed filler).
        """
        for body in fillers + matrix:
            c = body.local.mean(axis=0)
            diam = 2.0 * float(np.linalg.norm(body.local - c, axis=1).max())
            clearance = cfg.min_gap if body.is_filler else cfg.polymer_clearance
            body.check_self_image = diam + clearance >= lengths.min()
            # the smallest extent of the body (e.g. sheet thickness) must
            # fit in any orientation search: compare the thinnest
            # principal extent with the box
            c_loc = body.local - c
            thin = float(np.ptp(c_loc @ np.linalg.svd(
                c_loc, full_matrices=False)[2].T, axis=0).min())
            if body.is_filler and thin + clearance >= lengths.min():
                raise PackingError(
                    f"filler '{body.unit_id}' (thinnest extent {thin:.1f} A) "
                    f"cannot fit in the box (min side {lengths.min():.1f} A) "
                    f"with min_gap {cfg.min_gap} A to its own periodic image; "
                    "enlarge the box (lower initial_density / explicit "
                    "box_dims) or use smaller particles"
                )
            if diam >= 2.0 * lengths.min():
                raise PackingError(
                    f"matrix unit '{body.unit_id}' (diameter {diam:.1f} A) "
                    f"spans more than twice the box (min side "
                    f"{lengths.min():.1f} A); enlarge the box or use coiled "
                    "chains (GeometryConfig(use_mc_chain_growth=True))"
                )

    @staticmethod
    def _self_image_clash(world: np.ndarray, lengths: np.ndarray,
                          clearance: float) -> bool:
        """True if two atoms of one body meet through a periodic image."""
        from ..materials.topology import neighbor_pairs

        cut = min(clearance, 0.499 * float(lengths.min()))
        i, j, img, d = neighbor_pairs(world - world.min(axis=0), cut,
                                      np.diag(lengths), (True, True, True))
        return bool(np.any(np.abs(img).sum(axis=1) > 0))

    # ------------------------------------------------------------------
    # Placement
    # ------------------------------------------------------------------
    @staticmethod
    def _place_filler(body, k, fillers, gap_grid, lo, lengths, cfg, rng,
                      soft_grid=None):
        tol = cfg.max_initial_overlap
        core = body.core_mask
        for attempt in range(cfg.max_attempts):
            body.rotation = random_rotation(rng)
            center = lo + rng.random(3) * lengths
            body.translation = center
            world = body.world()
            if gap_grid.hits(world[core]):
                continue
            if soft_grid is not None and soft_grid.hits(world):
                continue
            if body.check_self_image and \
                    NanocompositeMCStrategy._self_image_clash(
                        world[core], lengths, cfg.min_gap):
                continue
            gap_grid.mark(world[core], max(cfg.min_gap - tol, 1e-3))
            if soft_grid is not None:
                soft_grid.mark(world, cfg.polymer_clearance)
                # shell atoms also stay clear of other cores
                gap_grid.mark(world[~core], cfg.filler_clearance)
            return
        raise PackingError(
            f"Could not place filler instance {body.instance} "
            f"({k + 1}/{len(fillers)}) after {cfg.max_attempts} attempts "
            f"with min_gap {cfg.min_gap} A: free volume "
            f"{100 * gap_grid.free_fraction():.1f}% of the box. Reduce the "
            "filler count/size, enlarge the box, or lower min_gap."
        )

    @staticmethod
    def _place_matrix(body, k, matrix, fillers, grid, lo, lengths, cfg, rng):
        mode = cfg.matrix_placement
        regrowable = body.chain is not None and body.chain.topology != "ring"
        best_hits = None
        if mode == "auto" and regrowable and body.intra_clash:
            mode = "regrow"   # never keep a self-overlapping conformation
        if mode == "rigid" or not regrowable or mode == "auto":
            attempts = (cfg.rigid_attempts if mode == "auto" and regrowable
                        else cfg.max_attempts)
            ok, best_hits = NanocompositeMCStrategy._rigid_trials(
                body, grid, lengths, cfg, rng, attempts)
            if ok:
                return
        if regrowable and mode in ("auto", "regrow"):
            from .chain_regrowth import ObstacleAwareGrower
            grower = ObstacleAwareGrower(
                grid, lengths, intra=cfg.intra_clearance,
                intra14=cfg.intra14_clearance)
            for _ in range(cfg.regrow_starts):
                transforms = grower.grow(body.chain, rng)
                if transforms is not None:
                    body.regrown = transforms
                    body.override = np.vstack([
                        body.chain.local(m) @ R.T + t
                        for m, (R, t) in enumerate(transforms)])
                    return
        raise PackingError(
            f"Could not place matrix instance {body.instance} "
            f"({body.unit_id}, {len(body.elements)} atoms; {k}/{len(matrix)} "
            f"matrix instances placed; mode '{mode}'): "
            f"{100 * grid.free_fraction():.1f}% of the box is free at "
            f"clearances filler {cfg.filler_clearance} / polymer "
            f"{cfg.polymer_clearance} A (best rigid trial still had "
            f"{best_hits} blocked atoms"
            + (f"; {cfg.regrow_starts} in-box regrowth attempts failed"
               if regrowable and mode != "rigid" else "")
            + "). Suggested sequence: lower initial_density (build dilute, "
              "compress in MD), use MC chain growth "
              "(GeometryConfig(use_mc_chain_growth=True)) for compact coils, "
              "reduce polymer_clearance, or increase regrow_starts / "
              "max_attempts."
        )

    @staticmethod
    def _rigid_trials(body, grid, lengths, cfg, rng, attempts):
        """Random rigid-body trials; (accepted, fewest blocked atoms)."""
        centroid = body.local.mean(axis=0)
        anchor = int(np.argmin(np.linalg.norm(body.local - centroid, axis=1)))
        best_hits = None
        for _ in range(attempts):
            body.rotation = random_rotation(rng)
            p = grid.random_free_point(rng)
            if p is None:
                break
            body.translation = p - body.rotation @ body.local[anchor]
            world = body.world()
            n = grid.n_hits(world)
            if n == 0 and body.check_self_image and \
                    NanocompositeMCStrategy._self_image_clash(
                        world, lengths, cfg.polymer_clearance):
                n = 1
            if n == 0:
                return True, 0
            if best_hits is None or n < best_hits:
                best_hits = n
        return False, best_hits

    # ------------------------------------------------------------------
    # Verification + output
    # ------------------------------------------------------------------
    @staticmethod
    def _verify(fillers, matrix, lengths, cfg) -> Dict[str, object]:
        bodies = fillers + matrix
        pos = np.vstack([b.world() for b in bodies])
        owner = np.concatenate([np.full(len(b.elements), k)
                                for k, b in enumerate(bodies)])
        is_filler = np.concatenate([b.core_mask for b in bodies])
        tol = cfg.max_initial_overlap + 1e-6
        cutoff = max(cfg.min_gap, cfg.filler_clearance,
                     cfg.polymer_clearance) + 2.0
        cutoff = min(cutoff, 0.499 * float(lengths.min()))
        i, j, d = min_image_contacts(pos, owner, lengths, cutoff)
        mins = {"filler_filler": None, "filler_matrix": None,
                "matrix_matrix": None}
        limits = {"filler_filler": cfg.min_gap,
                  "filler_matrix": cfg.filler_clearance,
                  "matrix_matrix": cfg.polymer_clearance}
        is_h = np.concatenate([[e == "H" for e in b.elements] for b in bodies])
        violations = {}
        for a, b, dd in zip(i, j, d):
            fa, fb = is_filler[a], is_filler[b]
            key = ("filler_filler" if fa and fb else
                   "matrix_matrix" if not (fa or fb) else "filler_matrix")
            if mins[key] is None or dd < mins[key]:
                mins[key] = float(dd)
            limit = limits[key]
            if key == "matrix_matrix" and (is_h[a] or is_h[b]):
                limit = cfg.hydrogen_clearance
            if dd < limit - tol:
                violations[key] = min(float(dd), violations.get(key, 1e9))
        if violations:
            raise PackingError(
                f"Placement verification failed (minimum-image contacts "
                f"below clearance): {violations}"
            )
        if mins["filler_matrix"] is None and is_filler.any() and \
                (~is_filler).any():
            # no contact within the cutoff: report the exact nearest
            # filler-matrix distance instead of None
            mins["filler_matrix"] = NanocompositeMCStrategy._nearest(
                pos, owner, is_filler, lengths)
        limits = dict(limits, matrix_hydrogen=cfg.hydrogen_clearance)
        return {
            "min_distance": {k: (None if v is None else round(v, 3))
                             for k, v in mins.items()},
            "clearances": limits,
            "pbc_checked": True,
            "n_atoms": int(len(pos)),
        }

    @staticmethod
    def _nearest(pos: np.ndarray, owner: np.ndarray, is_filler: np.ndarray,
                 lengths: np.ndarray) -> Optional[float]:
        """Minimum-image nearest distance between filler-core atoms and
        non-core atoms of other bodies (orthorhombic box)."""
        try:
            from scipy.spatial import cKDTree
        except ImportError:
            cKDTree = None
        # wrapped into [0, L) as cKDTree(boxsize=...) requires
        wrapped = np.mod(pos - pos.min(axis=0), lengths)
        wrapped = np.minimum(wrapped, np.nextafter(lengths, 0.0))
        best = None
        for k in np.unique(owner[is_filler]):
            core = wrapped[is_filler & (owner == k)]
            other = wrapped[~is_filler & (owner != k)]
            if not len(other):
                continue
            if cKDTree is not None:
                dmin = float(cKDTree(other, boxsize=lengths).query(core, k=1)[0].min())
            else:
                dmin = np.inf
                for c in range(0, len(core), 32):     # bounded memory
                    d = core[c:c + 32, None, :] - other[None, :, :]
                    d -= lengths * np.round(d / lengths)
                    dmin = min(dmin, float(np.sqrt(
                        np.einsum("ijk,ijk->ij", d, d).min())))
            best = dmin if best is None else min(best, dmin)
        return best

    @staticmethod
    def _verify_intrachain(matrix, lengths, cfg) -> Dict[str, object]:
        """Atom-level self-overlap check of every placed chain (beyond 1-4)."""
        from .chain_regrowth import intrachain_contacts

        worst, n_bad, kept = None, 0, []
        for b in matrix:
            if b.chain is None:
                continue
            n, dmin = intrachain_contacts(b.world(), b.chain.chain_bonds(),
                                          INTRA_CHECK_CUTOFF, lengths,
                                          cutoff14=INTRA_CHECK_CUTOFF_14)
            if n:
                n_bad += 1
                kept.append(b.instance)
                worst = dmin if worst is None else min(worst, dmin)
        if n_bad and cfg.matrix_placement != "rigid":
            raise PackingError(
                f"{n_bad} placed chain(s) still self-overlap (closest "
                f"intra-chain contact {worst:.2f} A beyond 1-4): {kept[:5]}"
            )
        return {"cutoff": INTRA_CHECK_CUTOFF,
                "cutoff_14": INTRA_CHECK_CUTOFF_14,
                "overlapping_chains": n_bad,
                "min_distance": worst,
                "note": "pre-grown conformations kept as-is in 'rigid' mode"
                if n_bad else "no intra-chain contacts beyond 1-4"}

    @staticmethod
    def _record(body: _Body) -> PlacementRecord:
        if body.regrown:
            # regrown chains carry absolute (box-frame) monomer transforms
            return PlacementRecord(
                body.unit_id, body.instance,
                f"{body.instance} = new {body.regrown_class}")
        angle, ax, ay, az = matrix_to_axis_angle(body.rotation)
        x, y, z = body.translation
        if abs(angle) < 1e-9:
            cmd = (f"{body.instance} = new {body.class_name}"
                   f".move({x:.4f},{y:.4f},{z:.4f})")
        else:
            cmd = (f"{body.instance} = new {body.class_name}"
                   f".rot({angle:.6f},{ax:.6f},{ay:.6f},{az:.6f})"
                   f".move({x:.4f},{y:.4f},{z:.4f})")
        return PlacementRecord(body.unit_id, body.instance, cmd)

LAMMPS smoke test

AutoPoly.pipeline.smoke

LAMMPS smoke test of a generated system.

Turns the generated in.run into a short run (bounded minimization, a few hundred MD steps, no dumps), executes LAMMPS, and checks that

  • LAMMPS exits cleanly (no ERROR, no lost atoms/bonds),
  • every thermo energy is finite, the temperature stays bounded,
  • the expected number of rigid bodies was created (nanocomposites).

Used by the qualification tests (tests/test_nanocomposite_lammps_smoke.py) and available to users:

>>> from AutoPoly.pipeline.smoke import run_smoke
>>> report = run_smoke("runs/ps_silica", steps=200)

Created on 2026-11-13 @author: zwu

Classes:

Name Description
SmokeReport

Outcome of a smoke run.

Functions:

Name Description
lammps_executable

First LAMMPS binary found on PATH (None if none).

smoke_input

Shorten a generated in.run: bounded minimize, short run, no dumps.

parse_log

All thermo rows of a LAMMPS log.

run_smoke

Run the shortened script (default in.run; in.polymer for the

SmokeReport dataclass

Outcome of a smoke run.

Source code in AutoPoly/pipeline/smoke.py
@dataclass
class SmokeReport:
    """Outcome of a smoke run."""
    ok: bool
    thermo: List[Dict[str, float]] = field(default_factory=list)
    rigid_bodies: Optional[int] = None
    warnings: List[str] = field(default_factory=list)
    errors: List[str] = field(default_factory=list)
    log: str = ""

    def to_dict(self) -> Dict[str, object]:
        return {"ok": self.ok, "thermo_last": self.thermo[-1] if self.thermo
                else None, "rigid_bodies": self.rigid_bodies,
                "warnings": self.warnings[:20], "errors": self.errors}

lammps_executable(candidates=('lmp', 'lmp_serial', 'lmp_mpi')) -> Optional[str]

First LAMMPS binary found on PATH (None if none).

Source code in AutoPoly/pipeline/smoke.py
def lammps_executable(candidates=("lmp", "lmp_serial", "lmp_mpi")) -> Optional[str]:
    """First LAMMPS binary found on PATH (None if none)."""
    for name in candidates:
        path = shutil.which(name)
        if path:
            return path
    return None

smoke_input(run_script: str, steps: int = 200, min_iterations: int = 200) -> str

Shorten a generated in.run: bounded minimize, short run, no dumps.

Source code in AutoPoly/pipeline/smoke.py
def smoke_input(run_script: str, steps: int = 200,
                min_iterations: int = 200) -> str:
    """Shorten a generated in.run: bounded minimize, short run, no dumps."""
    out = []
    for line in run_script.splitlines():
        s = line.strip()
        if s.startswith("dump") or s.startswith("undump"):
            continue
        if s.startswith("minimize"):
            line = f"minimize        1.0e-4 1.0e-6 {min_iterations} " \
                   f"{10 * min_iterations}"
        elif s.startswith("run "):
            line = f"run             {steps}"
        elif s.startswith("thermo ") and not s.startswith("thermo_"):
            line = f"thermo          {max(1, steps // 4)}"
        out.append(line)
    return "\n".join(out) + "\n"

parse_log(text: str) -> List[Dict[str, float]]

All thermo rows of a LAMMPS log.

Source code in AutoPoly/pipeline/smoke.py
def parse_log(text: str) -> List[Dict[str, float]]:
    """All thermo rows of a LAMMPS log."""
    rows: List[Dict[str, float]] = []
    lines = text.splitlines()
    k = 0
    while k < len(lines):
        if _THERMO_HEAD.match(lines[k]):
            keys = lines[k].split()
            k += 1
            while k < len(lines):
                parts = lines[k].split()
                if len(parts) != len(keys):
                    break
                try:
                    rows.append({key: float(v) for key, v in zip(keys, parts)})
                except ValueError:
                    break
                k += 1
        k += 1
    return rows

run_smoke(project_dir, steps: int = 200, lmp: Optional[str] = None, expected_rigid_bodies: Optional[int] = None, max_temperature: float = 5000.0, timeout: float = 1800.0, script: str = 'in.run') -> SmokeReport

Run the shortened script (default in.run; in.polymer for the bead-spring backends) of project_dir with LAMMPS.

Raises:

Type Description
WorkflowError

No LAMMPS executable or no run script.

Source code in AutoPoly/pipeline/smoke.py
def run_smoke(project_dir, steps: int = 200, lmp: Optional[str] = None,
              expected_rigid_bodies: Optional[int] = None,
              max_temperature: float = 5000.0,
              timeout: float = 1800.0,
              script: str = "in.run") -> SmokeReport:
    """
    Run the shortened ``script`` (default in.run; in.polymer for the
    bead-spring backends) of ``project_dir`` with LAMMPS.

    Raises:
        WorkflowError: No LAMMPS executable or no run script.
    """
    project = Path(project_dir)
    lmp = lmp or lammps_executable()
    if lmp is None:
        raise WorkflowError("No LAMMPS executable (lmp) found on PATH")
    run_in = project / script
    if not run_in.is_file():
        raise WorkflowError(f"No {script} in {project}")
    (project / "in.smoke").write_text(smoke_input(run_in.read_text(), steps))
    proc = subprocess.run(
        [lmp, "-nb", "-in", "in.smoke", "-log", "log.smoke",
         "-screen", "none"],
        cwd=project, capture_output=True, text=True, timeout=timeout,
    )
    log_path = project / "log.smoke"
    log = log_path.read_text() if log_path.is_file() else proc.stdout
    report = SmokeReport(ok=True, log=log)
    report.thermo = parse_log(log)
    for line in log.splitlines():
        if line.startswith("ERROR"):
            report.errors.append(line)
        elif line.startswith("WARNING"):
            report.warnings.append(line)
        m = re.match(r"^\s*(\d+) rigid bodies with (\d+) atoms", line)
        if m:
            report.rigid_bodies = int(m.group(1))
    if proc.returncode != 0 and not report.errors:
        report.errors.append(
            f"LAMMPS exited with code {proc.returncode}: "
            f"{(proc.stderr or proc.stdout)[-500:]}")
    if any("Lost atoms" in w or "lost" in w.lower() and "bond" in w.lower()
           for w in report.warnings + report.errors):
        report.errors.append("atoms or bonds were lost")
    if not report.thermo:
        report.errors.append("no thermo output")
    for row in report.thermo:
        for key, value in row.items():
            if not math.isfinite(value):
                report.errors.append(f"non-finite {key} = {value}")
                break
    temps = [row.get("Temp", row.get("c_tmatrix", 0.0)) for row in
             report.thermo[-5:]]
    if temps and max(temps) > max_temperature:
        report.errors.append(f"temperature blew up ({max(temps):.0f} K)")
    if expected_rigid_bodies is not None and \
            report.rigid_bodies != expected_rigid_bodies:
        report.errors.append(
            f"expected {expected_rigid_bodies} rigid bodies, LAMMPS created "
            f"{report.rigid_bodies}")
    report.ok = not report.errors
    return report