Skip to content

Reconstruction API reference

Reference · 简体中文

Use xyz_to_rdmol for one XYZ frame and iter_xyz_to_rdmol_batch for a finite collection. Both take coordinates, total charge and spin multiplicity. A successful reconstruction returns an RDKit molecule with a 3D conformer. 338-S reconstruction tutorial

Single-molecule reconstruction

Import xyz_to_rdmol from molgr.interface. Options after * are keyword-only. Implementation

xyz_to_rdmol(xyz_block, total_charge=0, spin_multiplicity=1, *,
             backend="cpp", make_dative_bonds=True,
             make_stereochemistry=True, kekulize=True, config=None) -> Chem.Mol
Input Type and default Meaning
xyz_block str, required Text of one XYZ frame, with an atom count, comment, and coordinates in Å. Include every atom, including hydrogen.
total_charge int, 0 Net charge of the whole system, including disconnected fragments. Positive values remove electrons.
spin_multiplicity int, 1 Positive integer 2S + 1. The target unpaired-electron count is multiplicity minus one.

Supply charge and multiplicity as arguments. The XYZ comment is descriptive. Let N be the sum of atomic numbers minus total charge and M the multiplicity. N must be nonnegative, 1 ≤ M ≤ N + 1, and N and M − 1 must have the same parity. A singlet target requests zero unpaired electrons. Local radicals coupled to a singlet require information beyond this input. Model and scope

The single-molecule and batch entry points share the following keyword-only options.

Option Default Effect
backend "cpp" Choose the C++ implementation or the Python reference ("python").
make_dative_bonds True Infer contacts from donor electronic states and 3D geometry. A bridging donor may contact several metals. Set to False to skip this step.
make_stereochemistry True Assign stereo labels from coordinates after coordination processing. Set to False to skip 3D assignment. Aromaticity processing still runs.
kekulize True Return localized integer bond orders. Set to False for RDKit aromatic bond types.
config None Use the package-level molgr.CONFIG or supply an independent MolGRConfig for this call.

Return value and coordination

On success the Chem.Mol preserves the XYZ atom order, explicit hydrogen nodes and input conformer. This square-planar platinum complex checks the first atom, the 3D conformer and the inferred dative bonds.

from rdkit import Chem
from molgr.interface import xyz_to_rdmol

xyz = """5
[PtCl4]2-
Pt  0.0  0.0  0.0
Cl  2.3  0.0  0.0
Cl  0.0  2.3  0.0
Cl -2.3  0.0  0.0
Cl  0.0 -2.3  0.0
"""
mol = xyz_to_rdmol(xyz, total_charge=-2, spin_multiplicity=1)
print(mol.GetNumAtoms(), mol.GetAtomWithIdx(0).GetSymbol(), mol.GetConformer().Is3D())
print(sum(b.GetBondType() == Chem.BondType.DATIVE for b in mol.GetBonds()))
5 Pt True
4

With make_dative_bonds=False the same input returns five atoms and zero bonds. To apply coordination separately, call molgr.make_dative_bond(rdmol, extra_tolerance=None, *, config=None) with a Lewis graph, explicit hydrogen atoms, electronic assignments and a conformer in ångströms. Metal-containing graphs are edited on a copy. A metal-free input returns the original object.

A nitrile donates along its outward bond axis, a phosphine through the open face of its pyramid, and an ether can donate along either of two directions. Metals competing for the same direction are ranked by alignment, then distance. An explicit extra_tolerance (Å) overrides the configured distance tolerance. Coordination implementation

Batch reconstruction

Import both names from molgr. The request constructor supplies charge and multiplicity defaults. When passing a plain sequence, supply all three values.

ReconstructionBatchRequest(xyz_block, total_charge=0, spin_multiplicity=1, request_id=None)
iter_xyz_to_rdmol_batch(requests, *, backend="cpp", max_workers=None,
                       queue_size=16, ordered=False, make_dative_bonds=True,
                       make_stereochemistry=True, kekulize=True, config=None,
                       raise_on_error=False) -> Iterator[ReconstructionBatchResult]

The optional request_id string identifies a sample or file path. Read it from item.request.request_id for successes and failures. With raise_on_error=True, the item exception retains the original request in exc.request.

These requests use the same chloride geometry. The first multiplicity is incompatible with its electron count. Iteration continues and the second request succeeds.

from molgr import ReconstructionBatchRequest, iter_xyz_to_rdmol_batch

