assembly-theory 0.6.1

Open, reproducible calculation of assembly indices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Graph-theoretic representation of a molecule.

use std::{
    collections::{BTreeSet, HashMap, HashSet},
    fmt::Display,
    str::FromStr,
};

use petgraph::{
    dot::Dot,
    graph::{EdgeIndex, Graph, NodeIndex},
    Undirected,
};

use crate::utils::{edge_induced_subgraph, is_subset_connected};

pub(crate) type Index = u32;
pub(crate) type MGraph = Graph<Atom, Bond, Undirected, Index>;
type EdgeSet = BTreeSet<EdgeIndex<Index>>;
type NodeSet = BTreeSet<NodeIndex<Index>>;

/// Thrown by [`Element::from_str`] if the string is not a valid chemical
/// element.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ParseElementError;

macro_rules! periodic_table {
    ( $(($element:ident, $name:literal, $atomicweight:literal),)* ) => {
        #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        /// A chemical element on the periodic table.
        pub enum Element {
            $( $element, )*
        }

        impl Display for Element {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match &self {
                    $( Element::$element => write!(f, "{}", $name), )*
                }
            }
        }

        impl FromStr for Element {
            type Err = ParseElementError;
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                match s {
                    $( $name => Ok(Element::$element), )*
                    _ => Err(ParseElementError),
                }
            }
        }

        impl Element {
            pub fn repr(self) -> u8 {
                match &self {
                    $( Element::$element => $atomicweight, )*
                }
            }
        }
    };
}

periodic_table!(
    (Hydrogen, "H", 1),
    (Helium, "He", 2),
    (Lithium, "Li", 3),
    (Beryllium, "Be", 4),
    (Boron, "B", 5),
    (Carbon, "C", 6),
    (Nitrogen, "N", 7),
    (Oxygen, "O", 8),
    (Fluorine, "F", 9),
    (Neon, "Ne", 10),
    (Sodium, "Na", 11),
    (Magnesium, "Mg", 12),
    (Aluminum, "Al", 13),
    (Silicon, "Si", 14),
    (Phosphorus, "P", 15),
    (Sulfur, "S", 16),
    (Chlorine, "Cl", 17),
    (Argon, "Ar", 18),
    (Potassium, "K", 19),
    (Calcium, "Ca", 20),
    (Scandium, "Sc", 21),
    (Titanium, "Ti", 22),
    (Vanadium, "V", 23),
    (Chromium, "Cr", 24),
    (Manganese, "Mn", 25),
    (Iron, "Fe", 26),
    (Cobalt, "Co", 27),
    (Nickel, "Ni", 28),
    (Copper, "Cu", 29),
    (Zinc, "Zn", 30),
    (Gallium, "Ga", 31),
    (Germanium, "Ge", 32),
    (Arsenic, "As", 33),
    (Selenium, "Se", 34),
    (Bromine, "Br", 35),
    (Krypton, "Kr", 36),
    (Rubidium, "Rb", 37),
    (Strontium, "Sr", 38),
    (Yttrium, "Y", 39),
    (Zirconium, "Zr", 40),
    (Niobium, "Nb", 41),
    (Molybdenum, "Mo", 42),
    (Technetium, "Tc", 43),
    (Ruthenium, "Ru", 44),
    (Rhodium, "Rh", 45),
    (Palladium, "Pd", 46),
    (Silver, "Ag", 47),
    (Cadmium, "Cd", 48),
    (Indium, "In", 49),
    (Tin, "Sn", 50),
    (Antimony, "Sb", 51),
    (Tellurium, "Te", 52),
    (Iodine, "I", 53),
    (Xenon, "Xe", 54),
    (Cesium, "Cs", 55),
    (Barium, "Ba", 56),
    (Lanthanum, "La", 57),
    (Cerium, "Ce", 58),
    (Praseodymium, "Pr", 59),
    (Neodymium, "Nd", 60),
    (Promethium, "Pm", 61),
    (Samarium, "Sm", 62),
    (Europium, "Eu", 63),
    (Gadolinium, "Gd", 64),
    (Terbium, "Tb", 65),
    (Dysprosium, "Dy", 66),
    (Holmium, "Ho", 67),
    (Erbium, "Er", 68),
    (Thulium, "Tm", 69),
    (Ytterbium, "Yb", 70),
    (Lutetium, "Lu", 71),
    (Hafnium, "Hf", 72),
    (Tantalum, "Ta", 73),
    (Wolfram, "W", 74),
    (Rhenium, "Re", 75),
    (Osmium, "Os", 76),
    (Iridium, "Ir", 77),
    (Platinum, "Pt", 78),
    (Gold, "Au", 79),
    (Mercury, "Hg", 80),
    (Thallium, "Tl", 81),
    (Lead, "Pb", 82),
    (Bismuth, "Bi", 83),
    (Polonium, "Po", 84),
    (Astatine, "At", 85),
    (Radon, "Rn", 86),
    (Francium, "Fr", 87),
    (Radium, "Ra", 88),
    (Actinium, "Ac", 89),
    (Thorium, "Th", 90),
    (Protactinium, "Pa", 91),
    (Uranium, "U", 92),
    (Neptunium, "Np", 93),
    (Plutonium, "Pu", 94),
    (Americium, "Am", 95),
    (Curium, "Cm", 96),
    (Berkelium, "Bk", 97),
    (Californium, "Cf", 98),
    (Einsteinium, "Es", 99),
    (Fermium, "Fm", 100),
    (Mendelevium, "Md", 101),
    (Nobelium, "No", 102),
    (Lawrencium, "Lr", 103),
    (Rutherfordium, "Rf", 104),
    (Dubnium, "Db", 105),
    (Seaborgium, "Sg", 106),
    (Bohrium, "Bh", 107),
    (Hassium, "Hs", 108),
    (Meitnerium, "Mt", 109),
    (Darmstadtium, "Ds", 110),
    (Roentgenium, "Rg", 111),
    (Copernicium, "Cn", 112),
    (Nihonium, "Nh", 113),
    (Flerovium, "Fl", 114),
    (Moscovium, "Mc", 115),
    (Livermorium, "Lv", 116),
    (Tennessine, "Ts", 117),
    (Oganesson, "Og", 118),
);

