Metadata-Version: 2.4
Name: mofchecker-next
Version: 0.2.1
Classifier: License :: OSI Approved :: GNU General Public License v2 (GPLv2)
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: Topic :: Scientific/Engineering :: Chemistry
Requires-Dist: numpy>=1.26
Requires-Dist: ase>=3.22
Requires-Dist: pymatgen>=2024.11.13,<2026
Requires-Dist: networkx>=3
Requires-Dist: structuregraph-helpers>=0.0.9
Requires-Dist: element-coder>=0.0.8
Requires-Dist: libconeangle>=0.1.2
Requires-Dist: rustworkx>=0.14
Requires-Dist: pytest>=8 ; extra == 'test'
Requires-Dist: maturin>=1.7,<2 ; extra == 'test'
Provides-Extra: test
License-File: LICENSE
Summary: Fast, fault-tolerant drop-in replacement for MOFChecker 0.9.6, built on Rust kernels
Author: Hendrik Kraß
License: GPL-2.0-only
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/henk789/mofchecker-next

<h1 align="center">
  mofchecker-next
</h1>

<p align="center">
  <b>A fast, fault-tolerant drop-in replacement for <a href="https://github.com/lamalab-org/mofchecker">MOFChecker</a> 0.9.6</b> — identical results on all 20,374 QMOF structures, the same API and CLI flags, <b>23× faster</b> per core and 536 structures/s on one 64-core node.
</p>

<p align="center">
    <a href="https://github.com/henk789/mofchecker-next/actions/workflows/ci.yml">
        <img alt="CI" src="https://github.com/henk789/mofchecker-next/actions/workflows/ci.yml/badge.svg" />
    </a>
    <a href="https://pypi.org/project/mofchecker-next/">
        <img alt="PyPI" src="https://img.shields.io/pypi/v/mofchecker-next" />
    </a>
    <a href="https://pypi.org/project/mofchecker-next/">
        <img alt="Python versions" src="https://img.shields.io/pypi/pyversions/mofchecker-next" />
    </a>
    <a href="https://github.com/henk789/mofchecker-next/blob/main/py/mofchecker_next/eqeq/LICENSE">
        <img alt="License" src="https://img.shields.io/pypi/l/mofchecker-next" />
    </a>
    <img alt="Speedup" src="https://img.shields.io/badge/vs%20MOFChecker%200.9.6-23%C3%97%20faster-brightgreen" />
    <img alt="Built with Rust" src="https://img.shields.io/badge/built%20with-Rust%20%2B%20PyO3-orange" />
</p>

Designed for the workloads where the original is painful: **validating thousands of model-generated MOFs** (e.g. from a diffusion model). Every structure runs in an isolated worker with a hard timeout, so a pathological CIF costs one error record, never the run.

## 💪 Getting started

Install a published wheel with `pip install mofchecker-next`. Building from the
source distribution additionally requires Rust, a C compiler, and libclang
(`qhull-sys` generates bindings at build time); ordinary wheel installs do not.
Release CI installs and smoke-tests every built wheel before publishing.

```python
from mofchecker_next import MOFChecker

# Default: exact legacy MOFChecker 0.9.6 behavior used by published MOF metrics.
mc = MOFChecker.from_cif("structure.cif")     # also .from_ase(atoms) / MOFChecker(structure)
mc.has_atomic_overlaps, mc.has_lone_molecule, mc.has_oms, mc.metal_number
descriptors = mc.get_mof_descriptors()

# Newer behavior remains explicit:
modern = MOFChecker.from_cif("structure.cif", mode="2.0")
corrected = MOFChecker.from_cif("structure.cif", mode="next")
```

`mode="next"` currently resolves to provisional `next-dev-2`. Its named
`generated_desolvated_organic_mof_v1` composite requires input sanity, C/metal
scope, objective overlap/overcoordination/component checks, and true-element
Rust EQeq at declared total charge 0. Unvalidated C/N undercoordination,
hydrogen presence, exposed-metal/terminal-oxo/rare-earth rules, connectivity and
OMS remain report-only. The `|q| > 4.0` policy is still provisional, so this is a
shadow-production evaluator rather than frozen `next-1.0`. Results include the
exact composite fields, structured check evidence, source-tree/profile/input
manifests, and separate structure/local-chemistry/charge/component/scope
statuses. See `docs/NEXT_PRODUCTION_PLAN.md` for release gates and blockers.