xyz = "1\nchloride\nCl 0 0 0\n"
requests = [ReconstructionBatchRequest(xyz, -1, 2), (xyz, -1, 1)]
for request, molecule, status in iter_xyz_to_rdmol_batch(requests, ordered=True):
    if status is None:
        print(request.spin_multiplicity, molecule.GetNumAtoms())
    else:
        print(request.spin_multiplicity, status.code.value)
2 INVALID_ELECTRONIC_TARGET
1 1
Option Behavior
requests Finite iterable of request objects or three-element sequences. All requests are collected before scheduling. Chunk a large input to bound memory.
max_workers=None Select the C++ worker count from configuration; an explicit positive integer overrides it. Python accepts only None or 1 and runs serially.
queue_size=16 Bound the result queue; must be at least 1. Does not bound input storage.
ordered=False Yield completion order; True preserves input order.
raise_on_error=False Yield per-item diagnostics; True raises at an item failure.
config, make_dative_bonds, make_stereochemistry, kekulize Same meaning as the single-call options.

Unpack a ReconstructionBatchResult as (input, result, status). The input is the normalized request. The aliases .request, .molecule, and .diagnostics expose the same fields. Chunking and multiprocessing examples

Iteration, result states and exceptions

item.result item.status Interpretation
Chem.Mol None Successful reconstruction.
None ReconstructionDiagnostics Item failed. Inspect its diagnostics.
Marked fallback Chem.Mol ReconstructionDiagnostics Initial perception available for inspection. Record the failure.

item.as_dict() returns the three fields with their original Python objects. item.as_pair() returns only the request and molecule. Check the status before using this pair.

Iteration checks batch-wide arguments first. An unsupported backend, nonpositive worker count or queue size, or a request sequence of the wrong length can raise ValueError. The raise_on_error option controls individual reconstruction failures. Python processes the requests in input order. Calling either entry point in a forked child after the parent imported MolGR raises RuntimeError; use the multiprocessing spawn start method. Batch implementation

Configuration defaults

Import MolGRConfig from molgr or molgr.config. Pass a separate instance to keep settings local to a call. For example, set config.cpp_backend.max_threads = 1 on a new instance and pass config=config to limit native threads for that call. Complete definitions are in config.py; the groups below list every configuration field.

Resonance search · resonance

config.resonance · ResonanceConfig

Field Type Default Meaning
max_depth int 3 Maximum number of successive moves along a reconstruction resonance path. Ligand targets initially try up to two steps and deepen when needed.
limited_discrepancy_max_discrepancy int 2 Maximum number of nonpreferred branch choices along a resonance walk. Increasing it admits more alternatives at the same depth.
traversal_score ResonanceTraversalScore 'uff_lite_gain' Order moves by estimated UFF-lite gain ("uff_lite_gain") or keep their generation order ("input_order"). This selects the preferred branch in the discrepancy-limited walk.
neighbor_radical_max_discrepancy int 2 Maximum neighboring radical pairs per seed resolved by charge separation instead of bond formation. This budget is independent of the resonance walk. Zero or a negative value permits no such choices.
Native scheduling and caching · cpp_backend

config.cpp_backend · CppBackendConfig

Field Type Default Meaning
max_threads Optional[int] Windows 1, elsewhere None Cap worker counts chosen automatically by the native backend. None uses available hardware parallelism, bounded by the number of tasks. The default is 1 on Windows and None elsewhere.
enable_target_bucket_parallelism bool True Allow independent ligand charge and radical targets within a molecule to be reconstructed concurrently when the task threshold is met.
enable_candidate_scoring_parallelism bool False Allow native scoring of independent metal–ligand candidates to run concurrently when enough score jobs are available.
enable_uff_atom_typing_cache bool False Reuse cached Universal Force Field atom types during native scoring. Enable to reduce repeated typing work.
target_bucket_parallel_threshold int 1 Minimum number of ligand target tasks required before native target-bucket parallelism is considered. Effective minimum is one task.
target_bucket_parallel_max_threads Optional[int] None Additional worker cap for target buckets within one molecule. None leaves worker selection to the native thread and task limits.
candidate_score_parallel_threshold int 32 Minimum number of score jobs required for parallel candidate scoring when enabled. Effective minimum is one job.
Aromatic ring scores and conjugation · organic_topology

config.organic_topology · OrganicTopologyConfig