/// The nodes of a [`Molecule`] graph.
///
/// Atoms contain an element and have a (currently unused) `capacity` field.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Atom {
    element: Element,
    capacity: u32,
}

impl Atom {
    /// Construct an [`Atom`] of type `element` with capacity `capacity`.
    pub fn new(element: Element, capacity: u32) -> Self {
        Self { element, capacity }
    }

    /// Return this [`Atom`]'s element.
    pub fn element(&self) -> Element {
        self.element
    }
}

/// The edges of a [`Molecule`] graph.
///
/// The `.mol` file spec describes seven types of bonds, but the assembly
/// theory literature only considers single, double, and triple bonds. Notably,
/// aromatic rings are represented by alternating single and double bonds
/// instead of the aromatic bond type.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Bond {
    Single,
    Double,
    Triple,
}

/// Either an [`Atom`] or a [`Bond`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AtomOrBond {
    Atom(Atom),
    Bond(Bond),
}

/// Thrown by [`Bond::try_from`] when given anything other than a 1, 2, or 3.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ParseBondError;

impl TryFrom<usize> for Bond {
    type Error = ParseBondError;
    fn try_from(value: usize) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(Bond::Single),
            2 => Ok(Bond::Double),
            3 => Ok(Bond::Triple),
            _ => Err(ParseBondError),
        }
    }
}

impl Bond {
    pub fn repr(self) -> u8 {
        match self {
            Bond::Single => 1,
            Bond::Double => 2,
            Bond::Triple => 3,
        }
    }
}

/// A simple, loopless graph with [`Atom`]s as nodes and [`Bond`]s as edges.
///
/// Assembly theory literature ignores hydrogen atoms by default. Molecules can
/// have hydrogen atoms inserted into them, but by default are constructed
/// without hydrogen atoms or bonds to hydrogen atoms.
#[derive(Debug, Clone)]
pub struct Molecule {
    graph: MGraph,
}

impl Molecule {
    /// Construct a [`Molecule`] from an existing `MGraph`.
    pub(crate) fn from_graph(g: MGraph) -> Self {
        Self { graph: g }
    }

    /// Return a representation of this molecule as an `MGraph`.
    ///
    /// Only public for benchmarking purposes.
    pub fn graph(&self) -> &MGraph {
        &self.graph
    }

    /// Return a pretty-printable representation of this molecule.
    pub fn info(&self) -> String {
        let dot = Dot::new(&self.graph);
        format!("{dot:?}")
    }