`mode="0.9.6"` restores the legacy undercoordinated C/N rules, carbon-overcoordination
rule, rare-earth element set (no Sc/Y), `|q| > 3` EqEq threshold and EQeq's
CIF-label element parsing, unsplit floating-component flag, CIF parsing,
symmetry, and primitive defaults. It is the default; request `mode="2.0"`
explicitly for newer behavior.

Validating many structures? `mofchecker_next.batch` parallelizes across structures and never aborts the run on a single bad structure:

```python
from mofchecker_next.batch import check_structures

results = check_structures("runs/epoch_200/")             # a folder: 0.9.6 mode, all CPUs
results = check_structures(["samples.extxyz", "best/*.cif", my_structure, my_atoms], n_workers=16)
modern_results = check_structures(inputs, n_workers=16, mode="2.0")
next_results = check_structures(inputs, n_workers=16, mode="next")
bad = [r for r in results if r["has_atomic_overlaps"]]

# subset to skip work: composition-only descriptors skip graph construction entirely
fast = check_structures(inputs, descriptors=["has_atomic_overlaps", "has_overcoordinated_c"])
```

### Inputs

Everywhere a structure is accepted — `check_structures`, both CLIs — you can pass any mix of:

| Input | Becomes |
|---|---|
| pymatgen `Structure`, ASE `Atoms` | one structure each |
| `.cif` / `.cif.gz` | one structure (read exactly as MOFChecker 0.9.6 does) |
| `.xyz` / `.extxyz` | **one structure per frame**; the cell comes from the extended-XYZ `Lattice="..."` header, results are named `file.extxyz@3` |
| `POSCAR*`, `CONTCAR*`, `.vasp`, and anything else `Structure.from_file` reads | one structure |
| a folder | every file above, recursively (hidden folders skipped), in sorted order |
| a list file (`.txt`, `.lst`, `.list`) | one file, folder or glob per line, `#` comments |
| a glob such as `"runs/**/sample_*.cif"` | every match |

A file that cannot be read (no periodic cell, malformed, missing list entry) becomes one result with an `error` field; only a path you name directly that does not exist stops the call. For a single structure, `MOFChecker.from_file(path, frame=None)` picks the matching constructor: `from_cif` for CIFs, `from_ase` for XYZ frames, and 0.9.6's generic file loader otherwise.

Each result is a dict with `index`, `id`, `source` (absolute path, plus `@frame` for XYZ), `n_atoms`, and the requested descriptors. A structure that fails gets an `error` field (`on_error="record"`) instead of aborting the batch; an error in any composite field yields an indeterminate verdict and is invalid in `valid_rate_incl_errors`.

### Command line

`mofchecker-compat` is a drop-in for the official `mofchecker` command: the same flags and defaults (`--primitive` on, `-d/--descriptors` repeatable) and the same JSON list on stdout, computed in parallel and printed in input order.

```bash
mofchecker-compat structures/*.cif > descriptors.json
mofchecker-compat -d has_lone_molecule -d has_high_charges --no-primitive a.cif b.cif
```

`mofchecker-next` is the batch tool for large runs. It takes the same inputs as `check_structures`, also defaults to 0.9.6 (`--mode 2.0` / `--mode next` select the other profiles), accepts `-d`, `--all_descriptors` and `--primitive/--no-primitive`, and streams one JSON line per structure as it finishes, so an interrupted run loses nothing and `--resume` continues it:

```bash
mofchecker-next generated/ samples.extxyz --output_results_jsonl results.jsonl --output_json summary.json \
    --n_workers 64 --timeout_s 600 --memory_limit_gb 8
mofchecker-next generated/ samples.extxyz --output_results_jsonl results.jsonl --resume   # after an interruption
```

**Fault tolerance.** A supervisor hands each worker one structure at a time. A structure that exceeds `--timeout_s` is killed and recorded as a timeout; a worker that crashes (segfault, out-of-memory) is replaced and its structure retried once before it is recorded as a crash. Workers fork from a parent that has already imported the heavy dependencies, so replacing one takes milliseconds. Each worker sizes its Rust thread pool to its share of the CPUs the job may use (the Slurm/cgroup allocation, not the whole node).

## 🚀 Installation

```bash
pip install mofchecker-next
```

Latest from source (needs a Rust toolchain):

```bash
pip install git+https://github.com/henk789/mofchecker-next.git
```

## ✨ Why use it

