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.

MolecularPackingInput

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 of state_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

RDKitConformerConfig

Options for generating 3D conformers with RDKit distance geometry.

generate_conformers_from_smiles

Generate 3D conformers with explicit hydrogens from one SMILES molecule.

build_contact_distance_matrix

Build intermolecular contact cutoffs used to measure overlap.

build_molecular_packing_input

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

Estimate formula-unit volume by summing per-atom contributions.

get_default_atomic_volumes

Return a fresh copy of the bundled COD-derived atomic volume table.

CrystalSystem

The seven crystallographic crystal systems.

SpaceGroupPolicy

Immutable fixed or weighted-sampling rule for crystal space groups.

get_space_group_candidates

Return space-group numbers with a requested operation count.

sample_space_groups

Sample compatible International space-group numbers with replacement.

csd_space_group_probabilities

Return default space-group sampling weights as a fresh copy.

get_space_group_operations

Return standard fractional operations for one space group.

get_space_group_operation_count

Return the number of standard operations for a space group.

get_crystal_system

Return the crystal system for an International space-group number.

is_sohncke_space_group

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:

SpaceGroupPolicy

Raises:
  • TypeError – If group is not a non-boolean integer or sohncke_only is not a boolean.

  • ValueError – If group is outside [1, 230] or is not a Sohncke group when sohncke_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:

SpaceGroupPolicy

Raises:
  • TypeError – If probabilities is not a mapping, a key or weight has an invalid type, crystal_system is not a CrystalSystem, or sohncke_only is 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 seed is not a non-boolean integer or None.

  • ValueError – If a count is not positive, seed is 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.

CSPGenerator

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.

CrystalPacker

Structural interface for a local crystal packer.

CandidateBudgetPacker

Optional interface for packers with an observable candidate budget.

PackingContext

Identity and rank assignment for one locally executed packing call.

PackingReport

One rank's requested, accepted, generated, and stopping counts.

PackingResult

Typed structures and one or more reports for a packing call.

PackingStopReason

Summary reason derived from the reports in a packing result.

OverlapReliefConfig

Choose how many trial structures to sample, which crystal symmetries and cell sizes to use, and when a trial is accepted.

OverlapReliefPacker

Generate molecular crystal starting structures from supplied conformers.

OverlapReliefProgress

Cumulative counters and overlap values reported during local packing.

OverlapReliefPacker.pack

Generate and return compact ASU structures on this process only.

OverlapReliefPacker.resolve_candidate_budget

Resolve this call's candidate cap without drawing randomness.

PackingContext.structure_ids

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.

RigidMoleculeASUBatch

Rigid-molecule ASU representations sharing one molecular formula input.

RigidMoleculeASUZarrWriter

Write and maintain rigid-molecule ASU representations in a Zarr store.

RigidMoleculeASUZarrReader

Read active rigid-molecule ASU representations from a CSP Zarr store.

RigidMoleculeASUBatch.check_integrity

Check compact ASU pointer, multiplicity, symmetry, and pool indices.

RigidMoleculeASUBatch.to_batch

Expand selected ASU rows into a full-cell periodic Toolkit Batch.

RigidMoleculeASUZarrWriter.write

Create a new store from rigid-molecule ASU structures.

RigidMoleculeASUZarrWriter.append

Append new ASU rows or skip rows already stored with identical IDs and values.

RigidMoleculeASUZarrReader.read

Load selected active rows as an ASU batch.

RigidMoleculeASUZarrReader.read_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.

RadialComparisonIndex

Compare structures by local radial distributions of atom-neighbor distances.

DeduplicationResult

Retained structures, each input's retained representative, and group sizes.

deduplicate_batch

Deduplicate every structure in one Batch with the tiled stream engine.

deduplicate_stream

Deduplicate a pool in priority order while bounding descriptor blocks.

iter_matches_stream

Yield radial matches from one or two loader-backed structure pools.

RadialComparisonIndex.build

Build a reusable index of local atom-neighbor distances for each structure.

RadialComparisonIndex.score_pairs

Return one local-distance mismatch score for each requested pair.

RadialComparisonIndex.find_matches

Collect proposed matches in deterministic pair order.

RadialComparisonIndex.iter_matches

Yield matching pair indices in deterministic bounded chunks.

RadialComparisonIndex.deduplicate

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.

DeduplicationEngine

Structural interface for generation-time Batch deduplication.

DeduplicateHook

Filter generated Batches through a caller-selected deduplication engine.

DeduplicationEngine.deduplicate

Return a torch.bool [batch.num_graphs] mask on batch.device.

DeduplicateHook.radial

Create a within-Batch element-sensitive radial deduplication hook.

TopologicalAtomTypeMap

Reuse reference molecular topology labels across reordered structures.

topological_atom_types_from_connectivity

Label atoms with equivalent element-and-bond connectivity.

topological_atom_types_from_mol

Group RDKit atoms by their element-and-bond connectivity.

TopologicalAtomTypeMap.for_batch

Map a topology-preserving expanded P1 batch to shared atom types.

TopologicalAtomTypeMap.for_connectivity

Map complete target graph components onto reference atom types.