Skip to main content

xpict_core/
spokes.rs

1//! Ring-center spoke detection and rigid placement (CX ``m:``).
2//!
3//! The SMILES dummy ``*`` is **dropped from the spoke graph** so it is not an
4//! extra CoordGen vertex. The first real bond is placed at a 120° chain angle
5//! to the stem (ethyl zigzag), not collinear with the centroid. A silent dummy
6//! sits at the centroid; the painted stem runs from there to the substituent
7//! (one bond past the ring).
8
9use std::collections::{HashMap, HashSet, VecDeque};
10
11use crate::cxsmiles::Multicenter;
12use crate::rings::{find_relevant_rings_from_adj, Ring};
13
14/// One ring-center substituent after dropping the dummy from the spoke graph.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct SpokeComp {
17    pub dummy: i32,
18    /// First real atom of the substituent (was bonded to ``*``).
19    pub atom: i32,
20    /// Substituent atoms including [`Self::atom`], excluding the dummy.
21    pub atoms: Vec<i32>,
22    pub endpts: Vec<i32>,
23}
24
25/// Detect CX ``m:`` groups whose endpoints lie on a ring (fusion allowed).
26pub fn detect_ring_spokes(
27    n: usize,
28    bonds: &[(i32, i32)],
29    groups: &[Multicenter],
30) -> Vec<SpokeComp> {
31    if n == 0 || groups.is_empty() {
32        return Vec::new();
33    }
34    let adj = adjacency(n, bonds);
35    let mut out = Vec::new();
36    let mut taken: HashSet<i32> = HashSet::new();
37    for g in groups {
38        let dummy = g.dummy;
39        if dummy < 0 || dummy as usize >= n {
40            continue;
41        }
42        if g.endpts.len() < 3 {
43            continue;
44        }
45        if g.endpts
46            .iter()
47            .any(|&a| a < 0 || a as usize >= n || a == dummy)
48        {
49            continue;
50        }
51        let Some(endpts) = resolve_ring_endpts(&adj, bonds, dummy, &g.endpts) else {
52            continue;
53        };
54        let blocked: HashSet<i32> = endpts.iter().copied().collect();
55        let mut spoke = bfs_component(&adj, dummy, &blocked);
56        spoke.sort_unstable();
57        spoke.dedup();
58        let attachment = adj
59            .get(dummy as usize)
60            .into_iter()
61            .flatten()
62            .copied()
63            .find(|&nb| nb != dummy && !blocked.contains(&nb));
64        let Some(atom) = attachment else {
65            continue;
66        };
67        let atoms: Vec<i32> = spoke.into_iter().filter(|&a| a != dummy).collect();
68        if atoms.is_empty() || !atoms.contains(&atom) {
69            continue;
70        }
71        if atoms.iter().any(|a| taken.contains(a)) || taken.contains(&dummy) {
72            continue;
73        }
74        for &a in &atoms {
75            taken.insert(a);
76        }
77        taken.insert(dummy);
78        out.push(SpokeComp {
79            dummy,
80            atom,
81            atoms,
82            endpts,
83        });
84    }
85    out
86}
87
88fn adjacency(n: usize, bonds: &[(i32, i32)]) -> Vec<Vec<i32>> {
89    let mut adj = vec![Vec::new(); n];
90    for &(a, b) in bonds {
91        if a < 0 || b < 0 {
92            continue;
93        }
94        let (au, bu) = (a as usize, b as usize);
95        if au >= n || bu >= n || au == bu {
96            continue;
97        }
98        adj[au].push(b);
99        adj[bu].push(a);
100    }
101    adj
102}
103
104/// Map a CX ``m:`` atom list onto the ring the dummy should stem from.
105///
106/// Consecutive SMILES indices often swallow an exocyclic substituent
107/// (``c1ccc(CC)cc1`` with ``m:…:2.3.4.5.6.7`` includes the ethyl). Drop
108/// acyclic listed atoms and, when the rest all sit on one Relevant Ring,
109/// expand to that full ring. Fused lists that already span more than one
110/// ring stay a connected cyclic system.
111fn resolve_ring_endpts(
112    adj: &[Vec<i32>],
113    bonds: &[(i32, i32)],
114    dummy: i32,
115    listed: &[i32],
116) -> Option<Vec<i32>> {
117    if listed.len() < 3 {
118        return None;
119    }
120    let rings = rings_without_dummy(adj, bonds, dummy);
121    if rings.is_empty() {
122        return None;
123    }
124    let cyclic_listed: Vec<i32> = listed
125        .iter()
126        .copied()
127        .filter(|a| rings.iter().any(|r| r.atoms.contains(a)))
128        .collect();
129    if cyclic_listed.len() >= 3 {
130        if let Some(ring) = rings
131            .iter()
132            .filter(|r| cyclic_listed.iter().all(|a| r.atoms.contains(a)))
133            .min_by_key(|r| r.size())
134        {
135            if ring.size() >= 3 {
136                return Some(ring.atoms.clone());
137            }
138        }
139        if endpts_fit_rings(adj, &cyclic_listed, &rings) {
140            return Some(cyclic_listed);
141        }
142    }
143    if endpts_fit_rings(adj, listed, &rings) {
144        return Some(listed.to_vec());
145    }
146    None
147}
148
149fn induced_connected(adj: &[Vec<i32>], endpts: &[i32]) -> bool {
150    let set: HashSet<i32> = endpts.iter().copied().collect();
151    let start = endpts[0];
152    let mut seen = HashSet::new();
153    let mut q = VecDeque::new();
154    q.push_back(start);
155    seen.insert(start);
156    while let Some(cur) = q.pop_front() {
157        let Some(nbs) = adj.get(cur as usize) else {
158            continue;
159        };
160        for &nb in nbs {
161            if !set.contains(&nb) || !seen.insert(nb) {
162                continue;
163            }
164            q.push_back(nb);
165        }
166    }
167    seen.len() == set.len()
168}
169
170fn rings_without_dummy(adj: &[Vec<i32>], bonds: &[(i32, i32)], dummy: i32) -> Vec<Ring> {
171    let map = adj_map_without_dummy(adj, dummy);
172    let rest_bonds = bonds
173        .iter()
174        .copied()
175        .filter(|&(a, b)| a != dummy && b != dummy);
176    find_relevant_rings_from_adj(&map, rest_bonds, 32)
177}
178
179/// Endpoints are a ring (or fused/bridged ring system) given precomputed rings.
180///
181/// Fusion / bridgehead atoms have degree >2 in the induced subgraph, so we
182/// do **not** require 2-regular cycles. Each endpoint must be cyclic, and
183/// the induced subgraph must be connected.
184fn endpts_fit_rings(adj: &[Vec<i32>], endpts: &[i32], rings: &[Ring]) -> bool {
185    if endpts.len() < 3 {
186        return false;
187    }
188    let set: HashSet<i32> = endpts.iter().copied().collect();
189    if set.len() != endpts.len() {
190        return false;
191    }
192    if rings.is_empty() || !induced_connected(adj, endpts) {
193        return false;
194    }
195    if rings
196        .iter()
197        .any(|r| endpts.iter().all(|a| r.atoms.contains(a)))
198    {
199        return true;
200    }
201    endpts
202        .iter()
203        .all(|&a| rings.iter().any(|r| r.atoms.contains(&a)))
204}
205
206fn adj_map_without_dummy(adj: &[Vec<i32>], dummy: i32) -> HashMap<i32, Vec<i32>> {
207    adj.iter()
208        .enumerate()
209        .filter(|(i, _)| *i as i32 != dummy)
210        .map(|(i, nbs)| {
211            let filtered: Vec<i32> = nbs.iter().copied().filter(|&n| n != dummy).collect();
212            (i as i32, filtered)
213        })
214        .collect()
215}
216
217fn bfs_component(adj: &[Vec<i32>], start: i32, blocked: &HashSet<i32>) -> Vec<i32> {
218    let mut seen = HashSet::new();
219    let mut q = VecDeque::new();
220    q.push_back(start);
221    seen.insert(start);
222    while let Some(cur) = q.pop_front() {
223        let Some(nbs) = adj.get(cur as usize) else {
224            continue;
225        };
226        for &nb in nbs {
227            if blocked.contains(&nb) || !seen.insert(nb) {
228                continue;
229            }
230            q.push_back(nb);
231        }
232    }
233    seen.into_iter().collect()
234}
235
236/// First substituent neighbor of ``attach`` in ``spoke_atoms`` (not dummy).
237pub fn first_spoke_neighbor(
238    bonds: &[(i32, i32)],
239    attach: i32,
240    spoke: &[i32],
241    dummy: i32,
242) -> Option<i32> {
243    let set: HashSet<i32> = spoke.iter().copied().collect();
244    for &(a, b) in bonds {
245        let other = if a == attach {
246            b
247        } else if b == attach {
248            a
249        } else {
250            continue;
251        };
252        if other != dummy && set.contains(&other) {
253            return Some(other);
254        }
255    }
256    None
257}
258
259/// Outward angles of ring-bond perpendicular bisectors (centroid → midpoint).
260pub fn bisector_angles(
261    centroid: (f64, f64),
262    ring_xy: &[(i32, f64, f64)],
263    bonds: &[(i32, i32)],
264) -> Vec<f64> {
265    let mut out = Vec::new();
266    for (a, b) in ring_bond_ends(ring_xy, bonds) {
267        let mx = 0.5 * (a.0 + b.0);
268        let my = 0.5 * (a.1 + b.1);
269        let dx = mx - centroid.0;
270        let dy = my - centroid.1;
271        if dx.hypot(dy) < 1e-9 {
272            continue;
273        }
274        out.push(dy.atan2(dx));
275    }
276    out.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
277    out.dedup_by(|a, b| ang_diff(*a, *b) < 1e-6);
278    out
279}
280
281pub fn ang_diff(a: f64, b: f64) -> f64 {
282    let mut d = (a - b).rem_euclid(std::f64::consts::TAU);
283    if d > std::f64::consts::PI {
284        d = std::f64::consts::TAU - d;
285    }
286    d
287}
288
289/// Distance from the ring centroid along ``angle`` to the ring perimeter.
290///
291/// Hits the first ring-bond segment the ray meets (a bond-gap exit). Falls
292/// back to inradius if the ray misses every segment.
293pub fn ring_exit_along_ray(
294    centroid: (f64, f64),
295    angle: f64,
296    ring_xy: &[(i32, f64, f64)],
297    bonds: &[(i32, i32)],
298) -> f64 {
299    let u = (angle.cos(), angle.sin());
300    let segs: Vec<((f64, f64), (f64, f64))> = ring_bond_ends(ring_xy, bonds).collect();
301    let mut hit = f64::INFINITY;
302    for &(pa, pb) in &segs {
303        if let Some(t) = ray_segment_t(centroid, u, pa, pb) {
304            if t > 1e-6 {
305                hit = hit.min(t);
306            }
307        }
308    }
309    if hit.is_finite() {
310        return hit;
311    }
312    let mut inr = f64::INFINITY;
313    for &((x1, y1), (x2, y2)) in &segs {
314        let dx = x2 - x1;
315        let dy = y2 - y1;
316        let len = dx.hypot(dy).max(1e-9);
317        let d = ((centroid.0 - x1) * dy - (centroid.1 - y1) * dx).abs() / len;
318        inr = inr.min(d);
319    }
320    if inr.is_finite() {
321        inr
322    } else {
323        ring_xy
324            .iter()
325            .map(|&(_, x, y)| (x - centroid.0).hypot(y - centroid.1))
326            .sum::<f64>()
327            / ring_xy.len().max(1) as f64
328    }
329}
330
331fn ring_bond_ends<'a>(
332    ring_xy: &'a [(i32, f64, f64)],
333    bonds: &'a [(i32, i32)],
334) -> impl Iterator<Item = ((f64, f64), (f64, f64))> + 'a {
335    let set: HashSet<i32> = ring_xy.iter().map(|&(i, _, _)| i).collect();
336    let xy: HashMap<i32, (f64, f64)> = ring_xy.iter().map(|&(i, x, y)| (i, (x, y))).collect();
337    bonds.iter().filter_map(move |&(a, b)| {
338        if !set.contains(&a) || !set.contains(&b) {
339            return None;
340        }
341        Some((*xy.get(&a)?, *xy.get(&b)?))
342    })
343}
344
345fn ray_segment_t(origin: (f64, f64), dir: (f64, f64), a: (f64, f64), b: (f64, f64)) -> Option<f64> {
346    let vx = b.0 - a.0;
347    let vy = b.1 - a.1;
348    let cross = dir.0 * vy - dir.1 * vx;
349    if cross.abs() < 1e-12 {
350        return None;
351    }
352    let acx = a.0 - origin.0;
353    let acy = a.1 - origin.1;
354    let t = (acx * vy - acy * vx) / cross;
355    let s = (acx * dir.1 - acy * dir.0) / cross;
356    if t > 0.0 && (0.0..=1.0).contains(&s) {
357        Some(t)
358    } else {
359        None
360    }
361}
362
363/// Stem length: ring perimeter along the ray, plus one house bond — not from
364/// the centroid (too close) and not an extra bond past the ring (too far).
365pub fn spoke_stem_len(
366    centroid: (f64, f64),
367    angle: f64,
368    ring_xy: &[(i32, f64, f64)],
369    bonds: &[(i32, i32)],
370    bond_len: f64,
371) -> f64 {
372    ring_exit_along_ray(centroid, angle, ring_xy, bonds) + bond_len.max(0.0)
373}
374
375pub fn point_segment_dist(px: f64, py: f64, x0: f64, y0: f64, x1: f64, y1: f64) -> f64 {
376    let dx = x1 - x0;
377    let dy = y1 - y0;
378    let l2 = dx * dx + dy * dy;
379    if l2 < 1e-18 {
380        return (px - x0).hypot(py - y0);
381    }
382    let t = ((px - x0) * dx + (py - y0) * dy) / l2;
383    let t = t.clamp(0.0, 1.0);
384    (px - (x0 + t * dx)).hypot(py - (y0 + t * dy))
385}
386
387/// 120° chain bond at the attachment carbon (turn of π/3 off the stem).
388pub const CHAIN_BOND_OFFSET: f64 = std::f64::consts::PI / 3.0;
389
390/// Rotate/translate ``local`` so ``attach`` sits at ``centroid + L·u(θ)``.
391///
392/// ``neighbor_idx`` is the first real spoke atom. Its bond is placed at
393/// ``angle + bond_offset`` (house chain zigzag is ``±π/3``, not collinear).
394pub fn place_spoke(
395    local: &[(f64, f64)],
396    attach_idx: usize,
397    neighbor_idx: Option<usize>,
398    centroid: (f64, f64),
399    angle: f64,
400    stem_len: f64,
401    bond_offset: f64,
402) -> Vec<(f64, f64)> {
403    if local.is_empty() || attach_idx >= local.len() {
404        return local.to_vec();
405    }
406    let u = (angle.cos(), angle.sin());
407    let target = (centroid.0 + stem_len * u.0, centroid.1 + stem_len * u.1);
408    let a = local[attach_idx];
409    let (c, s) = if let Some(ni) = neighbor_idx.filter(|&i| i < local.len() && i != attach_idx) {
410        let n = local[ni];
411        let lv = (n.0 - a.0, n.1 - a.1);
412        let local_ang = lv.1.atan2(lv.0);
413        let rot = angle + bond_offset - local_ang;
414        (rot.cos(), rot.sin())
415    } else {
416        (1.0, 0.0)
417    };
418    local
419        .iter()
420        .map(|&(x, y)| {
421            let dx = x - a.0;
422            let dy = y - a.1;
423            (target.0 + c * dx - s * dy, target.1 + s * dx + c * dy)
424        })
425        .collect()
426}
427
428/// Interior direction change at ``b`` along ``a → b → c`` (0 = collinear).
429pub fn kink_turn(a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> f64 {
430    let u = (b.0 - a.0, b.1 - a.1);
431    let v = (c.0 - b.0, c.1 - b.1);
432    let lu = u.0.hypot(u.1);
433    let lv = v.0.hypot(v.1);
434    if lu < 1e-9 || lv < 1e-9 {
435        return 0.0;
436    }
437    let inv = 1.0 / (lu * lv);
438    let dot = (u.0 * v.0 + u.1 * v.1) * inv;
439    let cross = (u.0 * v.1 - u.1 * v.0) * inv;
440    cross.atan2(dot).abs()
441}
442
443const HARD: f64 = 1.0e6;
444
445/// Energy of a stem angle: hard no-cross of ring atoms, soft snap to a bisector.
446pub fn spoke_angle_energy(
447    theta: f64,
448    centroid: (f64, f64),
449    bond_len: f64,
450    ring_xy: &[(i32, f64, f64)],
451    bonds: &[(i32, i32)],
452    disk: f64,
453    bisectors: &[f64],
454    taken: &[f64],
455    obstacles: &[(f64, f64)],
456) -> f64 {
457    let ux = theta.cos();
458    let uy = theta.sin();
459    let stem = spoke_stem_len(centroid, theta, ring_xy, bonds, bond_len);
460    let ax = centroid.0 + stem * ux;
461    let ay = centroid.1 + stem * uy;
462    let mut e = 0.0;
463    let hit = |x: f64, y: f64| {
464        let d = point_segment_dist(x, y, centroid.0, centroid.1, ax, ay);
465        if d < disk {
466            let g = disk - d;
467            HARD * g * g
468        } else {
469            0.0
470        }
471    };
472    for &(_, x, y) in ring_xy {
473        e += hit(x, y);
474    }
475    for &(x, y) in obstacles {
476        e += hit(x, y);
477    }
478    if let Some(best) = bisectors
479        .iter()
480        .map(|&b| ang_diff(theta, b))
481        .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
482    {
483        e += 8.0 * best * best;
484    }
485    for &t in taken {
486        let gap = ang_diff(theta, t);
487        let min_gap = std::f64::consts::PI / 3.0;
488        if gap < min_gap {
489            let g = min_gap - gap;
490            e += 40.0 * g * g;
491        }
492    }
493    e
494}
495
496/// Greedy bisector slot, then 1-D refine (rigid rotation around the centroid).
497pub fn greedy_spoke_angle(
498    centroid: (f64, f64),
499    bond_len: f64,
500    ring_xy: &[(i32, f64, f64)],
501    bonds: &[(i32, i32)],
502    disk: f64,
503    bisectors: &[f64],
504    taken: &[f64],
505    obstacles: &[(f64, f64)],
506) -> f64 {
507    let energy = |th: f64| {
508        spoke_angle_energy(
509            th, centroid, bond_len, ring_xy, bonds, disk, bisectors, taken, obstacles,
510        )
511    };
512    let mut best_th = bisectors.first().copied().unwrap_or(0.0);
513    let mut best_e = f64::INFINITY;
514    let candidates: Vec<f64> = if bisectors.is_empty() {
515        (0..12)
516            .map(|i| i as f64 * std::f64::consts::TAU / 12.0)
517            .collect()
518    } else {
519        bisectors.to_vec()
520    };
521    for &th in &candidates {
522        let e = energy(th);
523        if e < best_e {
524            best_e = e;
525            best_th = th;
526        }
527    }
528    let window = if bisectors.len() >= 2 {
529        std::f64::consts::PI / bisectors.len() as f64
530    } else {
531        std::f64::consts::PI / 6.0
532    };
533    let steps = 21;
534    for i in 0..steps {
535        let t = i as f64 / (steps - 1) as f64;
536        let th = best_th - window + 2.0 * window * t;
537        let e = energy(th);
538        if e < best_e {
539            best_e = e;
540            best_th = th;
541        }
542    }
543    best_th
544}
545
546#[cfg(test)]
547mod tests {
548    use super::*;
549    use crate::cxsmiles::{cx_multicenters, Multicenter};
550    use std::collections::HashSet;
551
552    #[test]
553    fn detects_cc_star_on_benzene() {
554        // C0-C1-*2  .  c3..c8
555        let bonds = [
556            (0, 1),
557            (1, 2),
558            (3, 4),
559            (4, 5),
560            (5, 6),
561            (6, 7),
562            (7, 8),
563            (8, 3),
564        ];
565        let g = cx_multicenters("CC*.c1ccccc1 |m:2:3.4.5.6.7.8|");
566        let comps = detect_ring_spokes(9, &bonds, &g);
567        assert_eq!(comps.len(), 1);
568        assert_eq!(comps[0].dummy, 2);
569        assert_eq!(comps[0].atom, 1);
570        let mut atoms = comps[0].atoms.clone();
571        atoms.sort_unstable();
572        assert_eq!(atoms, vec![0, 1]);
573    }
574
575    #[test]
576    fn fused_ring_endpts_allow_degree_gt_two() {
577        // Naphthalene `c1ccc2ccccc2c1` (fusion atoms degree 3) + `CC*`.
578        // Atoms: C0-C1-*2, then 3..12 naphthalene. Fusion 6 and 11.
579        let mut bonds = vec![(0, 1), (1, 2)];
580        bonds.extend([
581            (3, 4),
582            (4, 5),
583            (5, 6),
584            (6, 7),
585            (7, 8),
586            (8, 9),
587            (9, 10),
588            (10, 11),
589            (11, 6),
590            (11, 12),
591            (12, 3),
592        ]);
593        let g = cx_multicenters("CC*.c1ccc2ccccc2c1 |m:2:3.4.5.6.7.8.9.10.11.12|");
594        let comps = detect_ring_spokes(13, &bonds, &g);
595        assert_eq!(
596            comps.len(),
597            1,
598            "fusion atoms are cyclic, not a 2-regular subset"
599        );
600        assert_eq!(comps[0].atom, 1);
601        let set: HashSet<i32> = g[0].endpts.iter().copied().collect();
602        let deg = |a: i32| {
603            bonds
604                .iter()
605                .filter(|&&(x, y)| (x == a && set.contains(&y)) || (y == a && set.contains(&x)))
606                .count()
607        };
608        assert!(
609            deg(6) >= 3 && deg(11) >= 3,
610            "sanity: fusion degree in subset"
611        );
612    }
613
614    #[test]
615    fn chain_endpts_are_not_a_ring_spoke() {
616        let bonds = [(0, 1), (1, 2), (3, 4), (4, 5), (5, 6)];
617        let g = cx_multicenters("CC*.CCCC |m:2:3.4.5.6|");
618        assert!(detect_ring_spokes(7, &bonds, &g).is_empty());
619    }
620
621    #[test]
622    fn ethylbenzene_m_range_drops_ethyl_and_completes_ring() {
623        // Cl0-*1 . c2-c3-c4-c5(C6-C7)-c8-c9
624        // `m:1:2.3.4.5.6.7` is the benzene-style index run and swallows the ethyl.
625        let bonds = [
626            (0, 1),
627            (2, 3),
628            (3, 4),
629            (4, 5),
630            (5, 6),
631            (6, 7),
632            (5, 8),
633            (8, 9),
634            (2, 9),
635        ];
636        let g = cx_multicenters("Cl*.c1ccc(CC)cc1 |m:1:2.3.4.5.6.7|");
637        let comps = detect_ring_spokes(10, &bonds, &g);
638        assert_eq!(comps.len(), 1);
639        assert_eq!(comps[0].dummy, 1);
640        assert_eq!(comps[0].atom, 0);
641        let mut endpts = comps[0].endpts.clone();
642        endpts.sort_unstable();
643        assert_eq!(endpts, vec![2, 3, 4, 5, 8, 9]);
644    }
645
646    #[test]
647    fn hexagon_stem_is_inradius_plus_one_bond() {
648        let r3 = 3.0_f64.sqrt();
649        let ring = [
650            (0, 1.0, 0.0),
651            (1, 0.5, r3 / 2.0),
652            (2, -0.5, r3 / 2.0),
653            (3, -1.0, 0.0),
654            (4, -0.5, -r3 / 2.0),
655            (5, 0.5, -r3 / 2.0),
656        ];
657        let bonds = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)];
658        let ang = std::f64::consts::PI / 6.0;
659        let exit = ring_exit_along_ray((0.0, 0.0), ang, &ring, &bonds);
660        assert!(
661            (exit - r3 / 2.0).abs() < 1e-9,
662            "bisector should hit inradius, exit={exit}"
663        );
664        let stem = spoke_stem_len((0.0, 0.0), ang, &ring, &bonds, 1.0);
665        assert!((stem - (exit + 1.0)).abs() < 1e-9);
666    }
667
668    #[test]
669    fn place_spoke_puts_first_bond_at_chain_angle() {
670        let local = [(0.0, 0.0), (1.5, 0.0)];
671        let placed = place_spoke(
672            &local,
673            0,
674            Some(1),
675            (0.0, 0.0),
676            std::f64::consts::FRAC_PI_2,
677            1.0,
678            CHAIN_BOND_OFFSET,
679        );
680        let attach = placed[0];
681        let next = placed[1];
682        assert!(
683            attach.1 > 0.5,
684            "attachment should sit on +y stem, got {attach:?}"
685        );
686        let turn = kink_turn((0.0, 0.0), attach, next);
687        assert!(
688            (turn - CHAIN_BOND_OFFSET).abs() < 1e-6,
689            "first bond should sit π/3 off the stem, turn={turn:.3}"
690        );
691    }
692
693    #[test]
694    fn two_multicenters_on_same_ring() {
695        let bonds = [
696            (0, 1),
697            (1, 2),
698            (3, 4),
699            (4, 5),
700            (6, 7),
701            (7, 8),
702            (8, 9),
703            (9, 10),
704            (10, 11),
705            (11, 6),
706        ];
707        let g = cx_multicenters("CC*.CC*.c1ccccc1 |m:2:6.7.8.9.10.11,5:6.7.8.9.10.11|");
708        let comps = detect_ring_spokes(12, &bonds, &g);
709        assert_eq!(comps.len(), 2);
710        assert_eq!(comps[0].dummy, 2);
711        assert_eq!(comps[1].dummy, 5);
712    }
713
714    #[test]
715    fn detect_rejects_out_of_range_dummy_and_short_endpts() {
716        let bonds = [(0, 1), (1, 2), (2, 0)];
717        let g = [Multicenter {
718            dummy: 9,
719            endpts: vec![0, 1, 2],
720        }];
721        assert!(detect_ring_spokes(3, &bonds, &g).is_empty());
722        let g = [Multicenter {
723            dummy: 0,
724            endpts: vec![1, 2],
725        }];
726        assert!(detect_ring_spokes(3, &bonds, &g).is_empty());
727        let g = [Multicenter {
728            dummy: 0,
729            endpts: vec![0, 1, 2],
730        }];
731        assert!(detect_ring_spokes(3, &bonds, &g).is_empty());
732    }
733
734    #[test]
735    fn ring_exit_falls_back_when_ray_misses_and_when_bonds_are_absent() {
736        let ring = [(0, 1.0, 0.0), (1, 0.0, 1.0), (2, -1.0, 0.0)];
737        let miss = ring_exit_along_ray((0.0, 0.0), 0.0, &ring, &[]);
738        assert!(miss.is_finite() && miss > 0.0);
739        let parallel = [(0, 1), (1, 2), (2, 0)];
740        let exit = ring_exit_along_ray((10.0, 10.0), 0.0, &ring, &parallel);
741        assert!(exit.is_finite() && exit > 0.0);
742    }
743
744    #[test]
745    fn greedy_angle_works_without_bisectors() {
746        let ring = [
747            (0, 1.0, 0.0),
748            (1, 0.5, 0.87),
749            (2, -0.5, 0.87),
750            (3, -1.0, 0.0),
751            (4, -0.5, -0.87),
752            (5, 0.5, -0.87),
753        ];
754        let bonds = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)];
755        let th = greedy_spoke_angle((0.0, 0.0), 1.0, &ring, &bonds, 0.3, &[], &[], &[]);
756        assert!(th.is_finite());
757    }
758}