Crystal structure prediction API#
The CSP API is organized by the tasks in a molecular crystal search: prepare formula-unit inputs, choose cell volumes and symmetry, generate starting packings, save and expand their asymmetric-unit (ASU) representations, and screen atomistic structures for possible duplicates. An ASU representation stores independent molecule placements and symmetry instead of coordinates for every atom in the cell. Atomistic optimization does not automatically preserve the generated space group.
See also
CSP user guide for the application workflow, examples, and scientific limits.
Prepare a formula unit#
MolecularPackingInput holds the molecules, conformers, contact distances,
and starting volume estimate needed by the rigid packer. The optional RDKit
helpers build it from molecules and generate conformers; the tensor input can
also be constructed directly.
Input data for one ordered molecular formula unit. |
MolecularPackingInput.sha256 recomputes the established exact-input digest,
including tensor dtype, shape, contents, metadata, and formula-unit volume.
It identifies the input representation, not chemical equivalence. Device-resident
reads may copy tensors to CPU and synchronize; use it for identity or startup,
rather than in the packing loop.
- property MolecularPackingInput.sha256: str#
Return the SHA-256 identity of the exact formula-input representation.
The established encoding hashes the ordered tensor field names, dtypes, shapes, and contiguous bytes, followed by recursively JSON-compatible metadata and
repr(float(formula_unit_volume)). This identifies the exact input representation rather than chemical equivalence. The digest is recomputed on every access and is not part ofstate_dict().Reading device-resident tensors copies them to CPU and may synchronize the device, so use this property for input identity or startup checks, not inside a packing loop. Direct in-place tensor mutation remains unsupported.
- Returns:
Lowercase 64-character SHA-256 hexadecimal digest.
- Return type:
str
Options for generating 3D conformers with RDKit distance geometry. |
Generate 3D conformers with explicit hydrogens from one SMILES molecule. |
|
Build intermolecular contact cutoffs used to measure overlap. |
|
Prepare molecular conformers and contact limits required by the Packer. |
Choose volume and symmetry#
Estimate a starting cell-volume range and select symmetry through
SpaceGroupPolicy. Its fixed and sampled constructors describe group
selection; draw samples compatible groups independently of packing.
OverlapReliefConfig checks the policy against z / z_prime.
You can save a space-group policy or packing configuration and reload it for another search. Reloading preserves all supplied weights, including groups excluded by the current filters.
Estimate formula-unit volume by summing per-atom contributions. |
|
Return a fresh copy of the bundled COD-derived atomic volume table. |
The seven crystallographic crystal systems. |
|
Immutable fixed or weighted-sampling rule for crystal space groups. |
Return space-group numbers with a requested operation count. |
|
Sample compatible International space-group numbers with replacement. |
|
Return default space-group sampling weights as a fresh copy. |
|
Return standard fractional operations for one space group. |
|
Return the number of standard operations for a space group. |
|
Return the crystal system for an International space-group number. |
|
Return whether a group's symmetry preserves molecular handedness. |
- classmethod SpaceGroupPolicy.fixed(group, *, sohncke_only=False)[source]#
Create a policy that always selects one compatible group.
The group number and optional handedness requirement are checked immediately. Its operation count is checked when the policy enters a packing configuration or a draw.
- Parameters:
group (int) – International space-group number in
[1, 230].sohncke_only (bool, default=False) – Require the selected group to preserve molecular handedness.
- Returns:
policy – Frozen fixed-group policy.
- Return type:
- Raises:
TypeError – If
groupis not a non-boolean integer orsohncke_onlyis not a boolean.ValueError – If
groupis outside[1, 230]or is not a Sohncke group whensohncke_only=True.
- classmethod SpaceGroupPolicy.sampled(*, probabilities=None, crystal_system=None, sohncke_only=False)[source]#
Create a policy that samples compatible groups with replacement.
A custom mapping replaces the bundled CSD weights. Missing entries have zero weight, and positive compatible weights are normalized when resolving a draw or packing configuration.
Construction validates and copies the supplied weights. Compatibility and positive remaining weight are checked when the policy enters a packing configuration or a draw.
- Parameters:
probabilities (Mapping[int, float], optional) – Replacement relative weights keyed by group number.
crystal_system (CrystalSystem, optional) – Restrict selection to one crystallographic system.
sohncke_only (bool, default=False) – Keep only groups whose symmetry-generated copies preserve molecular handedness.
- Returns:
policy – Frozen sampled-group policy with a copied prior mapping.
- Return type:
- Raises:
TypeError – If
probabilitiesis not a mapping, a key or weight has an invalid type,crystal_systemis not aCrystalSystem, orsohncke_onlyis not a boolean.ValueError – If a key is outside
[1, 230]or a weight is negative or nonfinite.
- SpaceGroupPolicy.draw(num_samples, *, num_operations, seed=None, device=None)[source]#
Draw compatible International space-group numbers with replacement.
Fixed policies repeat their group without advancing the random generator.
- Parameters:
num_samples (int) – Positive number of groups to draw.
num_operations (int) – Required number of symmetry operations.
seed (int, optional) – Nonnegative seed for a local CPU
torch.Generator. Without a seed, sampled policies consume the global CPU generator.device (torch.device or str, optional) – Device for the returned tensor.
- Returns:
space_groups – Sampled International numbers. Fixed policies repeat their group.
- Return type:
torch.Tensor, shape
[num_samples], dtype=torch.int32- Raises:
TypeError – If either count is not a non-boolean integer or
seedis not a non-boolean integer orNone.ValueError – If a count is not positive,
seedis negative, a fixed group’s operation count does not match, or no compatible sampled group has positive weight.
Generate candidates#
CSPGenerator extends AtomisticGenerator with packing execution policy,
optional gathering, and native-result callbacks. It accepts any structural
CrystalPacker; algorithms retain their own configuration and
scientific loop.
PackingResult contains rigid ASU data or a Batch, plus per-rank reports.
Expansion defaults to true; raw results bypass Batch hooks and dynamics.
When a finite candidate cap has no explicit rank budgets, custom rank targets receive proportional shares. Shares are rounded down, and leftover trials go to the largest fractional shares, with lower group-local ranks winning ties. Explicit budgets take precedence. The global sample target remains positive; individual rank targets may be zero.
A Toolkit generation driver for running crystal packers in local or distributed searches. |
- nvalchemi.csp.CSP_OUTPUT_FIELDS = frozenset({'atomic_numbers', 'cell', 'csp_source_structure_id', 'pbc', 'positions'})#
Build an immutable unordered collection of unique elements.
OverlapReliefPacker samples and adjusts rigid molecular placements until
their intermolecular overlaps meet the chosen tolerance or
the trial budget ends.
It changes whole-molecule translations and rotations and can transform the
cell while leaving each chosen conformer’s internal geometry fixed.
Its result contains accepted ASU structures and the stop reason; an optional
callback receives progress events during the search. Packing does not
minimize a physical crystal energy.
Structural interface for a local crystal packer. |
|
Optional interface for packers with an observable candidate budget. |
|
Identity and rank assignment for one locally executed packing call. |
|
One rank's requested, accepted, generated, and stopping counts. |
|
Typed structures and one or more reports for a packing call. |
|
Summary reason derived from the reports in a packing result. |
|
Choose how many trial structures to sample, which crystal symmetries and cell sizes to use, and when a trial is accepted. |
|
Generate molecular crystal starting structures from supplied conformers. |
|
Cumulative counters and overlap values reported during local packing. |
Generate and return compact ASU structures on this process only. |
|
Resolve this call's candidate cap without drawing randomness. |
|
Return rank-strided int64 identities. |
Store and expand selected structures#
RigidMoleculeASUBatch holds ASU representations and expands selected
structures to full-cell Toolkit Batch objects. The Zarr writer and reader
persist those representations without first expanding every structure.
check_integrity() explicitly checks ASU pointer spans, multiplicities,
bundled operation counts, and formula-molecule conformer-pool membership.
Construction, reading, packing, and expansion do not call it automatically.
Geometry validity remains a caller precondition. CPU checking before expansion
avoids additional GPU readbacks; device-resident checks may synchronize.
Rigid-molecule ASU representations sharing one molecular formula input. |
|
Write and maintain rigid-molecule ASU representations in a Zarr store. |
|
Read active rigid-molecule ASU representations from a CSP Zarr store. |
Check compact ASU pointer, multiplicity, symmetry, and pool indices. |
|
Expand selected ASU rows into a full-cell periodic Toolkit |
|
Create a new store from rigid-molecule ASU structures. |
|
Append new ASU rows or skip rows already stored with identical IDs and values. |
|
Load selected active rows as an ASU batch. |
|
Expand explicitly selected active logical rows into a Toolkit P1 batch. |
Screen similarity and duplicates#
RadialComparisonIndex screens fully periodic, partially periodic, and
nonperiodic atomistic batches using local atom-neighbor distances. Its scores
and matches are approximate; a match can be a false positive. Topological
atom types can distinguish different connectivity roles of the same element
before a caller’s more specific confirmation step.
Compare structures by local radial distributions of atom-neighbor distances. |
|
Retained structures, each input's retained representative, and group sizes. |
|
Deduplicate every structure in one Batch with the tiled stream engine. |
|
Deduplicate a pool in priority order while bounding descriptor blocks. |
|
Yield radial matches from one or two loader-backed structure pools. |
Build a reusable index of local atom-neighbor distances for each structure. |
|
Return one local-distance mismatch score for each requested pair. |
|
Collect proposed matches in deterministic pair order. |
|
Yield matching pair indices in deterministic bounded chunks. |
|
Keep each structure that does not match an earlier retained structure. |
Hooks for custom packers#
Custom packers, including those based on generative models, may propose repeated
crystal candidates. DeduplicateHook provides optional filtering of their
generated structures before downstream processing.
The bundled radial engine compares expanded atomic structures within each
generated Batch using approximate similarity. It keeps no reference set between
calls.
Structural interface for generation-time Batch deduplication. |
|
Filter generated Batches through a caller-selected deduplication engine. |
Return a |
|
Create a within-Batch element-sensitive radial deduplication hook. |
Reuse reference molecular topology labels across reordered structures. |
|
Label atoms with equivalent element-and-bond connectivity. |
|
Group RDKit atoms by their element-and-bond connectivity. |
Map a topology-preserving expanded P1 batch to shared atom types. |
|
Map complete target graph components onto reference atom types. |