- ⚡ **Fast.** 23× faster than MOFChecker 0.9.6 per core and 14× at 56 workers on the same CIFs; the full 20,374-structure QMOF set takes 38 s on one 64-core node (official 0.9.6: about 12 min on 32 workers).
- ✅ **Exact.** 0 disagreements with `mofchecker==0.9.6` across all 26 descriptors on all 20,374 QMOF CIFs (835,334 comparisons, two loading protocols). See **Parity**.
- 🛡️ **Fault-tolerant.** Per-structure hard timeouts, crash isolation with retry, memory limits, streamed results and resume.
- 🔌 **Drop-in.** `MOFChecker` keeps 0.9.6's constructor, `from_cif`, properties and `get_mof_descriptors()`; `mofchecker-compat` keeps its CLI.
- 🔁 **Reproducible.** `symmetry_hash` is deterministic (the reference's depends on `PYTHONHASHSEED`), and every batch result records the profile and a source/extension fingerprint.

## ⚡ Performance

500 randomly drawn QMOF CIFs (seed 0, pinned by `scripts/benchmark.py`), all 26 MOFChecker 0.9.6 descriptors through `from_cif`, wall-clock including worker start-up, 64-core node:

| Workers | MOFChecker 0.9.6 | mofchecker-next | Speedup |
|---:|---:|---:|---:|
| 1 | 739 s (0.68 /s) | 32 s (15.7 /s) | **23×** |
| 56 | 47.6 s (10.5 /s) | 3.3 s (150 /s) | **14×** |

At 56 workers the 500-structure run is dominated by start-up; the full QMOF set (20,374 CIFs, 56 workers) runs at 536 structures/s.

Per-structure cost on one core (119 atoms on average) is about 125 ms: about 40 ms parsing and symmetrising the CIF with pymatgen exactly as 0.9.6 does, about 40 ms EQeq (`has_high_charges`), and the rest spread over the graph checks.

## ⚙️ How it works

Every check runs the reference's algorithm, rewritten where the original is slow, and each rewrite is validated against the original on full QMOF:

- **Bond graph** (`checks/graph.py`): the same pymatgen neighbor-search kernel with the same arguments as `CutOffDictNN`, without building a Python object per neighbor; the graph is identical to `structuregraph_helpers.get_structure_graph`, edge order included.
- **Floating molecules** (`checks/periodic_components.py`): an integer emulation of `get_subgraphs_as_molecules`' 3x3x3 supercell, including its quirks (bond matching, rounding on wrap, last-parallel-edge wins); about 60x faster, with the original as fallback for float-sensitive inputs (~0.1% of QMOF).
- **Dimensionality**: the rank of the lattice translations spanned by each component's cycles, computed exactly with integers (pymatgen's Larsen algorithm runs thousands of small SVDs).
- **Graph and scaffold hashes** (`checks/graph_hashes.py`): the same Weisfeiler-Lehman hash on a simple graph built once, instead of deep-copying the pymatgen graph per hash.
- **Neighbor lists** (`checks/context.py`): `get_connected_sites` reproduced bit for bit, tie order included, without constructing `PeriodicSite`s.
- **Rust** (`_rust` PyO3 extension): short contacts in the LLL-reduced cell, bounded cycle enumeration, OMS Voronoi shells (qhull) and order parameters, and the EQeq charge solve, which evaluates each atom pair once and stays bit-identical to EQeq.

## ✅ Parity

`scripts/parity.py` against the official `mofchecker==0.9.6` outputs on all 20,374 QMOF CIFs:

| Protocol | Fields | Comparisons | Disagreements | Errors |
|---|---|---:|---:|---:|
| `MOFChecker.from_cif` (0.9.6 defaults) | all 26 descriptors | 529,724 | 0 | 0 |
| `Structure.from_file`, no symmetrisation or primitive cell | 15 composite fields | 305,610 | 0 | 0 |

`symmetry_hash` counts as equal when it hashes the same Wyckoff-letter set in another order, because the reference's value depends on `PYTHONHASHSEED`. The documented deviations are in `profiles.V096_DEVIATIONS`.

Reproduce:

```bash
# inside an environment with the official mofchecker installed
python scripts/reference_run.py --cif_dir QMOF --out reference.jsonl --workers 32
# in the mofchecker-next environment
python scripts/parity.py --reference reference.jsonl --cif_dir QMOF --workers 56 --report parity.json
python scripts/benchmark.py --cif_dir QMOF --sample 500 --workers 1 56 --reference_python REF/bin/python
python scripts/validate_ports.py --cif_dir QMOF --workers 56     # fast rewrites vs the code they replace
```