    /// Return `true` iff this molecule contains self-loops or multiple edges
    /// between any pair of nodes.
    pub fn is_malformed(&self) -> bool {
        let mut uniq = HashSet::new();
        !self.graph.edge_indices().all(|ix| {
            uniq.insert(ix)
                && self
                    .graph
                    .edge_endpoints(ix)
                    .is_some_and(|(src, dst)| src != dst)
        })
    }

    /// Return `true` iff this molecule comprises only one bond (of any type).
    pub fn is_basic_unit(&self) -> bool {
        self.graph.edge_count() == 1 && self.graph.node_count() == 2
    }

    /// Join this molecule with `other` on edge `on`.
    pub fn join(
        &self,
        other: &Molecule,
        on: impl IntoIterator<Item = (NodeIndex<Index>, NodeIndex<Index>)>,
    ) -> Option<Molecule> {
        let mut output_graph = self.clone();

        let mut v_set = NodeSet::new();
        let mut io_map = HashMap::<NodeIndex<Index>, NodeIndex<Index>>::new();

        for (u, v) in on.into_iter() {
            v_set.insert(v);
            io_map.insert(v, u);
        }

        for ix in other.graph.node_indices() {
            if !v_set.contains(&ix) {
                let w = *other.graph.node_weight(ix)?;
                let out = output_graph.graph.add_node(w);
                io_map.insert(ix, out);
            }
        }

        for ix in other.graph.edge_indices() {
            let (u, v) = other.graph.edge_endpoints(ix)?;
            let um = io_map.get(&u)?;
            let vm = io_map.get(&v)?;
            let w = *other.graph.edge_weight(ix)?;

            output_graph.graph.add_edge(*um, *vm, w);
        }

        Some(output_graph)
    }

    /// Return an iterator over all ways of partitioning this molecule into two
    /// submolecules.
    pub fn partitions(&self) -> Option<impl Iterator<Item = (Molecule, Molecule)> + '_> {
        let mut solutions = HashSet::new();
        let remaining_edges = self.graph.edge_indices().collect();
        self.backtrack(
            remaining_edges,
            BTreeSet::new(),
            BTreeSet::new(),
            &mut solutions,
        );
        Some(solutions.into_iter().map(|(left, right)| {
            (
                Molecule {
                    graph: edge_induced_subgraph(self.graph.clone(), &left),
                },
                Molecule {
                    graph: edge_induced_subgraph(self.graph.clone(), &right),
                },
            )
        }))
    }

    fn backtrack(
        &self,
        mut remaining_edges: Vec<EdgeIndex<Index>>,
        left: EdgeSet,
        right: EdgeSet,
        solutions: &mut HashSet<(EdgeSet, EdgeSet)>,
    ) {
        if let Some(suffix) = remaining_edges.pop() {
            let mut lc = left.clone();
            lc.insert(suffix);

            let mut rc = right.clone();
            rc.insert(suffix);

            self.backtrack(remaining_edges.clone(), lc, right, solutions);
            self.backtrack(remaining_edges, left, rc, solutions);
        } else if self.is_valid_partition(&left, &right) {
            solutions.insert((left, right));
        }
    }

    fn is_valid_partition(&self, left: &EdgeSet, right: &EdgeSet) -> bool {
        !left.is_empty()
            && !right.is_empty()
            && is_subset_connected(&self.graph, left)
            && is_subset_connected(&self.graph, right)
    }

    #[allow(dead_code)]
    fn print_edgelist(&self, list: &[EdgeIndex], name: &str) {
        println!(
            "{name}: {:?}",
            list.iter()
                .map(|e| (
                    e.index(),
                    self.graph
                        .edge_endpoints(*e)
                        .map(|(i, j)| (
                            i.index(),
                            self.graph.node_weight(i).unwrap().element(),
                            j.index(),
                            self.graph.node_weight(j).unwrap().element(),
                        ))
                        .unwrap()
                ))
                .collect::<Vec<_>>()
        );
    }
}

mod tests {
    #![allow(unused_imports)]
    use super::*;

    #[test]
    fn element_to_string() {
        assert!(Element::Hydrogen.to_string() == "H")
    }

    #[test]
    fn element_from_string() {
        assert!(str::parse("H") == Ok(Element::Hydrogen));
        assert!(str::parse::<Element>("Foo").is_err());
    }
}