Skip to main content

xpict_core/
edge.rs

1//! EdgePlan / EdgeResult — host callback ABI (coord_gen / align).
2//!
3//! Core builds the plan (ids + forest); language edges process it and return
4//! flat [`MoleculeIn`] results. No molblocks on this wire.
5
6use serde::{Deserialize, Serialize};
7
8use crate::scene::MoleculeIn;
9
10#[cfg(feature = "codegen")]
11use schemars::JsonSchema;
12#[cfg(feature = "codegen")]
13use ts_rs::TS;
14
15/// Minimum mapped atoms before align is trusted (MCS or explicit map).
16pub const MIN_MCS_ATOMS: u32 = 3;
17
18/// MCS search style for [`AlignOpts::mode`].
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
22#[cfg_attr(feature = "codegen", ts(export))]
23pub enum AlignMode {
24    /// Branch-and-bound until timeout / node cap (house default).
25    #[default]
26    Exact,
27    /// Greedy incumbent only — skip BnB.
28    Greedy,
29    /// Free CoordGen; ignore the parent template.
30    Skip,
31}
32
33/// Align this mol onto its parent template.
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
35#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
36#[cfg_attr(feature = "codegen", ts(export))]
37pub struct AlignOpts {
38    /// Pairs `(query_atom, template_atom)`. `None` → edge runs MCS.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    #[cfg_attr(feature = "codegen", ts(optional))]
41    pub atom_map: Option<Vec<(u32, u32)>>,
42    /// Override [`MIN_MCS_ATOMS`] when set.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    #[cfg_attr(feature = "codegen", ts(optional))]
45    pub min_atoms: Option<u32>,
46    /// `exact` (default) / `greedy` / `skip`. Omit = exact with house timeout.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    #[cfg_attr(feature = "codegen", ts(optional))]
49    pub mode: Option<AlignMode>,
50    /// MCS budget in milliseconds. `None` = house 100 ms; `0` = unbounded.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    #[cfg_attr(feature = "codegen", ts(optional))]
53    pub timeout_ms: Option<u32>,
54}
55
56impl AlignOpts {
57    pub fn align_mode(&self) -> AlignMode {
58        self.mode.unwrap_or(AlignMode::Exact)
59    }
60
61    /// Search caps for MCS. Explicit `atom_map` skips search entirely.
62    pub fn search_limits(&self) -> crate::align_cost::SearchLimits {
63        crate::align_cost::SearchLimits::from_timeout_ms(
64            self.timeout_ms,
65            matches!(self.align_mode(), AlignMode::Greedy),
66        )
67    }
68}
69
70/// One node in a coord_gen forest (root = free layout; children align to parent).
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
72#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
73#[cfg_attr(feature = "codegen", ts(export))]
74pub struct MolTemplate {
75    /// Rust-assigned unique id; round-trips to the document node.
76    pub id: String,
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    #[cfg_attr(feature = "codegen", ts(optional))]
79    pub smiles: Option<String>,
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    #[cfg_attr(feature = "codegen", ts(optional))]
82    pub cxsmiles: Option<String>,
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    #[cfg_attr(feature = "codegen", ts(optional))]
85    pub molfile: Option<String>,
86    /// Opts for aligning onto the parent; `None` on roots.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    #[cfg_attr(feature = "codegen", ts(optional))]
89    pub align: Option<AlignOpts>,
90    /// Children that use this node as their align template.
91    #[serde(default, skip_serializing_if = "Vec::is_empty")]
92    pub template_for: Vec<MolTemplate>,
93}
94
95impl MolTemplate {
96    /// Exactly one of smiles / cxsmiles / molfile must be set.
97    pub fn validate_structure(&self) -> Result<(), String> {
98        let n = [&self.smiles, &self.cxsmiles, &self.molfile]
99            .iter()
100            .filter(|s| s.as_ref().is_some_and(|t| !t.trim().is_empty()))
101            .count();
102        if n == 1 {
103            Ok(())
104        } else {
105            Err(format!(
106                "MolTemplate {}: need exactly one of smiles/cxsmiles/molfile",
107                self.id
108            ))
109        }
110    }
111
112    pub fn source(&self) -> Result<&str, String> {
113        self.validate_structure()?;
114        if let Some(s) = self.smiles.as_deref().filter(|t| !t.trim().is_empty()) {
115            return Ok(s);
116        }
117        if let Some(s) = self.cxsmiles.as_deref().filter(|t| !t.trim().is_empty()) {
118            return Ok(s);
119        }
120        if let Some(s) = self.molfile.as_deref().filter(|t| !t.trim().is_empty()) {
121            return Ok(s);
122        }
123        Err(format!("MolTemplate {}: empty structure", self.id))
124    }
125}
126
127/// ``type: "coord_gen"`` edge task.
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
129#[serde(tag = "type", rename_all = "snake_case")]
130#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
131#[cfg_attr(feature = "codegen", ts(export))]
132pub enum EdgeTask {
133    CoordGen {
134        #[serde(default)]
135        roots: Vec<MolTemplate>,
136    },
137}
138
139/// Host callback request.
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
142#[cfg_attr(feature = "codegen", ts(export))]
143pub struct EdgePlan {
144    pub version: u32,
145    #[serde(default)]
146    pub tasks: Vec<EdgeTask>,
147}
148
149impl EdgePlan {
150    pub fn new_v1(tasks: Vec<EdgeTask>) -> Self {
151        Self { version: 1, tasks }
152    }
153
154    pub fn validate(&self) -> Result<(), String> {
155        if self.version != 1 {
156            return Err(format!("unsupported EdgePlan version {}", self.version));
157        }
158        let mut seen = std::collections::HashSet::new();
159        for task in &self.tasks {
160            match task {
161                EdgeTask::CoordGen { roots } => {
162                    for root in roots {
163                        validate_tree(root, /*is_root*/ true, &mut seen)?;
164                    }
165                }
166            }
167        }
168        Ok(())
169    }
170}
171
172fn validate_tree(
173    node: &MolTemplate,
174    is_root: bool,
175    seen: &mut std::collections::HashSet<String>,
176) -> Result<(), String> {
177    if !seen.insert(node.id.clone()) {
178        return Err(format!("duplicate MolTemplate id {}", node.id));
179    }
180    node.validate_structure()?;
181    if is_root && node.align.is_some() {
182        return Err(format!(
183            "MolTemplate {}: roots must have align=null",
184            node.id
185        ));
186    }
187    if !is_root && node.align.is_none() {
188        // Children may omit align object (= MCS defaults); that's OK.
189    }
190    for child in &node.template_for {
191        validate_tree(child, false, seen)?;
192    }
193    Ok(())
194}
195
196/// How coords were produced for one molecule.
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(rename_all = "snake_case")]
199#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
200#[cfg_attr(feature = "codegen", ts(export))]
201pub enum CoordMethod {
202    Free,
203    AtomMap,
204    Mcs,
205    /// Greedy incumbent (mode `greedy`, or exact search that never entered BnB).
206    Greedy,
207    /// Mode `skip` — free layout despite a parent template.
208    Skip,
209    /// Align was requested but failed — host fell back to unaligned coord gen.
210    None,
211}
212
213/// One flat molecule entry in a coord_gen result.
214#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
216#[cfg_attr(feature = "codegen", ts(export))]
217pub struct CoordGenMoleculeResult {
218    pub id: String,
219    /// True when usable coords were produced (aligned or free-layout fallback).
220    pub ok: bool,
221    pub method: CoordMethod,
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    #[cfg_attr(feature = "codegen", ts(optional))]
224    pub used_map: Option<Vec<(u32, u32)>>,
225    /// Present whenever ``ok`` is true.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    #[cfg_attr(feature = "codegen", ts(optional))]
228    pub molecule: Option<MoleculeIn>,
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    #[cfg_attr(feature = "codegen", ts(optional))]
231    pub error: Option<String>,
232}
233
234#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
235#[serde(tag = "type", rename_all = "snake_case")]
236#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
237#[cfg_attr(feature = "codegen", ts(export))]
238pub enum EdgeTaskResult {
239    CoordGen {
240        ok: bool,
241        molecules: Vec<CoordGenMoleculeResult>,
242    },
243}
244
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
246#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
247#[cfg_attr(feature = "codegen", ts(export))]
248pub struct EdgeResult {
249    pub version: u32,
250    #[serde(default)]
251    pub results: Vec<EdgeTaskResult>,
252}
253
254impl EdgeResult {
255    pub fn new_v1(results: Vec<EdgeTaskResult>) -> Self {
256        Self {
257            version: 1,
258            results,
259        }
260    }
261
262    /// Collect all molecule rows across tasks (order preserved).
263    pub fn molecules(&self) -> Vec<&CoordGenMoleculeResult> {
264        let mut out = Vec::new();
265        for r in &self.results {
266            match r {
267                EdgeTaskResult::CoordGen { molecules, .. } => out.extend(molecules.iter()),
268            }
269        }
270        out
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277
278    fn sample_plan() -> EdgePlan {
279        EdgePlan::new_v1(vec![EdgeTask::CoordGen {
280            roots: vec![MolTemplate {
281                id: "m_0".into(),
282                smiles: Some("c1ccccc1".into()),
283                cxsmiles: None,
284                molfile: None,
285                align: None,
286                template_for: vec![MolTemplate {
287                    id: "m_1".into(),
288                    smiles: Some("Cc1ccccc1".into()),
289                    cxsmiles: None,
290                    molfile: None,
291                    align: Some(AlignOpts {
292                        atom_map: Some(vec![(1, 0), (2, 1), (3, 2), (4, 3), (5, 4), (6, 5)]),
293                        ..Default::default()
294                    }),
295                    template_for: vec![],
296                }],
297            }],
298        }])
299    }
300
301    #[test]
302    fn plan_json_roundtrip() {
303        let plan = sample_plan();
304        plan.validate().unwrap();
305        let s = serde_json::to_string(&plan).unwrap();
306        let back: EdgePlan = serde_json::from_str(&s).unwrap();
307        assert_eq!(back, plan);
308    }
309
310    #[test]
311    fn reject_duplicate_ids() {
312        let mut plan = sample_plan();
313        match &mut plan.tasks[0] {
314            EdgeTask::CoordGen { roots } => {
315                roots[0].template_for[0].id = "m_0".into();
316            }
317        }
318        assert!(plan.validate().unwrap_err().contains("duplicate"));
319    }
320
321    #[test]
322    fn reject_root_with_align() {
323        let plan = EdgePlan::new_v1(vec![EdgeTask::CoordGen {
324            roots: vec![MolTemplate {
325                id: "m_0".into(),
326                smiles: Some("CCO".into()),
327                cxsmiles: None,
328                molfile: None,
329                align: Some(AlignOpts::default()),
330                template_for: vec![],
331            }],
332        }]);
333        assert!(plan.validate().unwrap_err().contains("align=null"));
334    }
335
336    #[test]
337    fn template_source_accepts_cxsmiles_and_molfile() {
338        let cx = MolTemplate {
339            id: "c".into(),
340            smiles: None,
341            cxsmiles: Some("*C |$R;$|".into()),
342            molfile: None,
343            align: None,
344            template_for: vec![],
345        };
346        assert_eq!(cx.source().unwrap(), "*C |$R;$|");
347        let mf = MolTemplate {
348            id: "m".into(),
349            smiles: None,
350            cxsmiles: None,
351            molfile: Some("molblock".into()),
352            align: None,
353            template_for: vec![],
354        };
355        assert_eq!(mf.source().unwrap(), "molblock");
356        let bad = MolTemplate {
357            id: "b".into(),
358            smiles: Some("C".into()),
359            cxsmiles: Some("CC".into()),
360            molfile: None,
361            align: None,
362            template_for: vec![],
363        };
364        assert!(bad
365            .validate_structure()
366            .unwrap_err()
367            .contains("exactly one"));
368    }
369
370    #[test]
371    fn fallback_result_lists_all_ids() {
372        let result = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
373            ok: true,
374            molecules: vec![
375                CoordGenMoleculeResult {
376                    id: "m_0".into(),
377                    ok: true,
378                    method: CoordMethod::Free,
379                    used_map: None,
380                    molecule: None,
381                    error: None,
382                },
383                CoordGenMoleculeResult {
384                    id: "m_1".into(),
385                    ok: true,
386                    method: CoordMethod::None,
387                    used_map: None,
388                    molecule: None,
389                    error: Some("align failed; fell back".into()),
390                },
391            ],
392        }]);
393        let ids: Vec<_> = result.molecules().iter().map(|m| m.id.as_str()).collect();
394        assert_eq!(ids, ["m_0", "m_1"]);
395        assert!(matches!(
396            &result.results[0],
397            EdgeTaskResult::CoordGen { ok: true, .. }
398        ));
399    }
400}