Skip to main content

chematic_cip/
lib.rs

1//! `chematic-cip` — low-level, hierarchical-digraph CIP (Cahn-Ingold-Prelog)
2//! stereochemistry engine for chematic.
3//!
4//! **Most applications should use [`chematic_chem::assign_cip_with_mode`] rather
5//! than depending on this crate directly.** That's the stable, supported entry point
6//! (opt-in `CipMode::Accurate`: this engine's R/S and E/Z, legacy allenes; see
7//! `docs/rfcs/cip_accurate_rfc.md`'s Milestone 5A). This crate is the low-level engine
8//! behind it, published separately so `chematic-chem` can depend on it normally.
9//! The accurate engine remains experimental and may receive breaking API revisions
10//! in a future 0.x minor release.
11//!
12//! Full milestone history in `docs/rfcs/cip_accurate_rfc.md` at the workspace root: this
13//! crate now builds a provenance-carrying digraph, ranks substituents (Rules 1a/1b/2/4b/5),
14//! and assigns R/S — the current residual-corpus report estimates 99.64%
15//! stable-oracle agreement (4171/4186) against modern RDKit `rdCIPLabeler` on
16//! the project's full validation corpus,
17//! with phosphorus on an unsaturated ring labelled as RDKit labels it (a label
18//! that changes with the Kekulé spelling, see `label_depends_on_kekule_spelling`).
19//! It does not replace `chematic_chem::assign_cip()`'s default (legacy) path, which is unaffected.
20//!
21//! The motivation is a real, proven limitation in `chematic-chem`'s existing engine:
22//! `cip_branch_spheres`/`compare_branches` pool every atom at a given BFS depth into
23//! one sorted multiset and compare shell-by-shell. That's an approximation of CIP, not
24//! the real algorithm (which recursively compares branch-by-branch, following the
25//! highest-priority sub-branch first) -- and the approximation is unsafe to patch
26//! piecemeal: extending a correct double-bond duplication rule to triple bonds went net
27//! negative (16 newly-wrong stereocenters vs. 1 newly-fixed) because the pooled
28//! representation had already discarded the branch/provenance information a correct
29//! comparison needs. This crate's [`digraph::CipDigraph`] keeps that information as
30//! explicit, provenance-carrying nodes instead.
31#![forbid(unsafe_code)]
32
33pub mod assign;
34mod auxiliary;
35pub mod budget;
36pub mod compare;
37pub mod debug;
38pub mod digraph;
39pub mod digraph_diff;
40pub mod edge;
41pub mod mancude;
42pub mod node;
43pub mod rational;
44mod resolver;
45mod rule4b;
46pub mod substituent_rank;
47pub mod trace;
48
49#[cfg(test)]
50mod tests;
51
52pub use assign::{
53    AccurateCipAssignment, SkipReason, assign_cip_accurate_experimental,
54    assign_cip_accurate_experimental_without_mancude, label_depends_on_kekule_spelling,
55    label_follows_rdkit_smiles_reading,
56};
57pub use budget::CipBudget;
58pub use compare::{
59    BranchComparison, CipCompareError, CompareContext, compare_ligands, rank_children,
60};
61pub use digraph::{CipDigraph, DigraphExpander};
62pub use edge::{CipEdge, EdgeId};
63pub use mancude::{
64    MancudeBudget, MancudeComponentId, MancudeContext, MancudeError, effective_atomic_number,
65    enumerate_kekule_matchings, prepare_kekule_form,
66};
67pub use node::{CipNode, CipNodeKind, NodeId};
68pub use rational::{AtomicNumberKey, RationalAtomicNumber};
69pub use substituent_rank::SubstituentRanker;
70pub use trace::{ComparisonTrace, DecisionStep};
71
72/// Errors from digraph construction/expansion.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum CipError {
75    /// Expansion exceeded a [`CipBudget`] limit (node count, depth, or expansion
76    /// count). Never returned as a substitute for a wrong-but-plausible answer --
77    /// exceeding budget always surfaces as this error, not a silently truncated or
78    /// guessed structure.
79    BudgetExceeded { reason: String },
80}
81
82impl core::fmt::Display for CipError {
83    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
84        match self {
85            CipError::BudgetExceeded { reason } => {
86                write!(f, "CIP digraph budget exceeded: {reason}")
87            }
88        }
89    }
90}
91
92impl std::error::Error for CipError {}
93
94#[cfg(test)]
95mod debug_boundary_contract_tests;
96
97#[cfg(test)]
98mod error_contract_tests {
99    use super::*;
100
101    #[test]
102    fn budget_error_preserves_the_reason() {
103        let error = CipError::BudgetExceeded {
104            reason: "node limit".into(),
105        };
106        assert_eq!(error.to_string(), "CIP digraph budget exceeded: node limit");
107        let source: &dyn std::error::Error = &error;
108        assert!(source.source().is_none());
109    }
110}