1use crate::align_cost::{
4 cost_mapping_with_generators_limited, reference_generators, AtomChirality, AtomFeat, BondFeat,
5 EzStereo, MappingResult, MolGraph, SearchLimits,
6};
7use crate::edge::{AlignMode, AlignOpts, MIN_MCS_ATOMS};
8use crate::layout_coordgen::{
9 generate_2d_coordinates, CoordGenError, LayoutMolecule, LayoutResult, BOND_STEREO_CIS,
10 BOND_STEREO_NONE, BOND_STEREO_TRANS,
11};
12
13pub fn mol_graph_from_layout(mol: &LayoutMolecule) -> MolGraph {
15 let atoms = mol
16 .atomic_numbers
17 .iter()
18 .zip(mol.formal_charges.iter())
19 .map(|(&z, &ch)| AtomFeat {
20 atomic_number: z.clamp(0, 255) as u8,
21 formal_charge: ch.clamp(i8::MIN as i32, i8::MAX as i32) as i8,
22 radical: 0,
23 chirality: AtomChirality::None,
24 })
25 .collect();
26 let bonds = mol
27 .bond_from
28 .iter()
29 .enumerate()
30 .map(|(i, &a)| {
31 let b = mol.bond_to[i];
32 let raw = mol.bond_orders.get(i).copied().unwrap_or(1);
34 let aromatic = raw >= 4;
35 let order = if aromatic { 1 } else { raw.clamp(0, 3) as u8 };
36 let stereo = match mol.bond_stereos.get(i).copied().unwrap_or(BOND_STEREO_NONE) {
37 x if x == BOND_STEREO_CIS => EzStereo::Cis,
38 x if x == BOND_STEREO_TRANS => EzStereo::Trans,
39 _ => EzStereo::None,
40 };
41 let (s1, s2) = match (&mol.bond_stereo_atom1, &mol.bond_stereo_atom2) {
42 (Some(a1), Some(a2)) if a1[i] >= 0 && a2[i] >= 0 => {
43 (Some(a1[i] as u16), Some(a2[i] as u16))
44 }
45 _ => (None, None),
46 };
47 BondFeat {
48 begin: a as u16,
49 end: b as u16,
50 order,
51 aromatic,
52 stereo,
53 stereo_atom1: s1,
54 stereo_atom2: s2,
55 }
56 })
57 .collect();
58 MolGraph::new(atoms, bonds)
59}
60
61#[derive(Debug, Clone)]
62pub struct ConstrainedAlignResult {
63 pub mapping: MappingResult,
64 pub ref_coords: LayoutResult,
65 pub query_coords: LayoutResult,
66}
67
68fn ensure_ref_coords(mol: &LayoutMolecule) -> Result<LayoutResult, CoordGenError> {
69 if let (Some(x), Some(y)) = (&mol.input_x, &mol.input_y) {
70 if x.len() == mol.n_atoms() && y.len() == mol.n_atoms() {
71 return Ok(LayoutResult {
72 x: x.clone(),
73 y: y.clone(),
74 });
75 }
76 }
77 let mut free = mol.clone();
78 free.has_template_match = None;
79 free.is_atom_fixed = None;
80 free.input_x = None;
81 free.input_y = None;
82 generate_2d_coordinates(&free)
83}
84
85pub fn align_molecule_constrained(
88 reference: &LayoutMolecule,
89 query: &LayoutMolecule,
90) -> Result<ConstrainedAlignResult, CoordGenError> {
91 align_molecule_constrained_with_map(reference, query, None)
92}
93
94pub fn align_molecule_constrained_with_map(
97 reference: &LayoutMolecule,
98 query: &LayoutMolecule,
99 dense_map: Option<&[(u16, u16)]>,
100) -> Result<ConstrainedAlignResult, CoordGenError> {
101 align_molecule_constrained_with_map_limited(
102 reference,
103 query,
104 dense_map,
105 &SearchLimits::unbounded(),
106 0,
107 )
108}
109
110fn align_molecule_constrained_with_map_limited(
111 reference: &LayoutMolecule,
112 query: &LayoutMolecule,
113 dense_map: Option<&[(u16, u16)]>,
114 limits: &SearchLimits,
115 min_atoms: u32,
116) -> Result<ConstrainedAlignResult, CoordGenError> {
117 let mapping = if let Some(pairs) = dense_map {
118 let mut map = std::collections::HashMap::new();
119 for &(q, r) in pairs {
120 map.insert(q, r);
121 }
122 MappingResult { map, cost: 0 }
123 } else {
124 let ref_g = mol_graph_from_layout(reference);
125 let query_g = mol_graph_from_layout(query);
126 let gens = reference_generators(&ref_g);
127 cost_mapping_with_generators_limited(&ref_g, &query_g, &gens, limits)
128 .ok()
129 .and_then(|(m, _)| m)
130 .ok_or(CoordGenError::Empty)?
131 };
132 if (mapping.map.len() as u32) < min_atoms {
133 return Err(CoordGenError::Empty);
134 }
135
136 let ref_coords = ensure_ref_coords(reference)?;
137
138 let nq = query.n_atoms();
139 let mut has_template = vec![0i32; nq];
140 let mut input_x = vec![0.0f32; nq];
141 let mut input_y = vec![0.0f32; nq];
142 for (&qi, &ri) in &mapping.map {
143 let qi = qi as usize;
144 let ri = ri as usize;
145 if qi < nq && ri < ref_coords.x.len() {
146 has_template[qi] = 1;
147 input_x[qi] = ref_coords.x[ri];
148 input_y[qi] = ref_coords.y[ri];
149 }
150 }
151
152 let mut q_lay = query.clone();
153 q_lay.has_template_match = Some(has_template);
154 q_lay.is_atom_fixed = None;
155 q_lay.input_x = Some(input_x);
156 q_lay.input_y = Some(input_y);
157 let query_coords = generate_2d_coordinates(&q_lay)?;
158
159 Ok(ConstrainedAlignResult {
160 mapping,
161 ref_coords,
162 query_coords,
163 })
164}
165
166pub fn layout_or_align(
175 query: &LayoutMolecule,
176 query_atom_indices: &[i32],
177 reference: Option<&LayoutMolecule>,
178 ref_atom_indices: Option<&[i32]>,
179 atom_map: Option<&[(i32, i32)]>,
180 peer_id: Option<&str>,
181 align: Option<&AlignOpts>,
182) -> Result<(LayoutResult, Option<crate::scene::AlignDebug>), CoordGenError> {
183 use crate::debug_align::align_debug_query;
184
185 let Some(reference) = reference else {
186 let coords = generate_2d_coordinates(query)?;
187 return Ok((coords, None));
188 };
189 if matches!(align.map(AlignOpts::align_mode), Some(AlignMode::Skip)) {
190 let coords = generate_2d_coordinates(query)?;
191 return Ok((coords, None));
192 }
193
194 let ref_idx = ref_atom_indices.unwrap_or(&[]);
195 let dense = if let Some(pairs) = atom_map {
196 let q_of: std::collections::HashMap<i32, u16> = query_atom_indices
197 .iter()
198 .enumerate()
199 .map(|(i, &a)| (a, i as u16))
200 .collect();
201 let r_of: std::collections::HashMap<i32, u16> = ref_idx
202 .iter()
203 .enumerate()
204 .map(|(i, &a)| (a, i as u16))
205 .collect();
206 let mut dense_pairs = Vec::new();
207 for &(qa, ra) in pairs {
208 if let (Some(&qi), Some(&ri)) = (q_of.get(&qa), r_of.get(&ra)) {
209 dense_pairs.push((qi, ri));
210 }
211 }
212 if dense_pairs.is_empty() {
213 return Err(CoordGenError::Empty);
214 }
215 Some(dense_pairs)
216 } else {
217 None
218 };
219
220 let limits = match (dense.is_some(), align) {
221 (true, _) => SearchLimits::unbounded(),
222 (false, Some(opts)) => opts.search_limits(),
223 (false, None) => SearchLimits::house(),
224 };
225 let min_atoms = if dense.is_some() {
226 0
227 } else {
228 align.and_then(|o| o.min_atoms).unwrap_or(MIN_MCS_ATOMS)
229 };
230 let res = align_molecule_constrained_with_map_limited(
231 reference,
232 query,
233 dense.as_deref(),
234 &limits,
235 min_atoms,
236 )?;
237
238 let mut tags: Vec<(i32, i32)> = res
239 .mapping
240 .map
241 .iter()
242 .filter_map(|(&qi, &ri)| {
243 let qa = *query_atom_indices.get(qi as usize)?;
244 let ra = *ref_idx.get(ri as usize)?;
245 Some((qa, ra))
246 })
247 .collect();
248 tags.sort_by_key(|(a, _)| *a);
249 let dbg = align_debug_query(peer_id.unwrap_or("?"), &tags);
250 Ok((res.query_coords, Some(dbg)))
251}
252
253pub fn hexagon_fit_max_dev(xy: &[(f64, f64)]) -> f64 {
256 let n = xy.len();
257 if n < 3 {
258 return f64::INFINITY;
259 }
260 let cx = xy.iter().map(|p| p.0).sum::<f64>() / n as f64;
261 let cy = xy.iter().map(|p| p.1).sum::<f64>() / n as f64;
262 let radii: Vec<f64> = xy.iter().map(|(x, y)| (x - cx).hypot(y - cy)).collect();
263 let r = radii.iter().sum::<f64>() / n as f64;
264 if r < 1e-9 {
265 return f64::INFINITY;
266 }
267 let a0 = (xy[0].1 - cy).atan2(xy[0].0 - cx);
269 let mut max_dev = 0.0f64;
270 for (i, &(x, y)) in xy.iter().enumerate() {
271 let ang = a0 + (i as f64) * (std::f64::consts::TAU / n as f64);
272 let tx = cx + r * ang.cos();
273 let ty = cy + r * ang.sin();
274 max_dev = max_dev.max((x - tx).hypot(y - ty));
275 }
276 let mut max_rev = 0.0f64;
278 for (i, &(x, y)) in xy.iter().enumerate() {
279 let ang = a0 - (i as f64) * (std::f64::consts::TAU / n as f64);
280 let tx = cx + r * ang.cos();
281 let ty = cy + r * ang.sin();
282 max_rev = max_rev.max((x - tx).hypot(y - ty));
283 }
284 max_dev.min(max_rev) / r
285}
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290 use crate::layout_coordgen::LayoutMolecule;
291
292 fn chain6() -> LayoutMolecule {
293 LayoutMolecule {
294 atomic_numbers: vec![6; 6],
295 formal_charges: vec![0; 6],
296 bond_from: vec![0, 1, 2, 3, 4],
297 bond_to: vec![1, 2, 3, 4, 5],
298 bond_orders: vec![1; 5],
299 bond_stereos: vec![0; 5],
300 ..Default::default()
301 }
302 }
303
304 fn cyclo6() -> LayoutMolecule {
305 LayoutMolecule {
306 atomic_numbers: vec![6; 6],
307 formal_charges: vec![0; 6],
308 bond_from: vec![0, 1, 2, 3, 4, 0],
309 bond_to: vec![1, 2, 3, 4, 5, 5],
310 bond_orders: vec![1; 6],
311 bond_stereos: vec![0; 6],
312 ..Default::default()
313 }
314 }
315
316 #[test]
317 fn hexane_cyclohexane_full_map_hexagon() {
318 let hexane = chain6();
319 let cyclo = cyclo6();
320 let res = align_molecule_constrained(&hexane, &cyclo).expect("align");
321 assert_eq!(res.mapping.map.len(), 6, "map={:?}", res.mapping.map);
322
323 let rx: Vec<(f64, f64)> = res
325 .ref_coords
326 .x
327 .iter()
328 .zip(res.ref_coords.y.iter())
329 .map(|(&x, &y)| (x as f64, y as f64))
330 .collect();
331 let ref_span = {
332 let xs: Vec<_> = rx.iter().map(|p| p.0).collect();
333 let ys: Vec<_> = rx.iter().map(|p| p.1).collect();
334 let dx = xs.iter().cloned().fold(f64::NEG_INFINITY, f64::max)
335 - xs.iter().cloned().fold(f64::INFINITY, f64::min);
336 let dy = ys.iter().cloned().fold(f64::NEG_INFINITY, f64::max)
337 - ys.iter().cloned().fold(f64::INFINITY, f64::min);
338 dx.max(dy)
339 };
340 assert!(
341 ref_span > 80.0,
342 "hexane should be chain-like, span={ref_span}"
343 );
344
345 let qxy: Vec<(f64, f64)> = res
346 .query_coords
347 .x
348 .iter()
349 .zip(res.query_coords.y.iter())
350 .map(|(&x, &y)| (x as f64, y as f64))
351 .collect();
352 let dev = hexagon_fit_max_dev(&qxy);
354 assert!(
355 dev < 0.35,
356 "constrained cyclohexane not hexagonal enough: rel_dev={dev}"
357 );
358 }
359}