Process XYZ files in batches
Run these examples from a MolGR checkout with the package installed. Give each structure its own XYZ text, charge and multiplicity.
Batch processing
The iterator yields (request, molecule, status) for each input. On success, molecule holds the reconstructed graph and status is None. On failure, status holds a ReconstructionDiagnostics object. The molecule field is normally None, but can hold a graph marked for review when return_suspicious is enabled.
from pathlib import Path
from rdkit import Chem
from molgr import ReconstructionBatchRequest, iter_xyz_to_rdmol_batch
# Run from the repository root; each request carries its own charge and spin.
path = Path("tests/data/tmqmg/reconstruction/ABACAL.xyz")
requests = [
ReconstructionBatchRequest(
path.read_text(encoding="utf-8"),
total_charge=0,
spin_multiplicity=1,
request_id=str(path),
)
]
for request, molecule, status in iter_xyz_to_rdmol_batch(requests):
if status is not None:
print(request.request_id, status.code.value, status.stage, status.message)
continue
print(Chem.MolToSmiles(molecule))
- Results default to completion order. Set
ordered=Trueto preserve input order, orraise_on_error=Trueto stop iteration on an item failure. max_workers=Noneselects the native worker count from the configuration;queue_size=16controls the result queue. Multi-worker batches disable per-molecule parallelism to avoid nested worker pools. The Python backend is serial and accepts onlymax_workers=Noneor1.- Results stream, but inputs are materialized before scheduling. A generator is accepted only if finite; large datasets should be split into bounded chunks.
queue_sizedoes not limit input memory. - Windows defaults to one native thread. Keep that default, including
max_workers=Noneor1, unless the workload has been validated locally; concurrent Open Babel reconstruction can cause native access violations.
Bound the input size
For a large finite input, consume requests in chunks. The following loop keeps at most 256 input requests in each batch and reports the original request with each failure.
import csv
from itertools import islice
source = iter(requests)
with open("failed.csv", "w", encoding="utf-8", newline="") as failures:
writer = csv.writer(failures)
writer.writerow(["request_id", "stage", "code", "message"])
while True:
chunk = list(islice(source, 256))
if not chunk:
break
for request, molecule, status in iter_xyz_to_rdmol_batch(chunk):
if status is None:
print(Chem.MolToSmiles(molecule))
else:
writer.writerow([request.request_id, status.stage, status.code.value, status.message])
Process-based parallelism
Windows sets config.cpp_backend.max_threads=1 by default; this is not a mandatory cap. Explicit batch max_workers takes precedence over that configuration. For parallel processing on Windows, Linux, or macOS, use multiple processes with one MolGR thread per process.
Save the following as a .py file and run it as a script. The worker function must be defined at module scope, and process creation must be inside the __main__ guard. Replace the sample requests with your XYZ inputs and their charges and multiplicities.
import multiprocessing as mp
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from rdkit import Chem
from molgr.config import MolGRConfig
from molgr.interface import xyz_to_rdmol
def reconstruct(request):
xyz, charge, multiplicity = request
config = MolGRConfig()
config.cpp_backend.max_threads = 1
config.cpp_backend.enable_target_bucket_parallelism = False
config.cpp_backend.enable_candidate_scoring_parallelism = False
mol = xyz_to_rdmol(
xyz, total_charge=charge, spin_multiplicity=multiplicity, config=config
)
return Chem.MolToSmiles(mol)
if __name__ == "__main__":
paths = [Path("tests/data/xyz/338-S.xyz"), Path("tests/data/tmqmg/reconstruction/ABACAL.xyz")]
requests = [(path.read_text(encoding="utf-8"), 0, 1) for path in paths]
with ProcessPoolExecutor(max_workers=4, mp_context=mp.get_context("spawn")) as pool:
for smiles in pool.map(reconstruct, requests):
print(smiles)
The worker writes the SMILES before returning it so the parent receives the square-planar Pd label as written by RDKit. Here, ProcessPoolExecutor(max_workers=4) controls the number of processes. Each process reconstructs one molecule at a time with internal parallelism disabled. If you call iter_xyz_to_rdmol_batch() inside a worker instead, also set its max_workers=1. Use spawn so each process initializes its own MolGR/Open Babel state; MolGR rejects calls from a child forked after initialization. pool.map() returns results in input order and propagates reconstruction errors.