Field Type Default Meaning
aromatic_stability_benzene_score float 1.0 Stability contribution of a six-carbon aromatic ring with no formally charged atoms and no unpaired electrons.
aromatic_stability_other_ring_max_score float 0.99 Upper bound on the per-ring stability contribution after multiplying the size, heteroatom, charge and radical factors for other aromatic rings.
aromatic_stability_ring_size_6_factor float 0.92 Base stability multiplier for a six-heavy-atom aromatic ring outside the neutral, closed-shell all-carbon case.
aromatic_stability_ring_size_5_factor float 0.84 Base stability multiplier for a five-heavy-atom aromatic ring before electronic penalties.
aromatic_stability_other_ring_size_factor float 0.76 Base stability multiplier for an aromatic ring with a heavy-atom count other than five or six.
aromatic_stability_hetero_atom_penalty float 0.1 Amount subtracted from the heteroatom factor for each noncarbon heavy atom in an aromatic ring. The factor starts at one.
aromatic_stability_min_hetero_factor float 0.62 Lower bound on the aromatic ring multiplier after the heteroatom penalty.
aromatic_stability_formal_charge_penalty float 0.16 Amount subtracted from the charge factor for each ring atom with a nonzero formal charge. Each charged atom counts once regardless of charge magnitude.
aromatic_stability_min_charge_factor float 0.5 Lower bound on the aromatic ring multiplier after the formal-charge penalty.
aromatic_stability_radical_penalty float 0.2 Amount subtracted from the radical factor for each ring atom carrying unpaired electrons. Each radical-bearing atom counts once.
aromatic_stability_min_radical_factor float 0.5 Lower bound on the aromatic ring multiplier after the radical penalty.
conjugation_normalized_tetrahedron_volume_tolerance float 0.075 Largest dimensionless tetrahedron volume accepted by the donor–acceptor coplanarity check. Volume is normalized by the cube of the RMS edge length. Larger values allow more distortion.
conjugation_min_plane_overlap float 0.5 Minimum mean squared cosine between observable local pi-plane normals for conjugation. A value of 0.5 corresponds to 45 degrees for two planar environments.
Metal assignments and coordination · metal_scoring

config.metal_scoring · MetalScoringConfig

Field Type Default Meaning
open_shell_multimetal_state_penalty_window float 10.0 Penalty interval used to widen successive metal-state layers in open-shell multimetal search. Zero advances one distinct penalty at a time. A negative value opens all options in the first layer.
open_shell_multimetal_min_state_options int 6 Minimum number of available state choices admitted per group in the first open-shell multimetal layer, including ties at the cutoff. Values below one are treated as one.
same_element_multimetal_unify_threshold int 3 When the number of metals of one element exceeds this threshold, group them if they share valence and radical-count options. A negative value disables grouping.
max_mixed_valence_spread Optional[int] 3 Maximum difference between the highest and lowest assigned valences for metals of the same element. None or a negative value disables this limit.
max_assignments_per_target int 64 Maximum number of ranked metal-state assignments retained for a given charge and radical target. At least one slot is retained.
metal_coordination_extra_tolerance_angstrom float 0.75 Distance in angstroms added to the scaled sum of metal and donor covalent radii when screening coordination contacts.
pi_dative_distance_difference_tolerance_angstrom float 0.1 Largest allowed difference in angstroms between the two metal-to-endpoint distances when considering a ligand bond as a pi donor during dative-bond post-processing.
metal_access_radius_scale float 1.0 Dimensionless multiplier for the covalent radii in coordination cutoffs and in the spheres used to test whether a donor is visible from the metal.
metal_access_clearance_angstrom float 0.0 Distance in angstroms added to each scaled blocker radius in metal-to-donor visibility tests. Increasing it makes more donor paths count as obstructed.
charge_localization_selection_margin float 0.3 Allowed increase in the organic charge-localization penalty relative to the reference candidate used in metal-state ranking. Reaching the margin can demote a candidate. A large oxidation-state jump is checked separately.
Metal spin and donor geometry · metal_radical_inference

config.metal_radical_inference · MetalRadicalInferenceConfig

Field Type Default Meaning
max_considered_donors int 6 Maximum number of candidate donors used to characterize a metal site. The closest donors are considered first.
square_planar_planarity_tolerance_angstrom float 0.45 Maximum out-of-plane distance in angstroms for classifying four donors as square planar around the metal.
trigonal_planar_planarity_tolerance_angstrom float 0.35 Maximum out-of-plane distance in angstroms for classifying three donors as trigonal planar around the metal.
linear_angle_min_degrees float 150.0 Minimum donor–metal–donor angle in degrees for a two-coordinate site to be classified as linear.
strong_field_threshold float 1.1 Base ligand-field score for strong-field classification. The score must reach this threshold plus the ambiguity margin.
weak_field_threshold float 0.75 Base ligand-field score for weak-field classification. The score must be at or below this threshold minus the ambiguity margin.
field_ambiguity_margin float 0.1 Buffer in ligand-field score units added to the strong-field threshold and subtracted from the weak-field threshold. Increasing it widens the ambiguous interval.
Output validation and failure policy · interface

