1use std::collections::{HashMap, HashSet, VecDeque};
54#[cfg(not(target_arch = "wasm32"))]
55use std::time::Duration;
56use std::time::Instant;
57
58use crate::rings::find_relevant_rings_from_adj;
59
60pub const ALIGN_HOUSE_TIMEOUT_MS: u64 = 100;
63pub const ALIGN_HOUSE_MAX_STATES: u64 = 50_000;
65const ALIGN_RING_MAX: usize = 40;
67const MAX_RING_SEEDS: usize = 32;
69
70#[derive(Debug, Clone, Default)]
72pub struct SearchLimits {
73 pub deadline: Option<Instant>,
75 pub max_states: Option<u64>,
77 pub greedy_only: bool,
79 pub strict_atoms: bool,
82 pub expand_ring_size: bool,
85}
86
87impl SearchLimits {
88 pub fn unbounded() -> Self {
90 Self::default()
91 }
92
93 pub fn house() -> Self {
95 Self::timed(ALIGN_HOUSE_TIMEOUT_MS)
96 }
97
98 pub fn timed(ms: u64) -> Self {
100 if ms == 0 {
101 return Self::unbounded();
102 }
103 Self {
104 deadline: deadline_from_ms(ms),
105 max_states: Some(ALIGN_HOUSE_MAX_STATES),
106 greedy_only: false,
107 strict_atoms: true,
108 expand_ring_size: true,
109 }
110 }
111
112 pub fn from_timeout_ms(timeout_ms: Option<u32>, greedy_only: bool) -> Self {
114 let mut limits = match timeout_ms {
115 Some(0) => Self::unbounded(),
116 Some(ms) => Self::timed(u64::from(ms)),
117 None => Self::house(),
118 };
119 limits.greedy_only = greedy_only;
120 limits
121 }
122}
123
124fn deadline_from_ms(ms: u64) -> Option<Instant> {
125 #[cfg(target_arch = "wasm32")]
127 {
128 let _ = ms;
129 None
130 }
131 #[cfg(not(target_arch = "wasm32"))]
132 {
133 Some(Instant::now() + Duration::from_millis(ms))
134 }
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum EzStereo {
139 None,
140 Cis,
141 Trans,
142}
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum AtomChirality {
145 None,
146 R,
147 S,
148}
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub struct AtomFeat {
151 pub atomic_number: u8,
152 pub formal_charge: i8,
153 pub radical: u8,
154 pub chirality: AtomChirality,
155}
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub struct BondFeat {
158 pub begin: u16,
159 pub end: u16,
160 pub order: u8,
161 pub aromatic: bool,
162 pub stereo: EzStereo,
163 pub stereo_atom1: Option<u16>,
164 pub stereo_atom2: Option<u16>,
165}
166#[derive(Debug, Clone)]
167pub struct MolGraph {
168 pub atoms: Vec<AtomFeat>,
169 pub bonds: Vec<BondFeat>,
170}
171impl MolGraph {
172 pub fn new(atoms: Vec<AtomFeat>, bonds: Vec<BondFeat>) -> Self {
173 Self { atoms, bonds }
174 }
175 pub fn n_atoms(&self) -> usize {
176 self.atoms.len()
177 }
178 pub fn n_bonds(&self) -> usize {
179 self.bonds.len()
180 }
181 pub fn permute(&self, perm: &[u16]) -> Self {
183 assert_eq!(perm.len(), self.n_atoms());
184 let n = self.n_atoms();
185 let mut atoms = vec![
186 AtomFeat {
187 atomic_number: 0,
188 formal_charge: 0,
189 radical: 0,
190 chirality: AtomChirality::None,
191 };
192 n
193 ];
194 for (old, &new) in perm.iter().enumerate() {
195 atoms[new as usize] = self.atoms[old];
196 }
197 let map_opt = |o: Option<u16>| o.map(|i| perm[i as usize]);
198 let bonds = self
199 .bonds
200 .iter()
201 .map(|b| BondFeat {
202 begin: perm[b.begin as usize],
203 end: perm[b.end as usize],
204 order: b.order,
205 aromatic: b.aromatic,
206 stereo: b.stereo,
207 stereo_atom1: map_opt(b.stereo_atom1),
208 stereo_atom2: map_opt(b.stereo_atom2),
209 })
210 .collect();
211 Self { atoms, bonds }
212 }
213}
214pub const COST_ELEMENT: i32 = 11;
215pub const COST_HETERO: i32 = 2;
218pub const COST_CHARGE_RADICAL: i32 = 2;
219pub const COST_BOND_ORDER: i32 = 3;
220pub const COST_UNMATCHED: i32 = 5;
221pub const COST_RING: i32 = 1;
222pub const COST_RING_SIZE: i32 = 1;
226const NONE: usize = usize::MAX;
227type AtomType = (u8, i8, u8, bool, usize, bool);
228
229#[derive(Debug, Clone)]
230pub struct MappingResult {
231 pub map: HashMap<u16, u16>,
232 pub cost: i32,
233}
234
235#[derive(Debug, Default, Clone)]
236pub struct SearchStats {
237 pub seeds: u64,
238 pub states: u64,
239 pub bound_prunes: u64,
240 pub assignment_bounds: u64,
241 pub symmetry_alternatives_removed: u64,
242 pub timed_out: bool,
244}
245
246struct Graph<'a> {
247 mol: &'a MolGraph,
248 n: usize,
249 edge: Vec<usize>,
251 adj: Vec<Vec<(usize, usize)>>,
252 ring: Vec<bool>,
253 ring_bits: Vec<u64>,
255 stereo_bonds: Vec<usize>,
256 stereo_designated: Vec<bool>,
257}
258impl<'a> Graph<'a> {
259 fn new(mol: &'a MolGraph) -> Result<Self, String> {
260 let n = mol.n_atoms();
261 if n > u16::MAX as usize {
262 return Err("atom count exceeds u16 indexing".into());
263 }
264 let mut edge = vec![NONE; n * n];
265 let mut adj = vec![Vec::new(); n];
266 let mut stereo_bonds = Vec::new();
267 let mut stereo_designated = vec![false; n];
268 for (i, b) in mol.bonds.iter().enumerate() {
269 let (a, c) = (b.begin as usize, b.end as usize);
270 if a >= n || c >= n || a == c || edge[a * n + c] != NONE {
271 return Err("requires a simple graph with valid distinct bond endpoints".into());
272 }
273 edge[a * n + c] = i;
274 edge[c * n + a] = i;
275 adj[a].push((c, i));
276 adj[c].push((a, i));
277 for s in [b.stereo_atom1, b.stereo_atom2].into_iter().flatten() {
278 if s as usize >= n {
279 return Err("invalid stereo atom index".into());
280 }
281 }
282 if b.stereo != EzStereo::None {
283 stereo_bonds.push(i);
284 for s in [b.stereo_atom1, b.stereo_atom2].into_iter().flatten() {
285 stereo_designated[s as usize] = true;
286 }
287 }
288 }
289 let mut time = 0;
291 let mut tin = vec![NONE; n];
292 let mut low = vec![0; n];
293 let mut parent = vec![NONE; n];
294 let mut parent_edge = vec![NONE; n];
295 let mut next = vec![0; n];
296 let mut bridge = vec![false; mol.n_bonds()];
297 for root in 0..n {
298 if tin[root] != NONE {
299 continue;
300 }
301 tin[root] = time;
302 low[root] = time;
303 time += 1;
304 let mut stack = vec![root];
305 while let Some(&v) = stack.last() {
306 if next[v] < adj[v].len() {
307 let (w, e) = adj[v][next[v]];
308 next[v] += 1;
309 if e == parent_edge[v] {
310 continue;
311 }
312 if tin[w] == NONE {
313 parent[w] = v;
314 parent_edge[w] = e;
315 tin[w] = time;
316 low[w] = time;
317 time += 1;
318 stack.push(w);
319 } else {
320 low[v] = low[v].min(tin[w]);
321 }
322 } else {
323 stack.pop();
324 if parent[v] != NONE {
325 let p = parent[v];
326 bridge[parent_edge[v]] = low[v] > tin[p];
327 low[p] = low[p].min(low[v]);
328 }
329 }
330 }
331 }
332 let mut ring = vec![false; n];
333 for (i, b) in mol.bonds.iter().enumerate() {
334 if !bridge[i] {
335 ring[b.begin as usize] = true;
336 ring[b.end as usize] = true;
337 }
338 }
339 let mut adj_i32: HashMap<i32, Vec<i32>> = (0..n as i32).map(|i| (i, Vec::new())).collect();
340 let mut ring_bonds = Vec::with_capacity(mol.n_bonds());
341 for b in &mol.bonds {
342 let u = i32::from(b.begin);
343 let v = i32::from(b.end);
344 adj_i32.entry(u).or_default().push(v);
345 adj_i32.entry(v).or_default().push(u);
346 ring_bonds.push((u, v));
347 }
348 let mut ring_bits = vec![0u64; n];
349 for cyc in find_relevant_rings_from_adj(&adj_i32, ring_bonds, ALIGN_RING_MAX) {
350 let sz = cyc.size();
351 if sz >= 64 {
352 continue;
353 }
354 let bit = 1u64 << sz;
355 for &a in &cyc.atoms {
356 ring_bits[a as usize] |= bit;
357 }
358 }
359 Ok(Self {
360 mol,
361 n,
362 edge,
363 adj,
364 ring,
365 ring_bits,
366 stereo_bonds,
367 stereo_designated,
368 })
369 }
370 fn atom_type(&self, a: usize) -> AtomType {
373 let x = &self.mol.atoms[a];
374 let aromatic = self.adj[a].iter().any(|&(_, e)| self.mol.bonds[e].aromatic);
375 (
376 x.atomic_number,
377 x.formal_charge,
378 x.radical,
379 self.ring[a],
380 self.adj[a].len(),
381 aromatic,
382 )
383 }
384 fn bond(&self, a: usize, b: usize) -> usize {
385 self.edge[a * self.n + b]
386 }
387}
388fn ring_size_mismatch(q: &Graph<'_>, r: &Graph<'_>, a: usize, b: usize) -> bool {
392 let qa = q.ring_bits[a];
393 let rb = r.ring_bits[b];
394 qa != 0 && rb != 0 && qa & rb == 0
395}
396
397fn is_n_o_s(z: u8) -> bool {
398 matches!(z, 7 | 8 | 16)
399}
400
401fn ring_hetero_swap(q: &Graph<'_>, r: &Graph<'_>, a: usize, b: usize) -> bool {
403 let za = q.mol.atoms[a].atomic_number;
404 let zb = r.mol.atoms[b].atomic_number;
405 if za == zb || !is_n_o_s(za) || !is_n_o_s(zb) {
406 return false;
407 }
408 let qa = q.ring_bits[a];
409 let rb = r.ring_bits[b];
410 qa != 0 && rb != 0 && qa & rb != 0
411}
412
413fn atom_cost(q: &Graph<'_>, r: &Graph<'_>, a: usize, b: usize) -> i64 {
414 let (x, y) = (&q.mol.atoms[a], &r.mol.atoms[b]);
415 let element = if ring_hetero_swap(q, r, a, b) {
416 i64::from(COST_HETERO)
417 } else {
418 i64::from(COST_ELEMENT) * i64::from(x.atomic_number != y.atomic_number)
419 };
420 element
421 + i64::from(COST_CHARGE_RADICAL)
422 * i64::from(x.formal_charge != y.formal_charge || x.radical != y.radical)
423 + i64::from(COST_RING) * i64::from(q.ring[a] != r.ring[b])
424 + i64::from(COST_RING_SIZE) * i64::from(ring_size_mismatch(q, r, a, b))
425}
426const PAIR_GAIN: i64 = 2 * COST_UNMATCHED as i64;
429fn unmatched_baseline(query: &MolGraph, reference: &MolGraph) -> i64 {
431 i64::from(COST_UNMATCHED)
432 * (query.n_atoms() + query.n_bonds() + reference.n_atoms() + reference.n_bonds()) as i64
433}
434fn bond_gain(a: &BondFeat, b: &BondFeat) -> i64 {
435 PAIR_GAIN
436 - if (a.aromatic && b.aromatic) || a.order == b.order {
437 0
438 } else {
439 i64::from(COST_BOND_ORDER)
440 }
441}
442
443fn stereo_ok(q: &Graph<'_>, r: &Graph<'_>, map: &[usize]) -> bool {
446 for &i in &q.stereo_bonds {
447 let qb = &q.mol.bonds[i];
448 let (a, b) = (map[qb.begin as usize], map[qb.end as usize]);
449 if a == NONE || b == NONE {
450 continue;
451 }
452 let e = r.bond(a, b);
453 if e == NONE {
454 continue;
455 }
456 let rb = &r.mol.bonds[e];
457 if rb.stereo == EzStereo::None {
458 continue;
459 }
460 let (Some(q1), Some(q2), Some(r1), Some(r2)) = (
461 qb.stereo_atom1,
462 qb.stereo_atom2,
463 rb.stereo_atom1,
464 rb.stereo_atom2,
465 ) else {
466 continue;
467 };
468 let wants = if a == rb.begin as usize {
469 [r1, r2]
470 } else {
471 [r2, r1]
472 };
473 for (qa, want) in [q1, q2].into_iter().zip(wants) {
474 let got = map[qa as usize];
475 if got == NONE {
476 continue;
477 }
478 if qb.stereo != rb.stereo {
479 if got != a && got != b && (r.bond(got, a) != NONE || r.bond(got, b) != NONE) {
480 return false;
481 }
482 } else if got != want as usize && r.stereo_designated[got] {
483 return false;
484 }
485 }
486 }
487 true
488}
489
490type Perm = Vec<usize>;
492fn compose(a: &[usize], b: &[usize]) -> Perm {
493 b.iter().map(|&v| a[v]).collect()
494}
495fn inverse(p: &[usize]) -> Perm {
496 let mut inv = vec![0; p.len()];
497 for (i, &v) in p.iter().enumerate() {
498 inv[v] = i;
499 }
500 inv
501}
502#[derive(Clone)]
503struct Group {
504 n: usize,
505 generators: Vec<Perm>,
506}
507impl Group {
508 fn new(n: usize, generators: Vec<Perm>) -> Self {
509 let mut seen = HashSet::new();
510 let generators = generators
511 .into_iter()
512 .filter(|p| p.iter().enumerate().any(|(i, &v)| i != v) && seen.insert(p.clone()))
513 .collect();
514 Self { n, generators }
515 }
516 fn orbit(&self, root: usize) -> Vec<usize> {
517 let mut seen = vec![false; self.n];
518 seen[root] = true;
519 let mut orbit = vec![root];
520 let mut i = 0;
521 while i < orbit.len() {
522 let v = orbit[i];
523 for p in &self.generators {
524 if !seen[p[v]] {
525 seen[p[v]] = true;
526 orbit.push(p[v]);
527 }
528 }
529 i += 1;
530 }
531 orbit
532 }
533 fn orbit_representative_of(&self) -> Vec<usize> {
535 let mut rep = vec![NONE; self.n];
536 for v in 0..self.n {
537 if rep[v] == NONE {
538 for w in self.orbit(v) {
539 rep[w] = v;
540 }
541 }
542 }
543 rep
544 }
545 fn representatives(&self) -> Vec<usize> {
546 let mut seen = vec![false; self.n];
547 let mut reps = Vec::new();
548 for v in 0..self.n {
549 if !seen[v] {
550 reps.push(v);
551 for w in self.orbit(v) {
552 seen[w] = true;
553 }
554 }
555 }
556 reps
557 }
558 fn stabilizer(&self, root: usize) -> Self {
562 if self.generators.iter().all(|g| g[root] == root) {
563 return self.clone();
564 }
565 let mut transversal: Vec<Option<Perm>> = vec![None; self.n];
566 transversal[root] = Some((0..self.n).collect());
567 let mut queue = VecDeque::from([root]);
568 let mut orbit = Vec::new();
569 while let Some(x) = queue.pop_front() {
570 orbit.push(x);
571 for g in &self.generators {
572 let y = g[x];
573 if transversal[y].is_none() {
574 transversal[y] = Some(compose(g, transversal[x].as_ref().unwrap()));
575 queue.push_back(y);
576 }
577 }
578 }
579 let inverses: Vec<_> = transversal
580 .iter()
581 .map(|t| t.as_ref().map(|p| inverse(p)))
582 .collect();
583 let mut gens = Vec::new();
584 for x in orbit {
585 for g in &self.generators {
586 let p = compose(
587 inverses[g[x]].as_ref().unwrap(),
588 &compose(g, transversal[x].as_ref().unwrap()),
589 );
590 gens.push(p);
591 }
592 }
593 Self::new(self.n, gens)
594 }
595}
596fn reference_group(r: &Graph<'_>, generators: &[Vec<u16>]) -> Result<Group, String> {
597 let mut perms = Vec::new();
598 for g in generators {
599 if g.len() != r.n {
600 return Err("generator must permute reference atoms only".into());
601 }
602 let p: Perm = g.iter().map(|&v| v as usize).collect();
603 let mut seen = vec![false; r.n];
604 for (a, &b) in p.iter().enumerate() {
605 if b >= r.n || seen[b] {
606 return Err("generator is not a permutation".into());
607 }
608 seen[b] = true;
609 let (x, y) = (&r.mol.atoms[a], &r.mol.atoms[b]);
610 if (x.atomic_number, x.formal_charge, x.radical)
611 != (y.atomic_number, y.formal_charge, y.radical)
612 {
613 return Err("generator changes atom scoring features".into());
614 }
615 }
616 for b in &r.mol.bonds {
617 let e = r.bond(p[b.begin as usize], p[b.end as usize]);
618 if e == NONE {
619 return Err("generator changes connectivity".into());
620 }
621 let c = &r.mol.bonds[e];
622 if (b.order, b.aromatic) != (c.order, c.aromatic) {
623 return Err("generator changes bond scoring features".into());
624 }
625 }
626 perms.push(p);
627 }
628 let mut group = Group::new(r.n, perms);
629 let mut fixed = vec![false; r.n];
630 for &e in &r.stereo_bonds {
631 let b = &r.mol.bonds[e];
632 for v in [Some(b.begin), Some(b.end), b.stereo_atom1, b.stereo_atom2]
633 .into_iter()
634 .flatten()
635 {
636 fixed[v as usize] = true;
637 }
638 }
639 for (v, fix) in fixed.into_iter().enumerate() {
640 if fix {
641 group = group.stabilizer(v);
642 }
643 }
644 Ok(group)
645}
646
647fn assignment_upper(w: &[Vec<i64>]) -> i64 {
651 let n = w.len();
652 if n == 0 {
653 return 0;
654 }
655 let real = w[0].len();
656 let m = real + n;
657 let mut u = vec![0i64; n + 1];
658 let mut v = vec![0i64; m + 1];
659 let mut p = vec![0usize; m + 1];
660 let mut way = vec![0usize; m + 1];
661 for i in 1..=n {
662 p[0] = i;
663 let mut j0 = 0;
664 let mut minv = vec![i64::MAX / 4; m + 1];
665 let mut used = vec![false; m + 1];
666 loop {
667 used[j0] = true;
668 let i0 = p[j0];
669 let (mut delta, mut j1) = (i64::MAX / 4, 0);
670 for j in 1..=m {
671 if used[j] {
672 continue;
673 }
674 let cost = if j <= real { -w[i0 - 1][j - 1] } else { 0 };
675 let cur = cost - u[i0] - v[j];
676 if cur < minv[j] {
677 minv[j] = cur;
678 way[j] = j0;
679 }
680 if minv[j] < delta {
681 delta = minv[j];
682 j1 = j;
683 }
684 }
685 for j in 0..=m {
686 if used[j] {
687 u[p[j]] += delta;
688 v[j] -= delta;
689 } else {
690 minv[j] -= delta;
691 }
692 }
693 j0 = j1;
694 if p[j0] == 0 {
695 break;
696 }
697 }
698 loop {
699 let j1 = way[j0];
700 p[j0] = p[j1];
701 j0 = j1;
702 if j0 == 0 {
703 break;
704 }
705 }
706 }
707 (1..=real)
708 .filter(|&j| p[j] != 0)
709 .map(|j| w[p[j] - 1][j - 1])
710 .sum()
711}
712
713struct Search<'a> {
714 q: Graph<'a>,
715 r: Graph<'a>,
716 atom_gain: Vec<i64>,
717 map: Vec<usize>,
718 inv: Vec<usize>,
719 forbidden: Vec<Vec<u64>>,
721 trail: Vec<(usize, usize)>,
722 rank: Vec<usize>,
723 root_rank: usize,
724 score: i64,
725 best_score: i64,
726 best_map: Vec<usize>,
727 stats: SearchStats,
728 limits: SearchLimits,
729}
730impl Search<'_> {
731 fn budget_exhausted(&mut self) -> bool {
732 if self.stats.timed_out {
733 return true;
734 }
735 if let Some(max) = self.limits.max_states {
736 if self.stats.states >= max {
737 self.stats.timed_out = true;
738 return true;
739 }
740 }
741 if let Some(deadline) = self.limits.deadline {
742 if self.stats.states % 32 == 0 && Instant::now() >= deadline {
743 self.stats.timed_out = true;
744 return true;
745 }
746 }
747 false
748 }
749 fn allowed(&self, a: usize, b: usize) -> bool {
750 self.map[a] == NONE
751 && self.inv[b] == NONE
752 && self.rank[a] >= self.root_rank
753 && self.forbidden[a][b / 64] & (1u64 << (b % 64)) == 0
754 }
755 fn pair_ok(&self, a: usize, b: usize) -> bool {
756 if self.limits.strict_atoms && self.atom_gain[a * self.r.n + b] <= 0 {
757 return false;
758 }
759 if ring_size_mismatch(&self.q, &self.r, a, b) && !self.limits.expand_ring_size {
760 return false;
761 }
762 true
763 }
764 fn seed_ok(&self, a: usize, b: usize) -> bool {
767 if ring_size_mismatch(&self.q, &self.r, a, b) {
768 return false;
769 }
770 self.pair_ok(a, b)
771 }
772 fn forbid(&mut self, a: usize, b: usize) {
773 let bit = 1u64 << (b % 64);
774 if self.forbidden[a][b / 64] & bit == 0 {
775 self.forbidden[a][b / 64] |= bit;
776 self.trail.push((a, b));
777 }
778 }
779 fn rollback(&mut self, mark: usize) {
780 while self.trail.len() > mark {
781 let (a, b) = self.trail.pop().unwrap();
782 self.forbidden[a][b / 64] &= !(1u64 << (b % 64));
783 }
784 }
785 fn delta(&self, a: usize, b: usize) -> (i64, bool) {
786 let mut gain = self.atom_gain[a * self.r.n + b];
787 let mut attached = false;
788 for &(x, e) in &self.q.adj[a] {
789 if self.map[x] != NONE {
790 let f = self.r.bond(b, self.map[x]);
791 if f != NONE {
792 attached = true;
793 gain += bond_gain(&self.q.mol.bonds[e], &self.r.mol.bonds[f]);
794 }
795 }
796 }
797 (gain, attached)
798 }
799 fn update_best(&mut self) {
800 if self.score > self.best_score {
801 self.best_score = self.score;
802 self.best_map.copy_from_slice(&self.map);
803 }
804 }
805 fn can_improve(&mut self) -> bool {
807 let qs: Vec<_> = (0..self.q.n)
808 .filter(|&a| self.map[a] == NONE && self.rank[a] >= self.root_rank)
809 .collect();
810 let rs: Vec<_> = (0..self.r.n).filter(|&b| self.inv[b] == NONE).collect();
811 if qs.is_empty() || rs.is_empty() {
812 return false;
813 }
814 let mut weights = vec![vec![0; rs.len()]; qs.len()];
815 let mut row_bound = 0;
816 for (i, &a) in qs.iter().enumerate() {
817 for (j, &b) in rs.iter().enumerate() {
818 if !self.allowed(a, b) {
819 continue;
820 }
821 let mut w2 = 2 * self.delta(a, b).0;
822 for &(x, e) in &self.q.adj[a] {
823 if self.map[x] != NONE || self.rank[x] < self.root_rank {
824 continue;
825 }
826 let mut best = 0;
827 for &(y, f) in &self.r.adj[b] {
828 if self.allowed(x, y) {
829 best = best.max(bond_gain(&self.q.mol.bonds[e], &self.r.mol.bonds[f]));
830 }
831 }
832 w2 += best;
833 }
834 weights[i][j] = w2.max(0);
837 }
838 row_bound += weights[i].iter().copied().max().unwrap_or(0);
839 }
840 let needed = 2 * (self.best_score - self.score);
841 if row_bound <= needed {
842 return false;
843 }
844 let col_bound: i64 = (0..rs.len())
845 .map(|j| weights.iter().map(|row| row[j]).max().unwrap_or(0))
846 .sum();
847 if col_bound <= needed {
848 return false;
849 }
850 self.stats.assignment_bounds += 1;
851 assignment_upper(&weights) > needed
852 }
853 fn choose_pair(&mut self) -> Option<(usize, usize, i64)> {
854 let mut best: Option<(usize, usize, i64, usize)> = None;
855 for a in 0..self.q.n {
856 if self.map[a] != NONE || self.rank[a] < self.root_rank {
857 continue;
858 }
859 let mut candidates = Vec::new();
860 for b in 0..self.r.n {
861 if !self.allowed(a, b) {
862 continue;
863 }
864 if !self.pair_ok(a, b) {
865 continue;
866 }
867 let (gain, attached) = self.delta(a, b);
868 if !attached {
869 continue;
870 }
871 self.map[a] = b;
872 let valid = stereo_ok(&self.q, &self.r, &self.map);
873 self.map[a] = NONE;
874 if valid {
875 candidates.push((b, gain));
876 }
877 }
878 let count = candidates.len();
879 for (b, gain) in candidates {
880 let replace = match best {
881 None => true,
882 Some((ba, bb, bg, bc)) => {
883 gain > bg
884 || (gain == bg && (count, self.rank[a], b) < (bc, self.rank[ba], bb))
885 }
886 };
887 if replace {
888 best = Some((a, b, gain, count));
889 }
890 }
891 }
892 best.map(|(a, b, gain, _)| (a, b, gain))
893 }
894 fn dfs(&mut self, group: &Group) {
895 self.update_best();
896 let mark = self.trail.len();
897 loop {
900 self.stats.states += 1;
901 if self.budget_exhausted() {
902 break;
903 }
904 if !self.can_improve() {
905 self.stats.bound_prunes += 1;
906 break;
907 }
908 let Some((a, b, gain)) = self.choose_pair() else {
909 break;
910 };
911 let orbit = group.orbit(b);
912 debug_assert!(orbit.iter().all(|&v| self.allowed(a, v)));
913 self.stats.symmetry_alternatives_removed += (orbit.len() - 1) as u64;
914 let child_group = group.stabilizer(b);
915 self.map[a] = b;
916 self.inv[b] = a;
917 self.score += gain;
918 self.dfs(&child_group);
919 self.score -= gain;
920 self.inv[b] = NONE;
921 self.map[a] = NONE;
922 if self.stats.timed_out {
923 break;
924 }
925 for v in orbit {
928 self.forbid(a, v);
929 }
930 }
931 self.rollback(mark);
932 }
933 fn greedy(&mut self) {
934 let mut added = Vec::new();
935 while let Some((a, b, gain)) = self.choose_pair() {
936 self.stats.states += 1;
937 if self.budget_exhausted() {
938 break;
939 }
940 if gain <= 0 {
941 break;
942 } self.map[a] = b;
944 self.inv[b] = a;
945 self.score += gain;
946 added.push((a, b, gain));
947 self.update_best();
948 }
949 for (a, b, gain) in added.into_iter().rev() {
950 self.map[a] = NONE;
951 self.inv[b] = NONE;
952 self.score -= gain;
953 }
954 }
955
956 fn clear_map(&mut self) {
957 self.map.fill(NONE);
958 self.inv.fill(NONE);
959 self.score = 0;
960 self.root_rank = 0;
961 }
962
963 fn apply_pairs(&mut self, pairs: &[(usize, usize)]) -> bool {
964 for (i, &(a, b)) in pairs.iter().enumerate() {
965 if !self.allowed(a, b) {
966 for &(x, y) in &pairs[..i] {
967 self.map[x] = NONE;
968 self.inv[y] = NONE;
969 }
970 self.score = 0;
971 return false;
972 }
973 let (gain, _) = self.delta(a, b);
974 self.map[a] = b;
975 self.inv[b] = a;
976 self.score += gain;
977 if !stereo_ok(&self.q, &self.r, &self.map) {
978 for &(x, y) in &pairs[..=i] {
979 self.map[x] = NONE;
980 self.inv[y] = NONE;
981 }
982 self.score = 0;
983 return false;
984 }
985 }
986 true
987 }
988
989 fn search_from_partial(&mut self, pairs: &[(usize, usize)], group: &Group) {
990 if pairs.is_empty() || self.budget_exhausted() {
991 return;
992 }
993 self.root_rank = 0;
994 if !self.apply_pairs(pairs) {
995 return;
996 }
997 self.stats.seeds += 1;
998 self.update_best();
999 self.greedy();
1000 if !self.limits.greedy_only && !self.stats.timed_out {
1001 let mut g = group.clone();
1002 for &(_, b) in pairs {
1003 g = g.stabilizer(b);
1004 }
1005 self.dfs(&g);
1006 }
1007 self.clear_map();
1008 }
1009}
1010
1011fn relevant_ring_cycles(g: &Graph<'_>, max_size: usize) -> Vec<Vec<usize>> {
1012 if g.n == 0 || g.mol.bonds.is_empty() {
1013 return Vec::new();
1014 }
1015 let mut adj: HashMap<i32, Vec<i32>> = (0..g.n as i32).map(|i| (i, Vec::new())).collect();
1016 let mut bonds = Vec::with_capacity(g.mol.bonds.len());
1017 for b in &g.mol.bonds {
1018 let u = i32::from(b.begin);
1019 let v = i32::from(b.end);
1020 adj.entry(u).or_default().push(v);
1021 adj.entry(v).or_default().push(u);
1022 bonds.push((u, v));
1023 }
1024 find_relevant_rings_from_adj(&adj, bonds, max_size)
1025 .into_iter()
1026 .map(|ring| ring.atoms.into_iter().map(|a| a as usize).collect())
1027 .collect()
1028}
1029
1030fn cyclic_ring_pairs(q_ring: &[usize], r_ring: &[usize]) -> Vec<Vec<(usize, usize)>> {
1031 let n = q_ring.len();
1032 if n == 0 || n != r_ring.len() {
1033 return Vec::new();
1034 }
1035 let mut out = Vec::with_capacity(2 * n);
1036 for k in 0..n {
1037 for flip in [false, true] {
1038 let mut pairs = Vec::with_capacity(n);
1039 for i in 0..n {
1040 let b = if flip {
1041 r_ring[(k + n - i) % n]
1042 } else {
1043 r_ring[(i + k) % n]
1044 };
1045 pairs.push((q_ring[i], b));
1046 }
1047 out.push(pairs);
1048 }
1049 }
1050 out
1051}
1052
1053fn exo_atomic_numbers(g: &Graph<'_>, a: usize, ring: &HashSet<usize>) -> Vec<u8> {
1054 let mut zs: Vec<u8> = g.adj[a]
1055 .iter()
1056 .filter(|(n, _)| !ring.contains(n))
1057 .map(|(n, _)| g.mol.atoms[*n].atomic_number)
1058 .collect();
1059 zs.sort_unstable();
1060 zs
1061}
1062
1063fn ring_map_atom_score(
1066 q: &Graph<'_>,
1067 r: &Graph<'_>,
1068 pairs: &[(usize, usize)],
1069 atom_gain: &[i64],
1070) -> Option<i64> {
1071 let q_ring: HashSet<usize> = pairs.iter().map(|&(a, _)| a).collect();
1072 let r_ring: HashSet<usize> = pairs.iter().map(|&(_, b)| b).collect();
1073 let mut score = 0i64;
1074 for &(a, b) in pairs {
1075 let g = atom_gain[a * r.n + b];
1076 if g <= 0 {
1077 return None;
1078 }
1079 if q.adj[a].len() != r.adj[b].len() {
1080 return None;
1081 }
1082 if q.ring[a] != r.ring[b] {
1083 return None;
1084 }
1085 if exo_atomic_numbers(q, a, &q_ring) != exo_atomic_numbers(r, b, &r_ring) {
1086 return None;
1087 }
1088 score += g;
1089 }
1090 Some(score)
1091}
1092
1093fn pack_nonconflicting(cands: &[(i64, Vec<(usize, usize)>)]) -> Vec<(usize, usize)> {
1094 let mut used_q = HashSet::new();
1095 let mut used_r = HashSet::new();
1096 let mut out = Vec::new();
1097 for (_, pairs) in cands {
1098 if pairs
1099 .iter()
1100 .any(|&(a, b)| used_q.contains(&a) || used_r.contains(&b))
1101 {
1102 continue;
1103 }
1104 for &(a, b) in pairs {
1105 used_q.insert(a);
1106 used_r.insert(b);
1107 out.push((a, b));
1108 }
1109 }
1110 out
1111}
1112
1113fn ring_seed_partials(q: &Graph<'_>, r: &Graph<'_>, atom_gain: &[i64]) -> Vec<Vec<(usize, usize)>> {
1115 let q_rings = relevant_ring_cycles(q, ALIGN_RING_MAX);
1116 let r_rings = relevant_ring_cycles(r, ALIGN_RING_MAX);
1117 if q_rings.is_empty() || r_rings.is_empty() {
1118 return Vec::new();
1119 }
1120 let q_size_n = |sz: usize| q_rings.iter().filter(|ring| ring.len() == sz).count();
1121 let r_size_n = |sz: usize| r_rings.iter().filter(|ring| ring.len() == sz).count();
1122 let unique: HashSet<usize> = q_rings
1123 .iter()
1124 .map(|ring| ring.len())
1125 .filter(|&sz| q_size_n(sz) == 1 && r_size_n(sz) == 1)
1126 .collect();
1127 let max_eq = q_rings
1128 .iter()
1129 .map(|ring| ring.len())
1130 .filter(|&sz| r_size_n(sz) > 0)
1131 .max();
1132 let use_size = |sz: usize| {
1133 if unique.is_empty() {
1134 Some(sz) == max_eq
1135 } else {
1136 unique.contains(&sz)
1137 }
1138 };
1139
1140 let mut scored: Vec<(i64, Vec<(usize, usize)>)> = Vec::new();
1141 let mut seen = HashSet::new();
1142 for qr in &q_rings {
1143 if !use_size(qr.len()) {
1144 continue;
1145 }
1146 for rr in &r_rings {
1147 if rr.len() != qr.len() {
1148 continue;
1149 }
1150 for pairs in cyclic_ring_pairs(qr, rr) {
1151 let Some(score) = ring_map_atom_score(q, r, &pairs, atom_gain) else {
1152 continue;
1153 };
1154 let mut key: Vec<(usize, usize)> = pairs.clone();
1155 key.sort_unstable();
1156 if !seen.insert(key) {
1157 continue;
1158 }
1159 scored.push((score, pairs));
1160 }
1161 }
1162 }
1163 scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.len().cmp(&a.1.len())));
1164
1165 let mut out = Vec::new();
1166 let packed = pack_nonconflicting(&scored);
1167 if packed.len() > scored.first().map(|c| c.1.len()).unwrap_or(0) {
1168 out.push(packed);
1169 }
1170 for (_, pairs) in scored.into_iter().take(MAX_RING_SEEDS) {
1171 out.push(pairs);
1172 if out.len() >= MAX_RING_SEEDS {
1173 break;
1174 }
1175 }
1176 out
1177}
1178
1179pub fn cost_mapping(reference: &MolGraph, query: &MolGraph) -> Option<MappingResult> {
1183 let generators = reference_generators(reference);
1184 cost_mapping_with_generators(reference, query, &generators)
1185 .expect("invalid molecular graph")
1186 .0
1187}
1188
1189thread_local! {
1190 static CANONAUT_GENERATORS: std::cell::RefCell<Vec<Vec<u32>>> =
1191 const { std::cell::RefCell::new(Vec::new()) };
1192}
1193
1194fn collect_generator(_n: u32, perm: &mut [u32], _: &mut [u32], _: u32, _: u32, _: u32) {
1195 CANONAUT_GENERATORS.with(|g| g.borrow_mut().push(perm.to_vec()));
1196}
1197
1198pub fn reference_generators(mol: &MolGraph) -> Vec<Vec<u16>> {
1204 use canonaut::structs::{CanonautManager, DenseGraph};
1205 let (n, m) = (mol.n_atoms(), mol.n_bonds());
1206 if n < 2 {
1207 return Vec::new();
1208 }
1209 let mut g = DenseGraph::new(n + m);
1210 for (i, b) in mol.bonds.iter().enumerate() {
1211 g.add_edge(b.begin as usize, n + i);
1212 g.add_edge(b.end as usize, n + i);
1213 }
1214 let mut keys: Vec<(u8, u8, i8, u8, bool)> = Vec::with_capacity(n + m);
1215 keys.extend(
1216 mol.atoms
1217 .iter()
1218 .map(|a| (0, a.atomic_number, a.formal_charge, a.radical, false)),
1219 );
1220 keys.extend(mol.bonds.iter().map(|b| (1, b.order, 0, 0, b.aromatic)));
1221 let mut palette = keys.clone();
1222 palette.sort_unstable();
1223 palette.dedup();
1224 let colors: Vec<u32> = keys
1225 .iter()
1226 .map(|k| palette.binary_search(k).unwrap_or(0) as u32)
1227 .collect();
1228
1229 CANONAUT_GENERATORS.with(|g| g.borrow_mut().clear());
1230 let mut manager = CanonautManager::new(n + m).with_automorphism_callback(collect_generator);
1231 manager.canonize_graph_with_colors(&g, &colors);
1232 let perms = CANONAUT_GENERATORS.with(|g| std::mem::take(&mut *g.borrow_mut()));
1233 perms
1234 .into_iter()
1235 .filter(|p| p.len() >= n && p[..n].iter().all(|&v| (v as usize) < n))
1236 .map(|p| p[..n].iter().map(|&v| v as u16).collect())
1237 .collect()
1238}
1239
1240pub fn cost_mapping_with_generators(
1245 reference: &MolGraph,
1246 query: &MolGraph,
1247 reference_generators: &[Vec<u16>],
1248) -> Result<(Option<MappingResult>, SearchStats), String> {
1249 cost_mapping_with_generators_limited(
1250 reference,
1251 query,
1252 reference_generators,
1253 &SearchLimits::unbounded(),
1254 )
1255}
1256
1257pub fn cost_mapping_with_generators_limited(
1260 reference: &MolGraph,
1261 query: &MolGraph,
1262 reference_generators: &[Vec<u16>],
1263 limits: &SearchLimits,
1264) -> Result<(Option<MappingResult>, SearchStats), String> {
1265 let q = Graph::new(query)?;
1266 let r = Graph::new(reference)?;
1267 let group = reference_group(&r, reference_generators)?;
1268 if q.n == 0 || r.n == 0 {
1269 return Ok((None, SearchStats::default()));
1270 }
1271 let q_types: Vec<_> = (0..q.n).map(|a| q.atom_type(a)).collect();
1273 let r_types: Vec<_> = (0..r.n).map(|b| r.atom_type(b)).collect();
1274 let mut frequency: HashMap<AtomType, usize> = HashMap::new();
1275 for t in q_types.iter().chain(&r_types) {
1276 *frequency.entry(*t).or_default() += 1;
1277 }
1278 let mut order: Vec<_> = (0..q.n).collect();
1279 order.sort_by_key(|&a| (frequency[&q_types[a]], std::cmp::Reverse(q.adj[a].len()), a));
1280 let mut rank = vec![0; q.n];
1281 for (i, &a) in order.iter().enumerate() {
1282 rank[a] = i;
1283 }
1284 let atom_gain: Vec<_> = (0..q.n)
1285 .flat_map(|a| (0..r.n).map(move |b| (a, b)))
1286 .map(|(a, b)| PAIR_GAIN - atom_cost(&q, &r, a, b))
1287 .collect();
1288 let mut seeds = Vec::new();
1289 let reference_representatives = group.representatives();
1290 for &a in &order {
1291 for &b in &reference_representatives {
1292 seeds.push((a, b));
1293 }
1294 }
1295 let assigned = optimal_assignment(&atom_gain, q.n, r.n);
1300 let orbit_rep = group.orbit_representative_of();
1301 let mut preferred = HashSet::new();
1302 for (a, b) in assigned.into_iter().enumerate() {
1303 if let Some(b) = b {
1304 preferred.insert((a, orbit_rep[b]));
1305 }
1306 }
1307 seeds.sort_by_key(|&(a, b)| {
1308 let lead = preferred.contains(&(a, b));
1309 let same = q_types[a] == r_types[b];
1311 (
1312 !lead,
1313 !same,
1314 if lead { rank[a] } else { 0 },
1315 std::cmp::Reverse(atom_gain[a * r.n + b]),
1316 rank[a],
1317 b,
1318 )
1319 });
1320 let mut s = Search {
1321 map: vec![NONE; q.n],
1322 inv: vec![NONE; r.n],
1323 forbidden: vec![vec![0; (r.n + 63) / 64]; q.n],
1324 trail: Vec::new(),
1325 best_map: vec![NONE; q.n],
1326 atom_gain,
1327 rank,
1328 root_rank: 0,
1329 score: 0,
1330 best_score: i64::MIN / 4,
1331 stats: SearchStats::default(),
1332 limits: limits.clone(),
1333 q,
1334 r,
1335 };
1336 let ring_seeds = ring_seed_partials(&s.q, &s.r, &s.atom_gain);
1337 for pairs in &ring_seeds {
1338 s.search_from_partial(pairs, &group);
1339 if s.budget_exhausted() {
1340 break;
1341 }
1342 if s.best_score == unmatched_baseline(query, reference) {
1343 break;
1344 }
1345 }
1346 for (a, b) in seeds {
1347 if s.budget_exhausted() {
1348 break;
1349 }
1350 if s.best_score == unmatched_baseline(query, reference) {
1351 break;
1352 }
1353 if !s.seed_ok(a, b) {
1354 continue;
1355 }
1356 s.root_rank = s.rank[a];
1359 s.map[a] = b;
1360 s.inv[b] = a;
1361 s.score = s.atom_gain[a * s.r.n + b];
1362 s.stats.seeds += 1;
1363 s.update_best();
1364 s.greedy();
1365 if !s.limits.greedy_only && !s.stats.timed_out {
1366 s.dfs(&group.stabilizer(b));
1367 }
1368 s.map[a] = NONE;
1369 s.inv[b] = NONE;
1370 if s.best_score == unmatched_baseline(query, reference) {
1371 break; }
1373 }
1374 if s.best_score == i64::MIN / 4 {
1375 return Ok((None, s.stats));
1376 }
1377 let baseline = unmatched_baseline(query, reference);
1378 let cost = i32::try_from(baseline - s.best_score).map_err(|_| "cost exceeds i32")?;
1379 let map = s
1380 .best_map
1381 .iter()
1382 .enumerate()
1383 .filter(|(_, b)| **b != NONE)
1384 .map(|(a, &b)| (a as u16, b as u16))
1385 .collect();
1386 Ok((Some(MappingResult { map, cost }), s.stats))
1387}
1388
1389fn optimal_assignment(gain: &[i64], nq: usize, nr: usize) -> Vec<Option<usize>> {
1393 let n = nq.max(nr);
1395 let cost = |i: usize, j: usize| -> i64 {
1396 if i < nq && j < nr {
1397 -gain[i * nr + j].max(0)
1398 } else {
1399 0
1400 }
1401 };
1402 let (mut u, mut v) = (vec![0i64; n + 1], vec![0i64; n + 1]);
1403 let (mut p, mut way) = (vec![0usize; n + 1], vec![0usize; n + 1]);
1404 for i in 1..=n {
1405 p[0] = i;
1406 let mut j0 = 0;
1407 let mut minv = vec![i64::MAX; n + 1];
1408 let mut used = vec![false; n + 1];
1409 loop {
1410 used[j0] = true;
1411 let (i0, mut delta, mut j1) = (p[j0], i64::MAX, 0);
1412 for j in 1..=n {
1413 if !used[j] {
1414 let cur = cost(i0 - 1, j - 1) - u[i0] - v[j];
1415 if cur < minv[j] {
1416 minv[j] = cur;
1417 way[j] = j0;
1418 }
1419 if minv[j] < delta {
1420 delta = minv[j];
1421 j1 = j;
1422 }
1423 }
1424 }
1425 for j in 0..=n {
1426 if used[j] {
1427 u[p[j]] += delta;
1428 v[j] -= delta;
1429 } else {
1430 minv[j] -= delta;
1431 }
1432 }
1433 j0 = j1;
1434 if p[j0] == 0 {
1435 break;
1436 }
1437 }
1438 loop {
1439 let j1 = way[j0];
1440 p[j0] = p[j1];
1441 j0 = j1;
1442 if j0 == 0 {
1443 break;
1444 }
1445 }
1446 }
1447 let mut out = vec![None; nq];
1448 for j in 1..=n {
1449 let (i, b) = (p[j] - 1, j - 1);
1450 if i < nq && b < nr && gain[i * nr + b] > 0 {
1451 out[i] = Some(b);
1452 }
1453 }
1454 out
1455}
1456
1457pub fn mapping_cost(query: &MolGraph, reference: &MolGraph, mapping: &HashMap<u16, u16>) -> i32 {
1461 let q = Graph::new(query).expect("invalid query graph");
1462 let r = Graph::new(reference).expect("invalid reference graph");
1463 let mut used = vec![false; r.n];
1464 let mut score = 0;
1465 for (&a, &b) in mapping {
1466 let (a, b) = (a as usize, b as usize);
1467 assert!(
1468 a < q.n && b < r.n && !used[b],
1469 "invalid/noninjective atom map"
1470 );
1471 used[b] = true;
1472 score += PAIR_GAIN - atom_cost(&q, &r, a, b);
1473 }
1474 for b in &query.bonds {
1475 if let (Some(&x), Some(&y)) = (mapping.get(&b.begin), mapping.get(&b.end)) {
1476 let e = r.bond(x as usize, y as usize);
1477 if e != NONE {
1478 score += bond_gain(b, &reference.bonds[e]);
1479 }
1480 }
1481 }
1482 let baseline = unmatched_baseline(query, reference);
1483 i32::try_from(baseline - score).expect("cost exceeds i32")
1484}
1485
1486pub fn signed_side(ax: f64, ay: f64, bx: f64, by: f64, px: f64, py: f64) -> f64 {
1487 (bx - ax) * (py - ay) - (by - ay) * (px - ax)
1488}
1489pub fn substituents_same_side(
1490 ax: f64,
1491 ay: f64,
1492 bx: f64,
1493 by: f64,
1494 s1x: f64,
1495 s1y: f64,
1496 s2x: f64,
1497 s2y: f64,
1498) -> bool {
1499 let s1 = signed_side(ax, ay, bx, by, s1x, s1y);
1500 let s2 = signed_side(ax, ay, bx, by, s2x, s2y);
1501 s1 * s2 > 0.0
1502}
1503#[cfg(test)]
1504mod tests {
1505 use super::*;
1506 fn c() -> AtomFeat {
1507 AtomFeat {
1508 atomic_number: 6,
1509 formal_charge: 0,
1510 radical: 0,
1511 chirality: AtomChirality::None,
1512 }
1513 }
1514 fn single(a: u16, b: u16) -> BondFeat {
1515 BondFeat {
1516 begin: a,
1517 end: b,
1518 order: 1,
1519 aromatic: false,
1520 stereo: EzStereo::None,
1521 stereo_atom1: None,
1522 stereo_atom2: None,
1523 }
1524 }
1525 fn chain(n: usize) -> MolGraph {
1526 MolGraph::new(
1527 vec![c(); n],
1528 (0..n - 1)
1529 .map(|i| single(i as u16, (i + 1) as u16))
1530 .collect(),
1531 )
1532 }
1533 fn cyclohexane() -> MolGraph {
1534 let mut bonds: Vec<_> = (0..5).map(|i| single(i, i + 1)).collect();
1535 bonds.push(single(0, 5));
1536 MolGraph::new(vec![c(); 6], bonds)
1537 }
1538 fn alkene(cis: bool) -> MolGraph {
1539 MolGraph::new(
1540 vec![c(); 4],
1541 vec![
1542 single(0, 1),
1543 BondFeat {
1544 begin: 1,
1545 end: 2,
1546 order: 2,
1547 aromatic: false,
1548 stereo: if cis { EzStereo::Cis } else { EzStereo::Trans },
1549 stereo_atom1: Some(0),
1550 stereo_atom2: Some(3),
1551 },
1552 single(2, 3),
1553 ],
1554 )
1555 }
1556 fn hetero_alkene(cis: bool) -> MolGraph {
1557 let mut atoms = vec![c(); 4];
1558 atoms[0].atomic_number = 17;
1559 atoms[3].atomic_number = 35;
1560 MolGraph::new(
1561 atoms,
1562 vec![
1563 single(0, 1),
1564 BondFeat {
1565 begin: 1,
1566 end: 2,
1567 order: 2,
1568 aromatic: false,
1569 stereo: if cis { EzStereo::Cis } else { EzStereo::Trans },
1570 stereo_atom1: Some(0),
1571 stereo_atom2: Some(3),
1572 },
1573 single(2, 3),
1574 ],
1575 )
1576 }
1577 fn branched_alkene(cis: bool) -> MolGraph {
1578 MolGraph::new(
1579 vec![c(); 6],
1580 vec![
1581 single(0, 1),
1582 BondFeat {
1583 begin: 1,
1584 end: 2,
1585 order: 2,
1586 aromatic: false,
1587 stereo: if cis { EzStereo::Cis } else { EzStereo::Trans },
1588 stereo_atom1: Some(0),
1589 stereo_atom2: Some(3),
1590 },
1591 single(2, 3),
1592 single(1, 4),
1593 single(2, 5),
1594 ],
1595 )
1596 }
1597 fn chiral(r: bool) -> MolGraph {
1598 let mut atoms = vec![c(); 4];
1599 atoms[2].atomic_number = 8;
1600 atoms[3].atomic_number = 17;
1601 atoms[1].chirality = if r {
1602 AtomChirality::R
1603 } else {
1604 AtomChirality::S
1605 };
1606 MolGraph::new(atoms, vec![single(0, 1), single(1, 2), single(1, 3)])
1607 }
1608 fn all_perms(n: usize) -> Vec<Vec<u16>> {
1609 let mut base: Vec<u16> = (0..n as u16).collect();
1610 let mut out = Vec::new();
1611 fn heap(a: &mut [u16], size: usize, out: &mut Vec<Vec<u16>>) {
1612 if size == 1 {
1613 out.push(a.to_vec());
1614 return;
1615 }
1616 for i in 0..size {
1617 heap(a, size - 1, out);
1618 if size % 2 == 0 {
1619 a.swap(i, size - 1);
1620 } else {
1621 a.swap(0, size - 1);
1622 }
1623 }
1624 }
1625 heap(&mut base, n, &mut out);
1626 out
1627 }
1628 fn butylcyclohexane_ring_first() -> MolGraph {
1630 let mut bonds: Vec<_> = (0..5).map(|i| single(i, i + 1)).collect();
1631 bonds.push(single(0, 5));
1632 bonds.extend((5..9).map(|i| single(i, i + 1)));
1633 MolGraph::new(vec![c(); 10], bonds)
1634 }
1635 fn butylcyclohexane_chain_first() -> MolGraph {
1637 let mut bonds: Vec<_> = (0..9).map(|i| single(i, i + 1)).collect();
1638 bonds.push(single(4, 9));
1639 MolGraph::new(vec![c(); 10], bonds)
1640 }
1641 #[test]
1642 fn hexane_onto_butylcyclohexane_atom_order_invariant() {
1643 let a = cost_mapping(&chain(6), &butylcyclohexane_ring_first()).expect("map");
1644 let b = cost_mapping(&chain(6), &butylcyclohexane_chain_first()).expect("map");
1645 assert_eq!(a.map.len(), 6, "ring-first map={:?}", a.map);
1646 assert_eq!(b.map.len(), 6, "chain-first map={:?}", b.map);
1647 assert_eq!(a.cost, b.cost, "a={a:?} b={b:?}");
1648 let ring_hits = |m: &HashMap<u16, u16>, ring: std::ops::Range<u16>| {
1651 m.keys().filter(|k| ring.contains(k)).count()
1652 };
1653 assert!(ring_hits(&a.map, 0..6) < 6, "ring-first map={:?}", a.map);
1654 assert!(ring_hits(&b.map, 4..10) < 6, "chain-first map={:?}", b.map);
1655 let a = cost_mapping(&butylcyclohexane_ring_first(), &chain(6)).expect("map");
1657 let b = cost_mapping(&butylcyclohexane_chain_first(), &chain(6)).expect("map");
1658 assert_eq!(a.map.len(), 6, "ring-first map={:?}", a.map);
1659 assert_eq!(a.cost, b.cost, "a={a:?} b={b:?}");
1660 assert!(
1661 a.map.values().filter(|v| (0..6).contains(*v)).count() < 6,
1662 "{:?}",
1663 a.map
1664 );
1665 assert!(
1666 b.map.values().filter(|v| (4..10).contains(*v)).count() < 6,
1667 "{:?}",
1668 b.map
1669 );
1670 }
1671 fn lcg_perms(n: usize, count: usize) -> Vec<Vec<u16>> {
1673 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
1674 (0..count)
1675 .map(|_| {
1676 let mut p: Vec<u16> = (0..n as u16).collect();
1677 for i in (1..n).rev() {
1678 state = state
1679 .wrapping_mul(6364136223846793005)
1680 .wrapping_add(1442695040888963407);
1681 p.swap(i, (state >> 33) as usize % (i + 1));
1682 }
1683 p
1684 })
1685 .collect()
1686 }
1687 #[test]
1688 fn cost_mapping_cost_invariant_under_atom_permutation() {
1689 let cases = [
1690 (chain(6), butylcyclohexane_ring_first()),
1691 (butylcyclohexane_ring_first(), chain(6)),
1692 (chain(6), cyclohexane()),
1693 (cyclohexane(), butylcyclohexane_chain_first()),
1694 ];
1695 for (r, q) in cases {
1696 let base = cost_mapping(&r, &q).expect("map").cost;
1697 for pq in lcg_perms(q.n_atoms(), 40) {
1698 for pr in lcg_perms(r.n_atoms(), 3) {
1699 let got = cost_mapping(&r.permute(&pr), &q.permute(&pq))
1700 .expect("map")
1701 .cost;
1702 assert_eq!(got, base, "pq={pq:?} pr={pr:?}");
1703 }
1704 }
1705 }
1706 }
1707 #[test]
1708 fn hexane_maps_all_cyclohexane_atoms() {
1709 let res = cost_mapping(&chain(6), &cyclohexane()).expect("map");
1710 assert_eq!(res.map.len(), 6, "map={:?}", res.map);
1711 assert_eq!(
1713 res.cost,
1714 COST_UNMATCHED + 6 * COST_RING,
1715 "cost={}",
1716 res.cost
1717 );
1718 }
1719 #[test]
1720 fn costly_terminal_element_maps_when_both_sides_pay() {
1721 let mut a = chain(2);
1723 a.atoms[1].atomic_number = 7;
1724 let res = cost_mapping(&chain(2), &a).expect("map");
1725 assert_eq!(res.map.len(), 2);
1726 assert_eq!(res.cost, COST_ELEMENT);
1727 }
1728 fn aromatic(a: u16, b: u16) -> BondFeat {
1729 BondFeat {
1730 begin: a,
1731 end: b,
1732 order: 4,
1733 aromatic: true,
1734 stereo: EzStereo::None,
1735 stereo_atom1: None,
1736 stereo_atom2: None,
1737 }
1738 }
1739 #[test]
1740 fn aromatic_ring_beats_substituent_element_mismatch() {
1741 let mut cresol_atoms = vec![c(); 8];
1743 cresol_atoms[6].atomic_number = 8; let cresol = MolGraph::new(
1746 cresol_atoms,
1747 vec![
1748 aromatic(0, 1),
1749 aromatic(1, 2),
1750 aromatic(2, 3),
1751 aromatic(3, 4),
1752 aromatic(4, 5),
1753 aromatic(5, 0),
1754 single(0, 6),
1755 single(1, 7),
1756 ],
1757 );
1758 let mut anisole_atoms = vec![c(); 8];
1760 anisole_atoms[7].atomic_number = 8;
1761 let anisole = MolGraph::new(
1762 anisole_atoms,
1763 vec![
1764 aromatic(0, 1),
1765 aromatic(1, 2),
1766 aromatic(2, 3),
1767 aromatic(3, 4),
1768 aromatic(4, 5),
1769 aromatic(5, 0),
1770 single(0, 7),
1771 single(7, 6),
1772 ],
1773 );
1774 let res = cost_mapping(&cresol, &anisole).expect("map");
1775 for (&q, &r) in &res.map {
1777 let zq = anisole.atoms[q as usize].atomic_number;
1778 let zr = cresol.atoms[r as usize].atomic_number;
1779 assert_eq!(
1780 zq, zr,
1781 "element mismatch in map q{q}(Z={zq})→r{r}(Z={zr}); map={:?}",
1782 res.map
1783 );
1784 }
1785 let ring_pairs = res.map.iter().filter(|(&q, _)| q < 6).count();
1786 assert!(
1787 ring_pairs >= 6,
1788 "expected full aromatic ring map, got {ring_pairs}; map={:?}",
1789 res.map
1790 );
1791 }
1792 #[test]
1793 fn toluene_anisole_ring_map_is_cheaper_than_shifted_methyl() {
1794 let mut anisole_atoms = vec![c(); 8];
1796 anisole_atoms[1].atomic_number = 8;
1797 let anisole = MolGraph::new(
1798 anisole_atoms,
1799 vec![
1800 single(0, 1),
1801 single(1, 2),
1802 aromatic(2, 3),
1803 aromatic(3, 4),
1804 aromatic(4, 5),
1805 aromatic(5, 6),
1806 aromatic(6, 7),
1807 aromatic(7, 2),
1808 ],
1809 );
1810 let toluene = MolGraph::new(
1811 vec![c(); 7],
1812 vec![
1813 single(0, 1),
1814 aromatic(1, 2),
1815 aromatic(2, 3),
1816 aromatic(3, 4),
1817 aromatic(4, 5),
1818 aromatic(5, 6),
1819 aromatic(6, 1),
1820 ],
1821 );
1822 let good: HashMap<u16, u16> = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]
1824 .into_iter()
1825 .collect();
1826 let bad: HashMap<u16, u16> = [(0, 3), (1, 2), (2, 7), (3, 6), (4, 5), (5, 4)]
1827 .into_iter()
1828 .collect();
1829 let good_c = mapping_cost(&toluene, &anisole, &good);
1830 let bad_c = mapping_cost(&toluene, &anisole, &bad);
1831 assert!(
1832 good_c < bad_c,
1833 "ring+Me↔O map should beat shifted map: good={good_c} bad={bad_c}"
1834 );
1835 let res = cost_mapping(&anisole, &toluene).expect("map");
1836 assert!(
1837 res.cost <= good_c,
1838 "search returned worse than known Me↔O ring map: got {} (map={:?}) vs good {good_c}",
1839 res.cost,
1840 res.map
1841 );
1842 assert_eq!(res.map.get(&0), Some(&1));
1845 assert_eq!(res.cost, COST_ELEMENT + 2 * COST_UNMATCHED);
1847 let ring_pairs = res
1848 .map
1849 .iter()
1850 .filter(|(&q, &r)| q >= 1 && q <= 6 && r >= 2 && r <= 7)
1851 .count();
1852 assert!(
1853 ring_pairs >= 6,
1854 "expected full aromatic ring map, got {ring_pairs}; map={:?}",
1855 res.map
1856 );
1857 }
1858 #[test]
1859 fn ez_self_all_orderings_zero_cost() {
1860 for g in [
1861 alkene(true),
1862 alkene(false),
1863 hetero_alkene(true),
1864 branched_alkene(true),
1865 ] {
1866 for perm in all_perms(g.n_atoms()) {
1867 let gp = g.permute(&perm);
1868 let res = cost_mapping(&g, &gp).expect("map");
1869 assert_eq!(res.cost, 0, "perm={perm:?} map={:?}", res.map);
1870 assert_eq!(res.map.len(), g.n_atoms());
1871 }
1872 }
1873 }
1874 #[test]
1875 fn ez_cis_vs_trans_never_zero() {
1876 let pairs = [
1878 (alkene(true), alkene(false)),
1879 (hetero_alkene(true), hetero_alkene(false)),
1880 (branched_alkene(true), branched_alkene(false)),
1881 ];
1882 for (cis, trans) in pairs {
1883 let res = cost_mapping(&cis, &trans).expect("map");
1884 assert!(res.cost > 0, "identity cost=0 map={:?}", res.map);
1885 for perm in all_perms(cis.n_atoms()).into_iter().take(24) {
1886 let c = cis.permute(&perm);
1887 let res = cost_mapping(&c, &trans).expect("map");
1888 assert!(res.cost > 0, "perm={perm:?} cost=0 map={:?}", res.map);
1889 }
1890 }
1891 }
1892 #[test]
1893 fn ez_geometry_sides_and_distances() {
1894 let cis = [(-1.0, 1.0), (0.0, 0.0), (1.5, 0.0), (2.5, 1.0)];
1895 let trans = [(-1.0, 1.0), (0.0, 0.0), (1.5, 0.0), (2.5, -1.0)];
1896 assert!(substituents_same_side(
1897 cis[1].0, cis[1].1, cis[2].0, cis[2].1, cis[0].0, cis[0].1, cis[3].0, cis[3].1
1898 ));
1899 assert!(!substituents_same_side(
1900 trans[1].0, trans[1].1, trans[2].0, trans[2].1, trans[0].0, trans[0].1, trans[3].0,
1901 trans[3].1
1902 ));
1903 let d = |p: &[(f64, f64)], i: usize, j: usize| -> f64 {
1904 ((p[i].0 - p[j].0).powi(2) + (p[i].1 - p[j].1).powi(2)).sqrt()
1905 };
1906 assert!(d(&cis, 0, 3) < d(&trans, 0, 3));
1907 }
1908 #[test]
1909 fn tetrahedral_stereo_free() {
1910 let r = chiral(true);
1911 let s = chiral(false);
1912 let res = cost_mapping(&r, &s).expect("map");
1913 assert_eq!(res.cost, 0);
1914 assert_eq!(res.map.len(), 4);
1915 for perm in all_perms(4) {
1916 let res = cost_mapping(&r, &s.permute(&perm)).expect("map");
1917 assert_eq!(res.cost, 0, "perm={perm:?}");
1918 }
1919 }
1920}
1921
1922#[cfg(test)]
1923mod exact_tests {
1924 use super::*;
1925 fn atom(z: u8) -> AtomFeat {
1926 AtomFeat {
1927 atomic_number: z,
1928 formal_charge: 0,
1929 radical: 0,
1930 chirality: AtomChirality::None,
1931 }
1932 }
1933 fn edge(a: usize, b: usize) -> BondFeat {
1934 BondFeat {
1935 begin: a as u16,
1936 end: b as u16,
1937 order: 1,
1938 aromatic: false,
1939 stereo: EzStereo::None,
1940 stereo_atom1: None,
1941 stereo_atom2: None,
1942 }
1943 }
1944 fn graph(n: usize, bits: usize) -> MolGraph {
1945 let mut bonds = Vec::new();
1946 let mut bit = 0;
1947 for a in 0..n {
1948 for b in 0..a {
1949 if bits & (1 << bit) != 0 {
1950 bonds.push(edge(a, b));
1951 }
1952 bit += 1;
1953 }
1954 }
1955 MolGraph::new(vec![atom(6); n], bonds)
1956 }
1957 fn connected(q: &Graph<'_>, r: &Graph<'_>, map: &[usize]) -> bool {
1958 let Some(root) = map.iter().position(|&b| b != NONE) else {
1959 return false;
1960 };
1961 let mut seen = vec![false; q.n];
1962 seen[root] = true;
1963 let mut stack = vec![root];
1964 while let Some(a) = stack.pop() {
1965 for &(x, _) in &q.adj[a] {
1966 if !seen[x] && map[x] != NONE && r.bond(map[a], map[x]) != NONE {
1967 seen[x] = true;
1968 stack.push(x);
1969 }
1970 }
1971 }
1972 map.iter().enumerate().all(|(a, &b)| b == NONE || seen[a])
1973 }
1974 fn brute(reference: &MolGraph, query: &MolGraph) -> i32 {
1977 let q = Graph::new(query).unwrap();
1978 let r = Graph::new(reference).unwrap();
1979 fn rec(
1980 q: &Graph<'_>,
1981 r: &Graph<'_>,
1982 map: &mut [usize],
1983 used: &mut [bool],
1984 a: usize,
1985 best: &mut i32,
1986 ) {
1987 if a < q.n {
1988 map[a] = NONE;
1989 rec(q, r, map, used, a + 1, best);
1990 for b in 0..r.n {
1991 if !used[b] && !ring_size_mismatch(q, r, a, b) {
1992 used[b] = true;
1993 map[a] = b;
1994 rec(q, r, map, used, a + 1, best);
1995 used[b] = false;
1996 }
1997 }
1998 map[a] = NONE;
1999 return;
2000 }
2001 if !connected(q, r, map) || !stereo_ok(q, r, map) {
2002 return;
2003 }
2004 let mut cost = 0;
2005 let mut matched_bonds = 0;
2006 for (a, &b) in map.iter().enumerate() {
2007 cost += if b == NONE {
2008 COST_UNMATCHED
2009 } else {
2010 atom_cost(q, r, a, b) as i32
2011 };
2012 }
2013 for qb in &q.mol.bonds {
2014 let (x, y) = (map[qb.begin as usize], map[qb.end as usize]);
2015 let e = if x != NONE && y != NONE {
2016 r.bond(x, y)
2017 } else {
2018 NONE
2019 };
2020 cost += if e == NONE {
2021 COST_UNMATCHED
2022 } else {
2023 matched_bonds += 1;
2024 (PAIR_GAIN - bond_gain(qb, &r.mol.bonds[e])) as i32
2025 };
2026 }
2027 let matched_atoms = map.iter().filter(|&&b| b != NONE).count();
2029 cost += COST_UNMATCHED * (r.n - matched_atoms + r.mol.n_bonds() - matched_bonds) as i32;
2030 *best = (*best).min(cost);
2031 }
2032 let mut best = i32::MAX;
2033 rec(
2034 &q,
2035 &r,
2036 &mut vec![NONE; q.n],
2037 &mut vec![false; r.n],
2038 0,
2039 &mut best,
2040 );
2041 best
2042 }
2043 fn assert_solution(r: &MolGraph, q: &MolGraph, gens: &[Vec<u16>]) {
2044 let got = cost_mapping_with_generators(r, q, gens).unwrap().0;
2045 let brute_cost = brute(r, q);
2046 let Some(result) = got else {
2047 assert_eq!(
2048 brute_cost,
2049 i32::MAX,
2050 "search empty but brute={brute_cost} q={q:?} r={r:?}"
2051 );
2052 return;
2053 };
2054 assert_eq!(
2055 result.cost, brute_cost,
2056 "q={q:?} r={r:?} map={:?}",
2057 result.map
2058 );
2059 assert_eq!(result.cost, mapping_cost(q, r, &result.map));
2060 let mut dense = vec![NONE; q.n_atoms()];
2061 for (&a, &b) in &result.map {
2062 dense[a as usize] = b as usize;
2063 }
2064 let (qg, rg) = (Graph::new(q).unwrap(), Graph::new(r).unwrap());
2065 assert!(connected(&qg, &rg, &dense));
2066 assert!(stereo_ok(&qg, &rg, &dense));
2067 }
2068 #[test]
2069 fn exhaustive_all_pairs_of_four_vertex_graphs() {
2070 for qb in 0..64 {
2071 for rb in 0..64 {
2072 assert_solution(&graph(4, rb), &graph(4, qb), &[]);
2073 }
2074 }
2075 }
2076 #[test]
2077 fn weighted_random_graphs_match_brute_force() {
2078 let mut state = 1234567u64;
2079 let mut next = || {
2080 state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
2081 state >> 32
2082 };
2083 for _ in 0..160 {
2084 let mut q = graph(5, next() as usize & 1023);
2085 let mut r = graph(5, next() as usize & 1023);
2086 for mol in [&mut q, &mut r] {
2087 for a in &mut mol.atoms {
2088 a.atomic_number = [6, 6, 7, 8][next() as usize % 4];
2089 a.formal_charge = (next() % 3) as i8 - 1;
2090 }
2091 for b in &mut mol.bonds {
2092 b.order = (next() % 3 + 1) as u8;
2093 }
2094 }
2095 assert_solution(&r, &q, &[]);
2096 }
2097 }
2098 fn closure(g: &Group) -> HashSet<Perm> {
2099 let id: Perm = (0..g.n).collect();
2100 let mut seen = HashSet::from([id.clone()]);
2101 let mut queue = VecDeque::from([id]);
2102 while let Some(p) = queue.pop_front() {
2103 for a in &g.generators {
2104 let b = compose(a, &p);
2105 if seen.insert(b.clone()) {
2106 queue.push_back(b);
2107 }
2108 }
2109 }
2110 seen
2111 }
2112 #[test]
2113 fn schreier_recovers_stabilizer_compositions() {
2114 let g = Group::new(4, vec![vec![1, 2, 3, 0], vec![1, 0, 2, 3]]);
2115 assert_eq!(closure(&g).len(), 24);
2116 let fixed = g.stabilizer(0);
2117 let expected: HashSet<_> = closure(&g).into_iter().filter(|p| p[0] == 0).collect();
2118 assert_eq!(closure(&fixed), expected);
2119 assert_eq!(closure(&fixed).len(), 6);
2120 assert_eq!(closure(&fixed.stabilizer(1)).len(), 2);
2121 }
2122 #[test]
2123 fn symmetry_and_exclusions_match_brute_force() {
2124 let ring = MolGraph::new(
2125 vec![atom(6); 5],
2126 (0..5).map(|i| edge(i, (i + 1) % 5)).collect(),
2127 );
2128 let star = MolGraph::new(vec![atom(6); 5], (1..5).map(|i| edge(0, i)).collect());
2129 let ring_gens = vec![vec![1, 2, 3, 4, 0], vec![0, 4, 3, 2, 1]];
2130 let star_gens = vec![vec![0, 2, 3, 4, 1], vec![0, 2, 1, 3, 4]];
2131 let mut removed = 0;
2132 for bits in (0..1024).step_by(17) {
2133 let mut q = graph(5, bits);
2134 q.atoms[1].atomic_number = 8;
2135 for (r, gens) in [(&ring, &ring_gens), (&star, &star_gens)] {
2136 assert_solution(r, &q, gens);
2137 removed += cost_mapping_with_generators(r, &q, gens)
2138 .unwrap()
2139 .1
2140 .symmetry_alternatives_removed;
2141 }
2142 }
2143 assert!(removed > 0);
2144 }
2145 #[test]
2146 fn negative_bridge_is_not_pruned() {
2147 let r = MolGraph::new(vec![atom(6); 5], (0..4).map(|i| edge(i, i + 1)).collect());
2148 let mut q = r.clone();
2149 q.atoms[2].atomic_number = 7;
2150 assert_solution(&r, &q, &[]);
2151 let result = cost_mapping(&r, &q).unwrap();
2152 assert_eq!(result.cost, 11);
2153 assert_eq!(result.map.len(), 5);
2154 }
2155 #[test]
2156 fn assignment_matches_exhaustive_assignments() {
2157 fn brute_w(w: &[Vec<i64>], i: usize, used: &mut [bool]) -> i64 {
2158 if i == w.len() {
2159 return 0;
2160 }
2161 let mut best = brute_w(w, i + 1, used);
2162 for j in 0..used.len() {
2163 if !used[j] {
2164 used[j] = true;
2165 best = best.max(w[i][j] + brute_w(w, i + 1, used));
2166 used[j] = false;
2167 }
2168 }
2169 best
2170 }
2171 for k in 0..100 {
2172 let w: Vec<Vec<_>> = (0..5)
2173 .map(|i| {
2174 (0..4)
2175 .map(|j| ((k + 3 * i + 7 * j + i * j) % 19) as i64)
2176 .collect()
2177 })
2178 .collect();
2179 assert_eq!(assignment_upper(&w), brute_w(&w, 0, &mut [false; 4]));
2180 }
2181 }
2182 #[test]
2183 fn invalid_generators_rejected() {
2184 let r = graph(4, 7);
2185 assert!(cost_mapping_with_generators(&r, &r, &[vec![0, 0, 2, 3]]).is_err());
2186 assert!(cost_mapping_with_generators(&r, &r, &[vec![0, 1]]).is_err());
2187 let mut r = graph(2, 1);
2188 r.atoms[1].atomic_number = 8;
2189 assert!(cost_mapping_with_generators(&r, &r, &[vec![1, 0]]).is_err());
2190 }
2191 #[test]
2192 fn empty_and_single_atom_inputs() {
2193 assert!(cost_mapping(&graph(0, 0), &graph(1, 0)).is_none());
2194 let r = MolGraph::new(vec![atom(8)], vec![]);
2195 let q = MolGraph::new(vec![atom(6)], vec![]);
2196 assert_eq!(cost_mapping(&r, &q).unwrap().cost, 11);
2198 }
2199 #[test]
2200 fn medium_related_molecule_smoke_benchmark() {
2201 let mut r = MolGraph::new(
2202 vec![atom(6); 12],
2203 (0..12).map(|i| edge(i, (i + 1) % 12)).collect(),
2204 );
2205 for i in 0..12 {
2206 let mut last = i;
2207 for j in 0..i % 4 {
2208 let a = r.n_atoms();
2209 r.atoms.push(atom(if j == 1 { 8 } else { 6 }));
2210 r.bonds.push(edge(last, a));
2211 last = a;
2212 }
2213 }
2214 let mut q = r.clone();
2215 q.atoms[8].atomic_number = 7;
2216 let start = std::time::Instant::now();
2217 let (result, stats) = cost_mapping_with_generators(&r, &q, &[]).unwrap();
2218 let result = result.unwrap();
2219 assert_eq!(result.cost, mapping_cost(&q, &r, &result.map));
2220 eprintln!(
2221 "synthetic {}-atom related pair: {:?}; {stats:?}; cost={}",
2222 q.n_atoms(),
2223 start.elapsed(),
2224 result.cost
2225 );
2226 }
2227
2228 #[test]
2229 fn greedy_only_maps_hexane_onto_cyclohexane() {
2230 let hexane = MolGraph::new(vec![atom(6); 6], (0..5).map(|i| edge(i, i + 1)).collect());
2231 let mut bonds: Vec<_> = (0..5).map(|i| edge(i, i + 1)).collect();
2232 bonds.push(edge(0, 5));
2233 let cyclo = MolGraph::new(vec![atom(6); 6], bonds);
2234 let limits = SearchLimits {
2235 greedy_only: true,
2236 ..SearchLimits::unbounded()
2237 };
2238 let (res, stats) =
2239 cost_mapping_with_generators_limited(&hexane, &cyclo, &[], &limits).unwrap();
2240 let res = res.expect("greedy map");
2241 assert_eq!(res.map.len(), 6, "map={:?}", res.map);
2242 assert!(!stats.timed_out);
2243 assert_eq!(res.cost, mapping_cost(&cyclo, &hexane, &res.map));
2244 }
2245
2246 fn oxolane() -> MolGraph {
2247 MolGraph::new(
2248 vec![atom(8), atom(6), atom(6), atom(6), atom(6)],
2249 vec![edge(0, 1), edge(1, 2), edge(2, 3), edge(3, 4), edge(4, 0)],
2250 )
2251 }
2252
2253 fn indane() -> MolGraph {
2254 let mut bonds: Vec<_> = (0..5).map(|i| edge(i, i + 1)).collect();
2256 bonds.push(edge(5, 0));
2257 bonds.push(edge(5, 6));
2258 bonds.push(edge(6, 7));
2259 bonds.push(edge(7, 8));
2260 bonds.push(edge(8, 0));
2261 MolGraph::new(vec![atom(6); 9], bonds)
2262 }
2263
2264 #[test]
2265 fn ring_seed_maps_oxolane_oxygen_to_oxygen() {
2266 let r = oxolane();
2267 let q = oxolane();
2268 let res = cost_mapping(&r, &q).expect("map");
2269 assert_eq!(res.map.len(), 5, "map={:?}", res.map);
2270 assert_eq!(
2271 res.map.get(&0),
2272 Some(&0),
2273 "O should map to O: {:?}",
2274 res.map
2275 );
2276 assert_eq!(res.cost, 0);
2277 }
2278
2279 #[test]
2280 fn house_timeout_locks_unique_five_ring_on_indane() {
2281 let r = indane();
2282 let mut q = indane();
2283 let extra = q.n_atoms();
2284 q.atoms.push(atom(6));
2285 q.bonds.push(edge(6, extra));
2286 let limits = SearchLimits::house();
2287 let (res, _stats) = cost_mapping_with_generators_limited(&r, &q, &[], &limits).unwrap();
2288 let res = res.expect("map");
2289 let five_q: HashSet<u16> = [0u16, 5, 6, 7, 8].into_iter().collect();
2290 let five_r: HashSet<u16> = [0u16, 5, 6, 7, 8].into_iter().collect();
2291 let mapped_five: Vec<_> = res.map.iter().filter(|(a, _)| five_q.contains(a)).collect();
2292 assert_eq!(mapped_five.len(), 5, "map={:?}", res.map);
2293 assert!(
2294 mapped_five.iter().all(|(_, b)| five_r.contains(b)),
2295 "5-ring mapped off the 5-ring: {:?}",
2296 res.map
2297 );
2298 assert!(!res.map.contains_key(&(extra as u16)));
2299 assert_eq!(res.map.get(&0), Some(&0), "map={:?}", res.map);
2301 assert_eq!(res.map.get(&5), Some(&5), "map={:?}", res.map);
2302 }
2303
2304 #[test]
2305 fn different_size_rings_do_not_wrap() {
2306 let twelve = MolGraph::new(
2307 vec![atom(6); 12],
2308 (0..12).map(|i| edge(i, (i + 1) % 12)).collect(),
2309 );
2310 let fifteen = MolGraph::new(
2311 vec![atom(6); 15],
2312 (0..15).map(|i| edge(i, (i + 1) % 15)).collect(),
2313 );
2314 let res = cost_mapping(&twelve, &fifteen);
2315 assert!(
2316 res.as_ref().map(|m| m.map.len()).unwrap_or(0) < 12,
2317 "must not overlay a 12-cycle on a 15-cycle: {:?}",
2318 res
2319 );
2320 }
2321
2322 fn pyranose_nme2_and_methyl() -> MolGraph {
2323 MolGraph::new(
2325 vec![
2326 atom(8),
2327 atom(6),
2328 atom(6),
2329 atom(6),
2330 atom(6),
2331 atom(6),
2332 atom(7),
2333 atom(6),
2334 ],
2335 vec![
2336 edge(0, 1),
2337 edge(1, 2),
2338 edge(2, 3),
2339 edge(3, 4),
2340 edge(4, 5),
2341 edge(5, 0),
2342 edge(1, 6),
2343 edge(3, 7),
2344 ],
2345 )
2346 }
2347
2348 #[test]
2349 fn sugar_ring_seed_does_not_flip_nme2_onto_methyl() {
2350 let g = pyranose_nme2_and_methyl();
2351 let (res, _) =
2352 cost_mapping_with_generators_limited(&g, &g, &[], &SearchLimits::house()).unwrap();
2353 let res = res.expect("map");
2354 assert_eq!(res.map.get(&6), Some(&6), "N must stay on N: {:?}", res.map);
2355 assert_eq!(
2356 res.map.get(&7),
2357 Some(&7),
2358 "Me must stay on Me: {:?}",
2359 res.map
2360 );
2361 assert_eq!(res.map.get(&0), Some(&0), "ring O: {:?}", res.map);
2362 }
2363
2364 #[test]
2365 fn fused_macrocycle_still_maps_shared_ring() {
2366 let eighteen = MolGraph::new(
2369 vec![atom(6); 18],
2370 (0..18).map(|i| edge(i, (i + 1) % 18)).collect(),
2371 );
2372 let mut bonds: Vec<_> = (0..18).map(|i| edge(i, (i + 1) % 18)).collect();
2373 bonds.push(edge(1, 18));
2374 bonds.push(edge(18, 19));
2375 bonds.push(edge(19, 20));
2376 bonds.push(edge(20, 21));
2377 bonds.push(edge(21, 0));
2378 let fused = MolGraph::new(vec![atom(6); 22], bonds);
2379 let res = cost_mapping(&eighteen, &fused).expect("map");
2380 assert_eq!(res.map.len(), 18, "map={:?}", res.map);
2381 }
2382
2383 fn six_ring_hetero(z: u8) -> MolGraph {
2384 let mut atoms = vec![atom(6); 6];
2385 atoms[0] = atom(z);
2386 MolGraph::new(atoms, (0..6).map(|i| edge(i, (i + 1) % 6)).collect())
2387 }
2388
2389 #[test]
2390 fn house_maps_ring_nitrogen_onto_ring_oxygen() {
2391 let thp = six_ring_hetero(8);
2392 let piperidine = six_ring_hetero(7);
2393 let (res, _) =
2394 cost_mapping_with_generators_limited(&thp, &piperidine, &[], &SearchLimits::house())
2395 .unwrap();
2396 let res = res.expect("map");
2397 assert_eq!(res.map.len(), 6, "map={:?}", res.map);
2398 assert_eq!(
2399 res.map.get(&0),
2400 Some(&0),
2401 "N should sit on O: {:?}",
2402 res.map
2403 );
2404 }
2405
2406 #[test]
2407 fn house_does_not_pair_oxygen_onto_carbon() {
2408 let ethane = MolGraph::new(vec![atom(6), atom(6)], vec![edge(0, 1)]);
2410 let methanol = MolGraph::new(vec![atom(6), atom(8)], vec![edge(0, 1)]);
2411 let unbounded = cost_mapping(ðane, &methanol).expect("map");
2412 assert_eq!(unbounded.map.len(), 2, "exact may pay COST_ELEMENT");
2413 let (house, _) =
2414 cost_mapping_with_generators_limited(ðane, &methanol, &[], &SearchLimits::house())
2415 .unwrap();
2416 let house = house.expect("C→C seed");
2417 assert_eq!(house.map.len(), 1, "map={:?}", house.map);
2418 assert_eq!(house.map.get(&0), Some(&0));
2419 }
2420
2421 #[test]
2422 fn max_states_cap_returns_incumbent_without_hanging() {
2423 let mut r = MolGraph::new(
2424 vec![atom(6); 12],
2425 (0..12).map(|i| edge(i, (i + 1) % 12)).collect(),
2426 );
2427 for i in 0..12 {
2428 let mut last = i;
2429 for j in 0..i % 4 {
2430 let a = r.n_atoms();
2431 r.atoms.push(atom(if j == 1 { 8 } else { 6 }));
2432 r.bonds.push(edge(last, a));
2433 last = a;
2434 }
2435 }
2436 let mut q = r.clone();
2437 q.atoms[8].atomic_number = 7;
2438 let limits = SearchLimits {
2439 max_states: Some(8),
2440 ..SearchLimits::unbounded()
2441 };
2442 let start = Instant::now();
2443 let (res, stats) = cost_mapping_with_generators_limited(&r, &q, &[], &limits).unwrap();
2444 assert!(stats.timed_out, "cap should fire; {stats:?}");
2445 assert!(res.is_some(), "incumbent should survive a cap");
2446 assert!(
2447 start.elapsed() < std::time::Duration::from_secs(2),
2448 "capped search hung: {:?}",
2449 start.elapsed()
2450 );
2451 }
2452}
2453
2454#[cfg(test)]
2455mod canonaut_tests {
2456 use super::*;
2457
2458 fn atom(z: u8) -> AtomFeat {
2459 AtomFeat {
2460 atomic_number: z,
2461 formal_charge: 0,
2462 radical: 0,
2463 chirality: AtomChirality::None,
2464 }
2465 }
2466 fn bond(a: u16, b: u16, order: u8) -> BondFeat {
2467 BondFeat {
2468 begin: a,
2469 end: b,
2470 order,
2471 aromatic: false,
2472 stereo: EzStereo::None,
2473 stereo_atom1: None,
2474 stereo_atom2: None,
2475 }
2476 }
2477 fn chain_ring(chain: u16, ring: u16) -> MolGraph {
2478 let n = chain + ring;
2479 let mut bonds: Vec<_> = (1..n).map(|i| bond(i - 1, i, 1)).collect();
2480 if ring > 2 {
2481 bonds.push(bond(chain, n - 1, 1));
2482 }
2483 MolGraph::new(vec![atom(6); n as usize], bonds)
2484 }
2485
2486 #[test]
2487 fn cyclohexane_generators_act_on_ring() {
2488 let ring = MolGraph::new(
2489 vec![atom(6); 6],
2490 (0..6).map(|i| bond(i, (i + 1) % 6, 1)).collect(),
2491 );
2492 let gens = reference_generators(&ring);
2493 assert!(!gens.is_empty());
2494 let (res, stats) = cost_mapping_with_generators(&ring, &ring, &gens).unwrap();
2495 assert_eq!(res.unwrap().cost, 0);
2496 assert_eq!(stats.seeds, 1);
2498 }
2499
2500 #[test]
2501 fn generators_respect_bond_order() {
2502 let diene = MolGraph::new(
2504 vec![atom(6); 4],
2505 vec![bond(0, 1, 2), bond(1, 2, 1), bond(2, 3, 2)],
2506 );
2507 for g in reference_generators(&diene) {
2508 assert!(g == [3, 2, 1, 0] || g == [0, 1, 2, 3], "{g:?}");
2509 }
2510 }
2511
2512 #[test]
2513 fn optimal_assignment_maximizes_gain_and_drops_losers() {
2514 let gain = [9, 8, 0, 7, 1, -4];
2516 assert_eq!(optimal_assignment(&gain, 2, 3), vec![Some(1), Some(0)]);
2517 assert_eq!(optimal_assignment(&[-1, -2], 1, 2), vec![None]);
2519 }
2520
2521 #[test]
2522 fn symmetry_does_not_change_optimum() {
2523 let pentyl = chain_ring(5, 6);
2524 let hexane = chain_ring(6, 0);
2525 for (r, q) in [(&pentyl, &hexane), (&hexane, &pentyl), (&pentyl, &pentyl)] {
2526 let plain = cost_mapping_with_generators(r, q, &[]).unwrap().0.unwrap();
2527 let sym = cost_mapping(r, q).unwrap();
2528 assert_eq!(plain.cost, sym.cost);
2529 assert_eq!(mapping_cost(q, r, &sym.map), sym.cost);
2530 }
2531 }
2532}