Skip to main content

xpict_core/doc/
edge_resolve.rs

1//! In-core EdgePlan processor: Chematic parse + CoordGen layout/align.
2//!
3//! Same role as the JS / `xpict` host processors, but never leaves Rust.
4
5use std::collections::HashMap;
6
7use chematic::core::{implicit_hcount, AtomIdx, BondOrder, Molecule};
8use chematic::mol::{parse_mol, parse_mol_v3000};
9use chematic::smiles::{self, parse_cxsmiles};
10
11use crate::cxsmiles::{cx_multicenters, smiles_base};
12use crate::edge::{
13    AlignMode, AlignOpts, CoordGenMoleculeResult, CoordMethod, EdgePlan, EdgeResult, EdgeTask,
14    EdgeTaskResult, MolTemplate, MIN_MCS_ATOMS,
15};
16use crate::elements::element_symbol;
17use crate::labels::atom_display_label;
18use crate::layout_coordgen::{LayoutMolecule, LayoutResult};
19use crate::layout_spoke::layout_or_align_with_spokes;
20use crate::metrics::SCALE;
21use crate::scene::{AtomIn, Attach, BondIn, MoleculeIn, SpokeIn};
22use crate::spokes::detect_ring_spokes;
23
24#[derive(Clone)]
25struct Parsed {
26    layout: LayoutMolecule,
27    atom_indices: Vec<i32>,
28    paint_orders: Vec<f64>,
29    /// Chematic implicit (or bracket-stored) H counts per atom.
30    implicit_hs: Vec<u32>,
31    /// Chematic atom-map numbers (`:n` in reaction SMILES), parallel to atoms.
32    atom_mapnos: Vec<Option<u32>>,
33}
34
35fn ctab_bond_order(order: BondOrder, a_arom: bool, b_arom: bool) -> i32 {
36    match order {
37        BondOrder::Aromatic => 4,
38        BondOrder::Double => 2,
39        BondOrder::Triple => 3,
40        BondOrder::Quadruple => 4,
41        BondOrder::Zero => 0,
42        BondOrder::Single | BondOrder::Up | BondOrder::Down | BondOrder::Dative
43            if a_arom && b_arom =>
44        {
45            4
46        }
47        _ => 1,
48    }
49}
50
51fn molecule_to_layout(mol: &Molecule) -> Result<Parsed, String> {
52    let n = mol.atom_count();
53    if n == 0 {
54        return Err("empty molecule".into());
55    }
56    let mut atomic_numbers = Vec::with_capacity(n);
57    let mut formal_charges = Vec::with_capacity(n);
58    let mut implicit_hs = Vec::with_capacity(n);
59    let mut atom_mapnos = Vec::with_capacity(n);
60    let mut arom = Vec::with_capacity(n);
61    for i in 0..n {
62        let idx = AtomIdx(i as u32);
63        let atom = mol.atom(idx);
64        let z = if atom.wildcard {
65            0
66        } else {
67            i32::from(atom.element.atomic_number())
68        };
69        atomic_numbers.push(z);
70        formal_charges.push(i32::from(atom.charge));
71        implicit_hs.push(u32::from(implicit_hcount(mol, idx)));
72        atom_mapnos.push(atom.atom_map.map(u32::from));
73        arom.push(atom.aromatic);
74    }
75    let mut bond_from = Vec::new();
76    let mut bond_to = Vec::new();
77    let mut bond_orders = Vec::new();
78    let mut paint_orders = Vec::new();
79    for (_bidx, bond) in mol.bonds() {
80        let a = bond.atom1.0 as usize;
81        let b = bond.atom2.0 as usize;
82        let order = ctab_bond_order(
83            bond.order,
84            arom.get(a).copied().unwrap_or(false),
85            arom.get(b).copied().unwrap_or(false),
86        );
87        bond_from.push(a as i32);
88        bond_to.push(b as i32);
89        bond_orders.push(order);
90        paint_orders.push(order as f64);
91    }
92    let nb = bond_from.len();
93    Ok(Parsed {
94        layout: LayoutMolecule {
95            atomic_numbers,
96            formal_charges,
97            bond_from,
98            bond_to,
99            bond_orders,
100            bond_stereos: vec![0; nb],
101            ..Default::default()
102        },
103        atom_indices: (0..n as i32).collect(),
104        paint_orders,
105        implicit_hs,
106        atom_mapnos,
107    })
108}
109
110fn parse_source(source: &str) -> Result<Parsed, String> {
111    let text = source.trim();
112    if text.is_empty() {
113        return Err("empty structure".into());
114    }
115    if text.contains("V2000") || text.contains("V3000") || text.lines().count() >= 4 {
116        let mol = if text.contains("V3000") {
117            parse_mol_v3000(text)
118                .map(|(m, _)| m)
119                .map_err(|e| format!("molfile V3000: {e}"))?
120        } else {
121            parse_mol(text)
122                .map(|(m, _)| m)
123                .map_err(|e| format!("molfile: {e}"))?
124        };
125        return molecule_to_layout(&mol);
126    }
127    let mol = if text.contains('|') {
128        parse_cxsmiles(text)
129            .map(|cx| cx.mol)
130            .map_err(|e| format!("cxsmiles: {e}"))?
131    } else {
132        smiles::parse(&smiles_base(text)).map_err(|e| format!("smiles: {e}"))?
133    };
134    molecule_to_layout(&mol)
135}
136
137fn scale_to_paint(coords: &LayoutResult, bonds: &[(i32, i32)]) -> (Vec<f64>, Vec<f64>) {
138    let mut lens = Vec::new();
139    for &(a, b) in bonds {
140        let i = a as usize;
141        let j = b as usize;
142        if i < coords.x.len() && j < coords.x.len() {
143            let dx = f64::from(coords.x[i] - coords.x[j]);
144            let dy = f64::from(coords.y[i] - coords.y[j]);
145            lens.push((dx * dx + dy * dy).sqrt());
146        }
147    }
148    let mean = if lens.is_empty() {
149        1.0
150    } else {
151        lens.iter().sum::<f64>() / lens.len() as f64
152    };
153    let s = SCALE / mean.max(1e-6);
154    let ymax = coords.y.iter().copied().fold(f32::NEG_INFINITY, f32::max);
155    let xs = coords.x.iter().map(|&x| f64::from(x) * s).collect();
156    let ys = coords.y.iter().map(|&y| f64::from(ymax - y) * s).collect();
157    (xs, ys)
158}
159
160fn to_molecule_in(id: &str, parsed: &Parsed, coords: &LayoutResult, source: &str) -> MoleculeIn {
161    let bonds_idx: Vec<(i32, i32)> = parsed
162        .layout
163        .bond_from
164        .iter()
165        .zip(parsed.layout.bond_to.iter())
166        .map(|(&a, &b)| (a, b))
167        .collect();
168    let (xs, ys) = scale_to_paint(coords, &bonds_idx);
169    let atoms: Vec<AtomIn> = (0..parsed.layout.n_atoms())
170        .map(|i| {
171            let z = parsed.layout.atomic_numbers[i] as u32;
172            let charge = parsed.layout.formal_charges[i];
173            let element = element_symbol(z).to_string();
174            let hs = parsed.implicit_hs.get(i).copied().unwrap_or(0);
175            // Charge stays on `AtomIn.charge`; `display_label` appends the
176            // suffix so we do not bake it into the string twice.
177            let label = atom_display_label(&element, hs, 0);
178            AtomIn {
179                index: parsed.atom_indices.get(i).copied().unwrap_or(i as i32),
180                element: Some(element),
181                z: Some(z),
182                x: xs.get(i).copied().unwrap_or(0.0),
183                y: ys.get(i).copied().unwrap_or(0.0),
184                label,
185                charge,
186                mapno: parsed.atom_mapnos.get(i).copied().flatten(),
187            }
188        })
189        .collect();
190    let groups = cx_multicenters(source);
191    let comps = detect_ring_spokes(parsed.layout.n_atoms(), &bonds_idx, &groups);
192    let dummy_of: HashMap<i32, &crate::spokes::SpokeComp> =
193        comps.iter().map(|c| (c.dummy, c)).collect();
194    let mut atoms = atoms;
195    for a in &mut atoms {
196        if dummy_of.contains_key(&a.index) {
197            a.label = Some(String::new());
198        }
199    }
200    let endpt_of_dummy =
201        |d: i32, other: i32| dummy_of.get(&d).is_some_and(|c| c.endpts.contains(&other));
202    let mut bonds: Vec<BondIn> = Vec::new();
203    for i in 0..parsed.layout.n_bonds() {
204        let begin = parsed.layout.bond_from[i];
205        let end = parsed.layout.bond_to[i];
206        if endpt_of_dummy(begin, end) || endpt_of_dummy(end, begin) {
207            continue;
208        }
209        bonds.push(BondIn {
210            index: i as i32,
211            begin,
212            end,
213            order: parsed
214                .paint_orders
215                .get(i)
216                .copied()
217                .unwrap_or(parsed.layout.bond_orders[i] as f64),
218            stereo: None,
219            interior: None,
220        });
221    }
222    let spokes: Vec<SpokeIn> = comps
223        .iter()
224        .map(|c| SpokeIn {
225            dummy: Some(c.dummy),
226            atom: c.atom,
227            endpts: c.endpts.clone(),
228            attach: Attach::Any,
229        })
230        .collect();
231    MoleculeIn {
232        id: Some(id.to_string()),
233        atoms,
234        bonds,
235        color: None,
236        atom_shade: None,
237        bond_shade: None,
238        shade_vmin: None,
239        shade_vmax: None,
240        scale: 1.0,
241        weight: 1.0,
242        aromatic: crate::scene::AromaticStyle::default(),
243        debug_box: false,
244        debug_align: false,
245        align_debug: None,
246        spokes,
247    }
248}
249
250fn frame_json(parsed: &Parsed, coords: &LayoutResult) -> String {
251    let atoms: Vec<serde_json::Value> = (0..parsed.layout.n_atoms())
252        .map(|i| {
253            let z = parsed.layout.atomic_numbers[i] as u32;
254            serde_json::json!({
255                "index": parsed.atom_indices.get(i).copied().unwrap_or(i as i32),
256                "element": element_symbol(z),
257                "x": coords.x.get(i).copied().unwrap_or(0.0),
258                "y": coords.y.get(i).copied().unwrap_or(0.0),
259                "charge": parsed.layout.formal_charges[i],
260            })
261        })
262        .collect();
263    let bonds: Vec<serde_json::Value> = (0..parsed.layout.n_bonds())
264        .map(|i| {
265            serde_json::json!({
266                "index": i,
267                "begin": parsed.layout.bond_from[i],
268                "end": parsed.layout.bond_to[i],
269                "order": parsed.paint_orders.get(i).copied().unwrap_or(1.0),
270            })
271        })
272        .collect();
273    serde_json::json!({ "atoms": atoms, "bonds": bonds }).to_string()
274}
275
276fn with_coords(mut layout: LayoutMolecule, coords: &LayoutResult) -> LayoutMolecule {
277    layout.input_x = Some(coords.x.clone());
278    layout.input_y = Some(coords.y.clone());
279    layout.has_template_match = None;
280    layout.is_atom_fixed = None;
281    layout
282}
283
284#[derive(Clone)]
285struct Pose {
286    parsed: Parsed,
287    layout_ref: LayoutMolecule,
288    molecule: MoleculeIn,
289    frame: String,
290}
291
292fn free_layout(source: &str, id: &str) -> Result<Pose, String> {
293    let parsed = parse_source(source)?;
294    let (coords, _) = layout_or_align_with_spokes(
295        &parsed.layout,
296        &parsed.atom_indices,
297        source,
298        None,
299        None,
300        None,
301        None,
302        None,
303    )
304    .map_err(|e| e.to_string())?;
305    let molecule = to_molecule_in(id, &parsed, &coords, source);
306    let frame = frame_json(&parsed, &coords);
307    let layout_ref = with_coords(parsed.layout.clone(), &coords);
308    Ok(Pose {
309        parsed,
310        layout_ref,
311        molecule,
312        frame,
313    })
314}
315
316fn align_layout(
317    source: &str,
318    id: &str,
319    parent: &Pose,
320    parent_id: &str,
321    atom_map: Option<&[(u32, u32)]>,
322    align: Option<&AlignOpts>,
323) -> Result<(Pose, CoordMethod), String> {
324    let parsed = parse_source(source)?;
325    let dense: Option<Vec<(i32, i32)>> =
326        atom_map.map(|pairs| pairs.iter().map(|&(q, r)| (q as i32, r as i32)).collect());
327    let (coords, dbg) = layout_or_align_with_spokes(
328        &parsed.layout,
329        &parsed.atom_indices,
330        source,
331        Some(&parent.layout_ref),
332        Some(&parent.parsed.atom_indices),
333        dense.as_deref(),
334        Some(parent_id),
335        align,
336    )
337    .map_err(|e| e.to_string())?;
338    let mut molecule = to_molecule_in(id, &parsed, &coords, source);
339    molecule.align_debug = dbg;
340    let method = if atom_map.is_some() {
341        CoordMethod::AtomMap
342    } else if matches!(align.map(AlignOpts::align_mode), Some(AlignMode::Greedy)) {
343        CoordMethod::Greedy
344    } else {
345        CoordMethod::Mcs
346    };
347    let frame = frame_json(&parsed, &coords);
348    let layout_ref = with_coords(parsed.layout.clone(), &coords);
349    Ok((
350        Pose {
351            parsed,
352            layout_ref,
353            molecule,
354            frame,
355        },
356        method,
357    ))
358}
359
360/// Process [`EdgePlan`] with Chematic + CoordGen (parity with JS host).
361pub fn process_edge_plan(plan: &EdgePlan) -> Result<EdgeResult, String> {
362    Ok(process_edge_plan_with_frames(plan)?.0)
363}
364
365/// Like [`process_edge_plan`], plus pose frames keyed by mol id.
366pub fn process_edge_plan_with_frames(
367    plan: &EdgePlan,
368) -> Result<(EdgeResult, HashMap<String, String>), String> {
369    plan.validate()?;
370    let mut task_results = Vec::new();
371    let mut all_frames = HashMap::new();
372
373    for task in &plan.tasks {
374        match task {
375            EdgeTask::CoordGen { roots } => {
376                let mut rows = Vec::new();
377                let mut poses: HashMap<String, Pose> = HashMap::new();
378
379                for root in roots {
380                    visit(root, None, &mut rows, &mut poses)?;
381                }
382
383                for (id, pose) in &poses {
384                    all_frames.insert(id.clone(), pose.frame.clone());
385                }
386                let ok = rows.iter().all(|r| r.ok);
387                task_results.push(EdgeTaskResult::CoordGen {
388                    ok,
389                    molecules: rows,
390                });
391            }
392        }
393    }
394
395    Ok((EdgeResult::new_v1(task_results), all_frames))
396}
397
398fn visit(
399    node: &MolTemplate,
400    parent_id: Option<&str>,
401    rows: &mut Vec<CoordGenMoleculeResult>,
402    poses: &mut HashMap<String, Pose>,
403) -> Result<(), String> {
404    let source = node.source()?;
405    let min_atoms = node
406        .align
407        .as_ref()
408        .and_then(|a| a.min_atoms)
409        .unwrap_or(MIN_MCS_ATOMS);
410    let atom_map = node.align.as_ref().and_then(|a| a.atom_map.clone());
411    let mode = node
412        .align
413        .as_ref()
414        .map(AlignOpts::align_mode)
415        .unwrap_or(AlignMode::Exact);
416
417    match parent_id {
418        None => match free_layout(source, &node.id) {
419            Ok(pose) => {
420                rows.push(CoordGenMoleculeResult {
421                    id: node.id.clone(),
422                    ok: true,
423                    method: CoordMethod::Free,
424                    used_map: None,
425                    molecule: Some(pose.molecule.clone()),
426                    error: None,
427                });
428                poses.insert(node.id.clone(), pose);
429            }
430            Err(e) => {
431                rows.push(CoordGenMoleculeResult {
432                    id: node.id.clone(),
433                    ok: false,
434                    method: CoordMethod::None,
435                    used_map: None,
436                    molecule: None,
437                    error: Some(e),
438                });
439                return Ok(());
440            }
441        },
442        Some(_) if mode == AlignMode::Skip => match free_layout(source, &node.id) {
443            Ok(pose) => {
444                rows.push(CoordGenMoleculeResult {
445                    id: node.id.clone(),
446                    ok: true,
447                    method: CoordMethod::Skip,
448                    used_map: None,
449                    molecule: Some(pose.molecule.clone()),
450                    error: None,
451                });
452                poses.insert(node.id.clone(), pose);
453            }
454            Err(e) => {
455                rows.push(CoordGenMoleculeResult {
456                    id: node.id.clone(),
457                    ok: false,
458                    method: CoordMethod::None,
459                    used_map: None,
460                    molecule: None,
461                    error: Some(e),
462                });
463                return Ok(());
464            }
465        },
466        Some(pid) => {
467            let Some(parent) = poses.get(pid).cloned() else {
468                match free_layout(source, &node.id) {
469                    Ok(pose) => {
470                        rows.push(CoordGenMoleculeResult {
471                            id: node.id.clone(),
472                            ok: true,
473                            method: CoordMethod::None,
474                            used_map: None,
475                            molecule: Some(pose.molecule.clone()),
476                            error: Some(format!(
477                                "missing parent pose {pid}; fell back to unaligned coord gen"
478                            )),
479                        });
480                        poses.insert(node.id.clone(), pose);
481                    }
482                    Err(e) => {
483                        rows.push(CoordGenMoleculeResult {
484                            id: node.id.clone(),
485                            ok: false,
486                            method: CoordMethod::None,
487                            used_map: None,
488                            molecule: None,
489                            error: Some(e),
490                        });
491                    }
492                }
493                for child in &node.template_for {
494                    visit(child, Some(node.id.as_str()), rows, poses)?;
495                }
496                return Ok(());
497            };
498            let map_ok = atom_map
499                .as_ref()
500                .map(|m| m.len() as u32 >= min_atoms)
501                .unwrap_or(true);
502            let use_map = if map_ok { atom_map.as_deref() } else { None };
503
504            match align_layout(source, &node.id, &parent, pid, use_map, node.align.as_ref()) {
505                Ok((pose, method)) => {
506                    rows.push(CoordGenMoleculeResult {
507                        id: node.id.clone(),
508                        ok: true,
509                        method,
510                        used_map: atom_map.clone(),
511                        molecule: Some(pose.molecule.clone()),
512                        error: None,
513                    });
514                    poses.insert(node.id.clone(), pose);
515                }
516                Err(_) => match free_layout(source, &node.id) {
517                    Ok(pose) => {
518                        rows.push(CoordGenMoleculeResult {
519                            id: node.id.clone(),
520                            ok: true,
521                            method: CoordMethod::None,
522                            used_map: None,
523                            molecule: Some(pose.molecule.clone()),
524                            error: Some("align failed; fell back to unaligned coord gen".into()),
525                        });
526                        poses.insert(node.id.clone(), pose);
527                    }
528                    Err(e) => {
529                        rows.push(CoordGenMoleculeResult {
530                            id: node.id.clone(),
531                            ok: false,
532                            method: CoordMethod::None,
533                            used_map: None,
534                            molecule: None,
535                            error: Some(e),
536                        });
537                        return Ok(());
538                    }
539                },
540            }
541        }
542    }
543
544    for child in &node.template_for {
545        visit(child, Some(node.id.as_str()), rows, poses)?;
546    }
547    Ok(())
548}
549
550#[cfg(test)]
551mod tests {
552    use super::*;
553    use crate::align_cost::{cost_mapping, mapping_cost};
554    use crate::align_layout::mol_graph_from_layout;
555    use crate::edge::EdgeTask;
556    use std::collections::HashMap;
557
558    #[test]
559    fn toluene_anisole_real_smiles_mcs_costs() {
560        let anisole = parse_source("COc1ccccc1").unwrap();
561        let toluene = parse_source("Cc1ccccc1").unwrap();
562        eprintln!(
563            "anisole bond_orders={:?} n_arom4={}",
564            anisole.layout.bond_orders,
565            anisole
566                .layout
567                .bond_orders
568                .iter()
569                .filter(|&&o| o >= 4)
570                .count()
571        );
572        eprintln!(
573            "toluene bond_orders={:?} n_arom4={}",
574            toluene.layout.bond_orders,
575            toluene
576                .layout
577                .bond_orders
578                .iter()
579                .filter(|&&o| o >= 4)
580                .count()
581        );
582        let ref_g = mol_graph_from_layout(&anisole.layout);
583        let query_g = mol_graph_from_layout(&toluene.layout);
584        eprintln!(
585            "anisole bond.aromatic={:?}",
586            ref_g.bonds.iter().map(|b| b.aromatic).collect::<Vec<_>>()
587        );
588        eprintln!(
589            "toluene bond.aromatic={:?}",
590            query_g.bonds.iter().map(|b| b.aromatic).collect::<Vec<_>>()
591        );
592
593        // Production shifted map (methyl → ring).
594        let bad: HashMap<u16, u16> = [(0, 3), (1, 2), (2, 7), (3, 6), (4, 5), (5, 4)]
595            .into_iter()
596            .collect();
597        let bad_c = mapping_cost(&query_g, &ref_g, &bad);
598        let res = cost_mapping(&ref_g, &query_g).expect("map");
599        eprintln!("cost_mapping cost={} map={:?}", res.cost, res.map);
600        eprintln!("bad_map cost={}", bad_c);
601        assert!(
602            res.cost <= bad_c,
603            "search should not prefer shifted map: got {} > bad {}",
604            res.cost,
605            bad_c
606        );
607        // Pendant Me maps to O (exo atom on the ring ipso), not a ring carbon.
608        assert_eq!(
609            res.map.get(&0),
610            Some(&1),
611            "toluene methyl should map to anisole oxygen; map={:?}",
612            res.map
613        );
614    }
615
616    /// `mol("CCCCCC") + mol("C1CCCCC1CCCCC")` must align exactly like the
617    /// same pentylcyclohexane spelled `CCCCCC1CCCCC1`: SMILES atom order is
618    /// not chemistry, so the optimum cost and the chain coverage must agree.
619    #[test]
620    fn hexane_pentylcyclohexane_alignment_is_order_independent() {
621        let hexane = mol_graph_from_layout(&parse_source("CCCCCC").unwrap().layout);
622        let ring_first = mol_graph_from_layout(&parse_source("C1CCCCC1CCCCC").unwrap().layout);
623        let chain_first = mol_graph_from_layout(&parse_source("CCCCCC1CCCCC1").unwrap().layout);
624
625        // Hexane must lie along ipso + pentyl chain — never wrapped around
626        // the cyclohexane (a zero-bond-cost tie that only atom order broke).
627        // Ring atoms: indices 0..6 in ring-first, 5..11 in chain-first.
628        let ring_first_ring = |a: u16| a < 6;
629        let chain_first_ring = |a: u16| a >= 5;
630        let ring_hits = |m: &HashMap<u16, u16>, keys: bool, in_ring: &dyn Fn(u16) -> bool| {
631            m.iter()
632                .filter(|(&q, &r)| in_ring(if keys { q } else { r }))
633                .count()
634        };
635
636        let rf = cost_mapping(&ring_first, &hexane).expect("map");
637        let cf = cost_mapping(&chain_first, &hexane).expect("map");
638        assert_eq!(rf.cost, cf.cost, "ring_first {rf:?} vs chain_first {cf:?}");
639        assert_eq!(rf.map.len(), 6, "ring_first: hexane must fully map; {rf:?}");
640        assert_eq!(
641            cf.map.len(),
642            6,
643            "chain_first: hexane must fully map; {cf:?}"
644        );
645        assert_eq!(
646            ring_hits(&rf.map, false, &ring_first_ring),
647            1,
648            "ring_first {rf:?}"
649        );
650        assert_eq!(
651            ring_hits(&cf.map, false, &chain_first_ring),
652            1,
653            "chain_first {cf:?}"
654        );
655
656        // `mol(hexane) + mol(pentylcyclohexane)`: hexane is the align ref.
657        let rf = cost_mapping(&hexane, &ring_first).expect("map");
658        let cf = cost_mapping(&hexane, &chain_first).expect("map");
659        assert_eq!(rf.cost, cf.cost, "ring_first {rf:?} vs chain_first {cf:?}");
660        assert_eq!(rf.map.len(), 6, "ring_first: six atoms should map; {rf:?}");
661        assert_eq!(cf.map.len(), 6, "chain_first: six atoms should map; {cf:?}");
662        assert_eq!(
663            ring_hits(&rf.map, true, &ring_first_ring),
664            1,
665            "ring_first {rf:?}"
666        );
667        assert_eq!(
668            ring_hits(&cf.map, true, &chain_first_ring),
669            1,
670            "chain_first {cf:?}"
671        );
672    }
673
674    #[test]
675    fn process_free_ethanol() {
676        let plan = EdgePlan::new_v1(vec![EdgeTask::CoordGen {
677            roots: vec![MolTemplate {
678                id: "m_0".into(),
679                smiles: Some("CCO".into()),
680                cxsmiles: None,
681                molfile: None,
682                align: None,
683                template_for: vec![],
684            }],
685        }]);
686        let (edge, frames) = process_edge_plan_with_frames(&plan).unwrap();
687        let EdgeTaskResult::CoordGen { molecules, ok } = &edge.results[0];
688        assert!(ok);
689        assert_eq!(molecules[0].molecule.as_ref().unwrap().atoms.len(), 3);
690        assert!(frames.contains_key("m_0"));
691    }
692
693    /// Chematic→paint must append implicit H on heteroatoms (OH / NH2), not
694    /// bare element symbols — matches RDKit host `atom_label`.
695    #[test]
696    fn chematic_labels_include_implicit_h_on_n_and_o() {
697        let cases: &[(&str, &[&str])] = &[
698            ("CCO", &["OH"]),
699            ("CCN", &["NH2"]),
700            ("c1ccccc1O", &["OH"]),
701            ("c1ccccc1N", &["NH2"]),
702            ("[NH4+]", &["NH4"]),
703            ("[OH-]", &["OH"]),
704        ];
705        for &(smiles, want_labels) in cases {
706            let mol = free_layout(smiles, "m").unwrap().molecule;
707            let got: Vec<String> = mol.atoms.iter().filter_map(|a| a.label.clone()).collect();
708            for want in want_labels {
709                assert!(
710                    got.iter().any(|g| g == *want),
711                    "{smiles}: expected label {want:?} among {got:?}"
712                );
713            }
714            // Bare heteroatom without H is wrong when H is present.
715            if want_labels.iter().any(|w| w.contains('H')) {
716                assert!(
717                    !got.iter().any(|g| g == "O" || g == "N"),
718                    "{smiles}: bare O/N label without H, got {got:?}"
719                );
720            }
721        }
722    }
723
724    fn tmpl(
725        id: &str,
726        smiles: &str,
727        align: Option<AlignOpts>,
728        kids: Vec<MolTemplate>,
729    ) -> MolTemplate {
730        MolTemplate {
731            id: id.into(),
732            smiles: Some(smiles.into()),
733            cxsmiles: None,
734            molfile: None,
735            align,
736            template_for: kids,
737        }
738    }
739
740    #[test]
741    fn skip_mode_free_layouts_child() {
742        let plan = EdgePlan::new_v1(vec![EdgeTask::CoordGen {
743            roots: vec![tmpl(
744                "a",
745                "c1ccccc1",
746                None,
747                vec![tmpl(
748                    "b",
749                    "Cc1ccccc1",
750                    Some(AlignOpts {
751                        mode: Some(AlignMode::Skip),
752                        ..Default::default()
753                    }),
754                    vec![],
755                )],
756            )],
757        }]);
758        let edge = process_edge_plan(&plan).unwrap();
759        let EdgeTaskResult::CoordGen { molecules, ok } = &edge.results[0];
760        assert!(ok);
761        assert_eq!(molecules[0].method, CoordMethod::Free);
762        assert_eq!(molecules[1].method, CoordMethod::Skip);
763        assert!(molecules[1]
764            .molecule
765            .as_ref()
766            .unwrap()
767            .align_debug
768            .is_none());
769    }
770
771    #[test]
772    fn greedy_mode_aligns_toluene_to_anisole() {
773        let plan = EdgePlan::new_v1(vec![EdgeTask::CoordGen {
774            roots: vec![tmpl(
775                "a",
776                "COc1ccccc1",
777                None,
778                vec![tmpl(
779                    "b",
780                    "Cc1ccccc1",
781                    Some(AlignOpts {
782                        mode: Some(AlignMode::Greedy),
783                        timeout_ms: Some(0),
784                        ..Default::default()
785                    }),
786                    vec![],
787                )],
788            )],
789        }]);
790        let edge = process_edge_plan(&plan).unwrap();
791        let EdgeTaskResult::CoordGen { molecules, ok } = &edge.results[0];
792        assert!(ok);
793        assert_eq!(molecules[1].method, CoordMethod::Greedy);
794        let tags = molecules[1]
795            .molecule
796            .as_ref()
797            .unwrap()
798            .align_debug
799            .as_ref()
800            .expect("greedy should stamp align_debug")
801            .tags
802            .len();
803        assert!(tags >= MIN_MCS_ATOMS as usize, "tags={tags}");
804    }
805
806    #[test]
807    fn atom_map_still_skips_mcs() {
808        let plan = EdgePlan::new_v1(vec![EdgeTask::CoordGen {
809            roots: vec![tmpl(
810                "a",
811                "CCO",
812                None,
813                vec![tmpl(
814                    "b",
815                    "CCO",
816                    Some(AlignOpts {
817                        atom_map: Some(vec![(0, 0), (1, 1), (2, 2)]),
818                        timeout_ms: Some(1),
819                        ..Default::default()
820                    }),
821                    vec![],
822                )],
823            )],
824        }]);
825        let edge = process_edge_plan(&plan).unwrap();
826        let EdgeTaskResult::CoordGen { molecules, ok } = &edge.results[0];
827        assert!(ok);
828        assert_eq!(molecules[1].method, CoordMethod::AtomMap);
829    }
830
831    fn xy(mol: &MoleculeIn, i: i32) -> (f64, f64) {
832        let a = mol.atom(i).expect("atom");
833        (a.x, a.y)
834    }
835
836    #[test]
837    fn cc_star_on_benzene_has_chain_kink() {
838        let mol = free_layout("CC*.c1ccccc1 |m:2:3.4.5.6.7.8|", "s")
839            .unwrap()
840            .molecule;
841        assert_eq!(mol.spokes.len(), 1, "expected one ring-center spoke");
842        let sp = &mol.spokes[0];
843        assert_eq!(sp.atom, 1);
844        let c = mol.centroid_of(&sp.endpts).expect("centroid");
845        let attach = xy(&mol, sp.atom);
846        let methyl = xy(&mol, 0);
847        let turn = crate::spokes::kink_turn(c, attach, methyl);
848        assert!(
849            turn > 0.7 && turn < 1.5,
850            "CC* should zigzag at CH2, not sit collinear; turn={turn:.3} rad"
851        );
852        let dummy = mol.atom(sp.dummy.expect("dummy")).unwrap();
853        assert_eq!(dummy.label.as_deref(), Some(""));
854        let disk = 0.25 * crate::metrics::BOND_PX;
855        for &e in &sp.endpts {
856            let (x, y) = xy(&mol, e);
857            let d = crate::spokes::point_segment_dist(x, y, c.0, c.1, attach.0, attach.1);
858            assert!(
859                d + 1e-6 >= disk,
860                "stem crosses ring atom {e}: d={d:.2} disk={disk:.2}"
861            );
862        }
863        let ring: Vec<(i32, f64, f64)> = sp
864            .endpts
865            .iter()
866            .map(|&i| {
867                let (x, y) = xy(&mol, i);
868                (i, x, y)
869            })
870            .collect();
871        let bonds: Vec<(i32, i32)> = mol.bonds.iter().map(|b| (b.begin, b.end)).collect();
872        let bis = crate::spokes::bisector_angles(c, &ring, &bonds);
873        let stem_ang = (attach.1 - c.1).atan2(attach.0 - c.0);
874        let best = bis
875            .iter()
876            .map(|&b| crate::spokes::ang_diff(stem_ang, b))
877            .fold(f64::INFINITY, f64::min);
878        assert!(
879            best < 0.4,
880            "stem should follow a ring-bond bisector, min Δθ={best:.3}"
881        );
882    }
883
884    fn min_dist_to_ring(mol: &MoleculeIn, attach: (f64, f64), endpts: &[i32]) -> f64 {
885        let set: HashMap<i32, (f64, f64)> = endpts
886            .iter()
887            .filter_map(|&i| mol.atom(i).map(|a| (i, (a.x, a.y))))
888            .collect();
889        let mut best = f64::INFINITY;
890        for b in &mol.bonds {
891            let Some(&pa) = set.get(&b.begin) else {
892                continue;
893            };
894            let Some(&pb) = set.get(&b.end) else {
895                continue;
896            };
897            best = best.min(crate::spokes::point_segment_dist(
898                attach.0, attach.1, pa.0, pa.1, pb.0, pb.1,
899            ));
900        }
901        best
902    }
903
904    fn aromatic_radii(scene: &crate::scene::Scene) -> Vec<f64> {
905        scene
906            .viewports
907            .iter()
908            .flat_map(|v| v.layers.iter())
909            .flat_map(|l| l.primitives.iter())
910            .filter_map(|p| match p {
911                crate::scene::Primitive::Circle { r, class, .. }
912                    if class.as_deref().is_some_and(|c| c.contains("aromatic")) =>
913                {
914                    Some(*r)
915                }
916                _ => None,
917            })
918            .collect()
919    }
920
921    #[test]
922    fn o_star_sits_one_bond_outside_ring_and_keeps_aromatic_circle() {
923        let source = "O*.c1ccccc1 |m:1:2.3.4.5.6.7|";
924        let mol = free_layout(source, "s").unwrap().molecule;
925        assert_eq!(mol.spokes.len(), 1);
926        let sp = &mol.spokes[0];
927        let c = mol.centroid_of(&sp.endpts).expect("centroid");
928        let attach = xy(&mol, sp.atom);
929        let ring: Vec<(i32, f64, f64)> = sp
930            .endpts
931            .iter()
932            .map(|&i| {
933                let (x, y) = xy(&mol, i);
934                (i, x, y)
935            })
936            .collect();
937        let bonds: Vec<(i32, i32)> = mol.bonds.iter().map(|b| (b.begin, b.end)).collect();
938        let ang = (attach.1 - c.1).atan2(attach.0 - c.0);
939        let exit = crate::spokes::ring_exit_along_ray(c, ang, &ring, &bonds);
940        let from_c = (attach.0 - c.0).hypot(attach.1 - c.1);
941        let from_ring = min_dist_to_ring(&mol, attach, &sp.endpts);
942        let bond = crate::metrics::BOND_PX;
943        assert!(
944            from_c > 1.4 * bond,
945            "O must sit past the ring, not on it: from_c={from_c:.1} exit={exit:.1}"
946        );
947        assert!(
948            (from_c - (exit + bond)).abs() < 0.35 * bond,
949            "stem should be ring-exit + 1 bond: from_c={from_c:.1} want={:.1}",
950            exit + bond
951        );
952        assert!(
953            from_ring > 0.7 * bond && from_ring < 1.4 * bond,
954            "O should be ~1 bond off the ring, got {from_ring:.1} (bond={bond:.1})"
955        );
956        let dummy = xy(&mol, sp.dummy.expect("dummy"));
957        let dummy_from_c = (dummy.0 - c.0).hypot(dummy.1 - c.1);
958        assert!(
959            dummy_from_c < 0.2 * bond,
960            "stem dummy must sit at the centroid, d={dummy_from_c:.1}"
961        );
962
963        let spec: crate::doc::DepictSpec = serde_json::from_value(serde_json::json!({
964            "type": "mol",
965            "smiles": source,
966        }))
967        .unwrap();
968        let painted = crate::doc::depict(&spec).unwrap();
969        let rs = aromatic_radii(&painted[0].scene);
970        assert!(
971            rs.iter().any(|&r| r > 0.25 * bond),
972            "aromatic circle vanished (radii={rs:?})"
973        );
974    }
975
976    #[test]
977    fn cl_star_on_ethylbenzene_stems_from_the_ring() {
978        let mol = free_layout("Cl*.c1ccc(CC)cc1 |m:1:2.3.4.5.6.7|", "s")
979            .unwrap()
980            .molecule;
981        assert_eq!(mol.spokes.len(), 1);
982        let sp = &mol.spokes[0];
983        assert_eq!(sp.atom, 0, "Cl is the substituent, not the dummy");
984        let mut endpts = sp.endpts.clone();
985        endpts.sort_unstable();
986        assert_eq!(endpts, vec![2, 3, 4, 5, 8, 9]);
987        let c = mol.centroid_of(&sp.endpts).expect("centroid");
988        let dummy = xy(&mol, sp.dummy.expect("dummy"));
989        let attach = xy(&mol, sp.atom);
990        let bond = crate::metrics::BOND_PX;
991        let dummy_from_c = (dummy.0 - c.0).hypot(dummy.1 - c.1);
992        assert!(
993            dummy_from_c < 0.2 * bond,
994            "dummy must sit at the ring centroid, d={dummy_from_c:.1}"
995        );
996        let from_ring = min_dist_to_ring(&mol, attach, &sp.endpts);
997        assert!(
998            from_ring > 0.7 * bond && from_ring < 1.4 * bond,
999            "Cl should be ~1 bond off the ring, got {from_ring:.1}"
1000        );
1001        let ethyl = xy(&mol, 6);
1002        let d_ethyl =
1003            crate::spokes::point_segment_dist(ethyl.0, ethyl.1, c.0, c.1, attach.0, attach.1);
1004        assert!(
1005            d_ethyl > 0.25 * bond,
1006            "stem must miss the ethyl, d={d_ethyl:.1}"
1007        );
1008    }
1009
1010    #[test]
1011    fn star_cc_on_ethylbenzene_has_kink_at_first_carbon() {
1012        let mol = free_layout("c1ccccc1CC.*CC |m:8:0.1.2.3.4.5|", "s")
1013            .unwrap()
1014            .molecule;
1015        assert_eq!(mol.spokes.len(), 1);
1016        let sp = &mol.spokes[0];
1017        assert_eq!(sp.atom, 9);
1018        let c = mol.centroid_of(&sp.endpts).expect("centroid");
1019        let attach = xy(&mol, 9);
1020        let methyl = xy(&mol, 10);
1021        let turn = crate::spokes::kink_turn(c, attach, methyl);
1022        assert!(
1023            turn > 0.7 && turn < 1.5,
1024            "*CC must kink at the first carbon, turn={turn:.3} rad"
1025        );
1026        let dummy = xy(&mol, sp.dummy.expect("dummy"));
1027        let bond = crate::metrics::BOND_PX;
1028        assert!((dummy.0 - c.0).hypot(dummy.1 - c.1) < 0.2 * bond);
1029    }
1030
1031    #[test]
1032    fn two_cc_star_spokes_take_different_slots() {
1033        let mol = free_layout("CC*.CC*.c1ccccc1 |m:2:6.7.8.9.10.11,5:6.7.8.9.10.11|", "s")
1034            .unwrap()
1035            .molecule;
1036        assert_eq!(mol.spokes.len(), 2);
1037        let c = mol.centroid_of(&mol.spokes[0].endpts).unwrap();
1038        let a0 = xy(&mol, mol.spokes[0].atom);
1039        let a1 = xy(&mol, mol.spokes[1].atom);
1040        let t0 = (a0.1 - c.1).atan2(a0.0 - c.0);
1041        let t1 = (a1.1 - c.1).atan2(a1.0 - c.0);
1042        assert!(
1043            crate::spokes::ang_diff(t0, t1) > 0.8,
1044            "two spokes must not share a slot: Δθ={:.3}",
1045            crate::spokes::ang_diff(t0, t1)
1046        );
1047        for sp in &mol.spokes {
1048            let attach = xy(&mol, sp.atom);
1049            let methyl_idx = if sp.atom == 1 { 0 } else { 3 };
1050            let methyl = xy(&mol, methyl_idx);
1051            let turn = crate::spokes::kink_turn(c, attach, methyl);
1052            assert!(
1053                turn > 0.7 && turn < 1.5,
1054                "spoke {} should zigzag at CH2, turn={turn:.3}",
1055                sp.atom
1056            );
1057        }
1058    }
1059}