config.interface · PythonInterfaceConfig

Field Type Default Meaning
reconstruction_failure_policy ReconstructionFailurePolicy 'raise' Use "raise" to raise ReconstructionError on single-frame reconstruction failure or "return_suspicious" to return a marked initial-perception graph. Single-frame input validation still raises for an impossible charge or spin.
require_smiles_roundtrip bool True Verify that the finalized explicit-H atom and bond labels survive RDKit SMILES writing and reading. Coordinate-derived stereo stays on the returned graph. To test stereo serialization, use validate_smiles_roundtrip with check_stereochemistry=True.

A multi-worker C++ batch parallelizes across molecules and disables within-molecule target and scoring parallelism. A single worker honors the supplied settings.

Diagnostics and failure policy

Electronic validation precedes backend search. This single-frame call raises an input diagnostic even under the fallback policy.

from molgr import ReconstructionError
from molgr.interface import xyz_to_rdmol

try:
    xyz_to_rdmol("1\nH atom\nH 0 0 0\n", spin_multiplicity=1)
except ReconstructionError as exc:
    print(exc.diagnostics.code.value, exc.diagnostics.stage)
INVALID_ELECTRONIC_TARGET input.electronic_state

ReconstructionError subclasses ValueError and exposes .diagnostics. ReconstructionDiagnostics contains code, stage, backend, message, counts, details, cause_type, and cause_message. Use .as_dict() or

For metal scoring diagnostics, consult the rule index. For example, metal_pyramidal_pn_geometry_conflict_count records a geometry conflict in cyclic RPN₂. .as_json() to serialize it. Definitions are in diagnostics.py.

Failure code Meaning
INVALID_XYZ Input could not be parsed as XYZ.
INVALID_ELECTRONIC_TARGET Charge/electron count and multiplicity are incompatible.
NO_REACHABLE_METAL_STATE Metal-state search found no reachable assignment.
NO_VALID_ORGANIC_CANDIDATE Ligand or metal-free reconstruction found no valid candidate.
ALL_METAL_CANDIDATES_REJECTED Candidate metal assignments were rejected.
OUTPUT_INVARIANT_BROKEN The output failed a required invariant.
BACKEND_EXCEPTION The reconstruction backend raised an exception.
RDKIT_POSTPROCESS_FAILED RDKit conversion or finalization failed.
SMILES_ROUNDTRIP_FAILED The final graph failed the explicit-H SMILES round-trip check.
NO_VALID_RECONSTRUCTION Reconstruction failed without a more specific code.

An unknown policy raises ValueError when handling a failure. With return_suspicious, eligible reconstruction/finalization failures return an initial Open Babel perception graph carrying _MolGRReconstructionStatus="suspicious_fallback". It is a diagnostic artifact, not a graph confirmed to satisfy the search targets. Input validation still raises. See failure handling.

Use mol.HasProp("_MolGRReconstructionDiagnostics") to identify a fallback carrying serialized diagnostics. Read its JSON with mol.GetProp("_MolGRReconstructionDiagnostics"). Read _MolGRReconstructionFailureCode and _MolGRReconstructionFailureStage for its code and stage.

Serialization and comparison

Use the same kekulize setting for reconstruction, molgr.mol_from_smiles() and molgr.validate_smiles_roundtrip(). Both modes retain explicit hydrogen nodes. Ordinary SMILES does not preserve coordinates or all MolGR electron annotations. Use the original molecule when these properties are needed; see the SMILES reference.

molgr.utils.equivalence.evaluate_equivalence() returns equivalent, not_equivalent, or inconclusive under its documented representation rules. It uses max_resonance=5000, ignores metal coordination bonds by default, and uses use_chirality=False. These are comparison settings, not reconstruction parameters. See the evaluator reference.

Installation and compatibility

Install with pip install molgr. The package requires Python ≥3.8; the CI matrix covers Python 3.8–3.14 on Linux, macOS, and Windows. Runtime dependencies include RDKit, NumPy, and Open Babel. Python 3.8–3.9 use openbabel-wheel; Python ≥3.10 uses openbabel>=3.2.0. Exact constraints are in pyproject.toml. Both backends require the native MolGR extension and Open Babel. The Python backend is a reference implementation, not a compilation-free installation option.

Compatible wheels avoid local compilation. Source installation requires the build prerequisites. The package provides a Python API and has no molgr console command. For benchmark commands, see the repository benchmark guide.

For the signatures and docstrings in your installed version, import the functions and call help(xyz_to_rdmol) or help(iter_xyz_to_rdmol_batch).