`mode="2.0"` reproduces MOFChecker 2.0's rules (same supercell floating-molecule algorithm) but has not had a full 20,374-QMOF audit. `mode="next"` is the corrected evaluator described above; it deliberately differs from both references.

Parity says which reference a mode reproduces, not which reference is right. For
that, `scripts/undercoordination_review.py` builds a blinded, protocol-matched,
per-atom hand-labeling study of the C/N disagreements between 0.9.6 and 2.0 and
scores both versions against the labels — see
[`docs/UNDERCOORDINATION_ADJUDICATION.md`](docs/UNDERCOORDINATION_ADJUDICATION.md).
The requirements for a separately versioned corrected evaluator are listed in
[`docs/FIXED_CHECKER.md`](docs/FIXED_CHECKER.md); the staged implementation and
validation plan is [`docs/NEXT_MODE_PLAN.md`](docs/NEXT_MODE_PLAN.md).

## ⚠️ Limitations & deliberate differences

- **Floating molecules follow the reference heuristic in 0.9.6 and 2.0 modes.** It misses finite molecules longer than about two cell lengths and can mistake a 1D chain bonded to its own image twice for a molecule (e.g. qmof-dca8305). `mode="next"` uses an exact periodic finite-component test instead.
- **No porosity.** `is_porous` returns `None` (no bundled Zeo++).
- **Healing not implemented.** `adding_hydrogen` / `adding_linker` raise `NotImplementedError`.
- **Inputs the reference mis-parses are errors.** In 0.9.6 mode a CIF without any symmetry information raises instead of being silently mangled, and non-finite EQeq charges are reported as errors.
- **`mode="2.0"` uses real elements for `has_high_charges`.** MOFChecker hands EQeq a
  pymatgen CIF and EQeq's parser reads two characters of the `<symbol><index>`
  label column, so one-letter elements (`C1`, `O2`, `U0`) miss its table and fall
  back to hydrogen's ionization row. The default `mode="0.9.6"` reproduces the
  reference behaviour bit-exactly.
- **pymatgen version.** Parity was established with pymatgen 2025.10.7 against reference outputs produced with pymatgen 2024.11.13; the dependency is pinned to `>=2024.11.13,<2026` (pymatgen 2026 removes an API that `structuregraph-helpers` needs).

## ⚖️ License

The **published package is GPLv2**, because it bundles `py/mofchecker_next/eqeq/` — a faithful translation of [EQeq](https://github.com/lsmo-epfl/EQeq) (GPLv2, see `py/mofchecker_next/eqeq/LICENSE`) — and the GPL governs the combined work. The non-eqeq sources are **MIT** (`LICENSE`); for an MIT-only build, omit the `eqeq` subpackage and the `has_high_charges` diagnostic.

The MOFChecker 2.0 checkout used as the behavioral oracle (ANCSA 1.0) is **not** redistributed; see `external/REFERENCE.md` to reproduce it locally.

## 🛠️ For developers

<details>
<summary>Build, test, and release</summary>

```bash
python -m maturin develop --release          # build the Rust extension into the venv
python -m pytest -q                          # Python tests
cargo test --release --manifest-path rust/Cargo.toml   # Rust tests
# Source builds need libclang for qhull-sys/bindgen (LIBCLANG_PATH, and on some
# systems BINDGEN_EXTRA_CLANG_ARGS="-I$(gcc -print-file-name=include)").
```

**Layout**

- `py/mofchecker_next/core.py` — the `MOFChecker` class; `profiles.py` holds every behavioural difference between modes.
- `py/mofchecker_next/checks/` — one module per topic (graph, components, coordination, metal sites, linker charges, hashes).
- `py/mofchecker_next/engine.py`, `batch.py`, `cli.py`, `compat_cli.py` — fault-tolerant worker pool, batch API, CLIs.
- `rust/` — the `_rust` PyO3 extension (contacts, cycles, OMS, EQeq kernels).
- `scripts/` — `reference_run.py`, `parity.py`, `benchmark.py`, `validate_ports.py`, and the undercoordination review.
- `tests/` — Rust and Python unit tests; CI runs both (`.github/workflows/ci.yml`).
- `docs/DIAGNOSTIC_INVENTORY.md` — per-diagnostic parity status.

**Making a release** — wheels are built and published by `.github/workflows/release.yml` via PyPI Trusted Publishing on a version tag:

```bash
git tag v0.1.0 && git push origin v0.1.0
```

</details>

