Skip to main content

gen_graph/
lib.rs

1use std::{
2    collections::{HashMap, HashSet, VecDeque},
3    fmt::{self, Debug},
4    hash::Hash,
5    iter::from_fn,
6    rc::Rc,
7};
8
9use gen_core::{
10    HashId, NodeIntervalBlock, PATH_END_NODE_ID, PATH_START_NODE_ID, PathBlock, Strand,
11    calculate_hash, is_end_node, is_start_node,
12};
13use interavl::IntervalTree as IT2;
14use intervaltree::IntervalTree;
15use petgraph::{
16    Direction,
17    graphmap::DiGraphMap,
18    prelude::EdgeRef,
19    visit::{
20        Dfs, GraphRef, IntoEdgeReferences, IntoEdges, IntoNeighbors, IntoNeighborsDirected,
21        NodeCount, Reversed,
22    },
23};
24use serde::{Deserialize, Serialize};
25use thiserror::Error;
26
27pub mod traits;
28pub use traits::MergeGraph;
29
30#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Deserialize, Serialize)]
31pub struct GraphNode {
32    pub node_id: HashId,
33    pub sequence_start: i64,
34    pub sequence_end: i64,
35}
36
37impl fmt::Display for GraphNode {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(
40            f,
41            "{}[{}-{}]",
42            self.node_id, self.sequence_start, self.sequence_end
43        )
44    }
45}
46
47impl GraphNode {
48    pub fn length(&self) -> i64 {
49        self.sequence_end - self.sequence_start
50    }
51}
52
53/// A slice of a single graph block: the block itself plus local start/end byte
54/// offsets within that block's sequence.  Middle blocks in a multi-block locus
55/// span the full block (`start = 0`, `end = block.length()`).
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
57pub struct GraphNodeSlice {
58    pub block: GraphNode,
59    /// Local start offset within the block's sequence slice (`0..block.length()`).
60    pub start: usize,
61    /// Local end offset, exclusive (`start..=block.length()`).
62    pub end: usize,
63    /// 5'→3' orientation of this slice.
64    pub strand: Strand,
65}
66
67impl GraphNodeSlice {
68    pub fn full(block: GraphNode, strand: Strand) -> Self {
69        Self {
70            block,
71            start: 0,
72            end: block.length() as usize,
73            strand,
74        }
75    }
76}
77
78pub type GenGraph = DiGraphMap<GraphNode, Vec<GraphEdge>>;
79pub type OperationGraph = DiGraphMap<HashId, ()>;
80
81#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Deserialize, Serialize)]
82pub struct GraphEdge {
83    pub edge_id: HashId,
84    pub source_strand: Strand,
85    pub target_strand: Strand,
86    pub chromosome_index: i64,
87    pub phased: i64,
88    pub created_on: i64,
89}
90
91/// A cursor within a GraphNode
92#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Deserialize, Serialize)]
93pub struct GraphNodePosition {
94    pub graph_node: GraphNode,
95    /// Distance from sequence_start of graph_node
96    pub offset: i64,
97}
98
99impl GraphNodePosition {
100    pub fn coordinate(&self) -> i64 {
101        self.graph_node.sequence_start + self.offset
102    }
103}
104
105#[derive(Debug, Error)]
106pub enum GraphError {
107    #[error("Distance {0} exceeds graph boundaries")]
108    OutOfBounds(i64),
109    #[error("No reachable position found from anchor")]
110    NoPath,
111}
112
113// #[derive(Debug)]
114// pub struct OperationGraph {
115//     pub graph: DiGraphMap<usize, ()>,
116//     max_node_id: usize,
117//     pub node_ids: HashMap<String, usize>,
118//     reverse_map: HashMap<usize, String>,
119// }
120
121// impl Default for OperationGraph {
122//     fn default() -> Self {
123//         Self::new()
124//     }
125// }
126
127// impl OperationGraph {
128//     pub fn new() -> Self {
129//         OperationGraph {
130//             graph: DiGraphMap::new(),
131//             max_node_id: HashId::convert_str("0"),
132//             node_ids: HashMap::new(),
133//             reverse_map: HashMap::new(),
134//         }
135//     }
136
137//     pub fn add_node(&mut self, hash_id: &str) -> usize {
138//         let node_id = *self.node_ids.entry(hash_id.to_string()).or_insert_with(|| {
139//             let node_id = self.max_node_id;
140//             self.reverse_map.insert(node_id, hash_id.to_string());
141//             self.graph.add_node(node_id);
142//             self.max_node_id += 1;
143//             node_id
144//         });
145//         node_id
146//     }
147
148//     pub fn remove_node(&mut self, node_id: usize) {
149//         self.graph.remove_node(node_id);
150//         if let Some(key) = self.reverse_map.remove(&node_id) {
151//             self.node_ids.remove(&key).unwrap();
152//         }
153//     }
154
155//     pub fn remove_key(&mut self, hash_id: &str) {
156//         if let Some(node_index) = self.node_ids.remove(hash_id) {
157//             self.graph.remove_node(node_index);
158//             self.reverse_map.remove(&node_index).unwrap();
159//         }
160//     }
161
162//     pub fn get_node(&self, node_id: &str) -> usize {
163//         self.node_ids[node_id]
164//     }
165
166//     pub fn get_key(&self, index: usize) -> String {
167//         self.reverse_map[&index].clone()
168//     }
169
170//     pub fn add_edge(&mut self, src: &str, target: &str) {
171//         let src_node_id = self.add_node(src);
172//         let target_node_id = self.add_node(target);
173//         self.graph.add_edge(src_node_id, target_node_id, ());
174//     }
175// }
176
177// hacked from https://docs.rs/petgraph/latest/src/petgraph/algo/simple_paths.rs.html#36-102 to support digraphmap
178
179pub fn all_simple_paths<G>(
180    graph: G,
181    from: G::NodeId,
182    to: G::NodeId,
183) -> impl Iterator<Item = Vec<G::NodeId>>
184where
185    G: NodeCount,
186    G: IntoNeighborsDirected,
187    G::NodeId: Eq + Hash,
188{
189    // list of visited nodes
190    let mut visited = vec![from];
191    // list of childs of currently exploring path nodes,
192    // last elem is list of childs of last visited node
193    let mut stack = vec![graph.neighbors_directed(from, Direction::Outgoing)];
194
195    from_fn(move || {
196        while let Some(children) = stack.last_mut() {
197            if let Some(child) = children.next() {
198                if child == to {
199                    let path = visited.iter().cloned().chain(Some(to)).collect::<_>();
200                    return Some(path);
201                } else if !visited.contains(&child) {
202                    visited.push(child);
203                    stack.push(graph.neighbors_directed(child, Direction::Outgoing));
204                }
205            } else {
206                stack.pop();
207                visited.pop();
208            }
209        }
210        None
211    })
212}
213
214pub fn all_intermediate_edges<G>(
215    graph: G,
216    from: G::NodeId,
217    to: G::NodeId,
218) -> Vec<<G as IntoEdgeReferences>::EdgeRef>
219where
220    G: GraphRef + IntoEdges + petgraph::visit::IntoNeighborsDirected + petgraph::visit::Visitable,
221    G::NodeId: Eq + Hash + std::fmt::Display,
222{
223    let mut outgoing_nodes = HashSet::new();
224    outgoing_nodes.insert(from);
225    let mut dfs_outbound = Dfs::new(graph, from);
226
227    while let Some(outgoing_node) = dfs_outbound.next(graph) {
228        outgoing_nodes.insert(outgoing_node);
229    }
230
231    // This is a standard graph algorithm trick.  To get all nodes on paths from a source s to a
232    // target t, but not any other nodes, first find all nodes reachable from s.  Then reverse all
233    // the edges in the graph and find all nodes reachable from t.  The nodes in common between
234    // those two sets are the exactly the ones on some path from s to t.
235    let reversed_graph = Reversed(&graph);
236    let mut incoming_nodes = HashSet::new();
237    incoming_nodes.insert(to);
238    let mut dfs_inbound = Dfs::new(reversed_graph, to);
239    while let Some(incoming_node) = dfs_inbound.next(reversed_graph) {
240        incoming_nodes.insert(incoming_node);
241    }
242
243    let common_nodes: HashSet<&<G as petgraph::visit::GraphBase>::NodeId> =
244        outgoing_nodes.intersection(&incoming_nodes).collect();
245    let mut common_edgerefs = vec![];
246    for edge in graph.edge_references() {
247        let (source, target) = (edge.source(), edge.target());
248
249        if common_nodes.contains(&source) && common_nodes.contains(&target) {
250            common_edgerefs.push(edge);
251        }
252    }
253
254    common_edgerefs
255}
256
257pub fn all_simple_paths_by_edge<G>(
258    graph: G,
259    from: G::NodeId,
260    to: G::NodeId,
261) -> impl Iterator<Item = Vec<G::EdgeRef>>
262where
263    G: NodeCount + IntoEdges,
264    G: IntoNeighborsDirected,
265    G::NodeId: Eq + Hash,
266{
267    // list of visited nodes
268    let mut visited = vec![from];
269    // list of childs of currently exploring path nodes,
270    // last elem is list of childs of last visited node
271    let mut path: Vec<G::EdgeRef> = vec![];
272    let mut stack = vec![graph.edges(from)];
273
274    from_fn(move || {
275        while let Some(edges) = stack.last_mut() {
276            if let Some(edge) = edges.next() {
277                let target = edge.target();
278                if target == to {
279                    let a_path = path.iter().cloned().chain(Some(edge)).collect::<_>();
280                    return Some(a_path);
281                } else if !visited.contains(&target) {
282                    path.push(edge);
283                    visited.push(target);
284                    stack.push(graph.edges(target));
285                }
286            } else {
287                stack.pop();
288                path.pop();
289                visited.pop();
290            }
291        }
292        None
293    })
294}
295
296pub fn all_reachable_nodes<G>(graph: G, nodes: &[G::NodeId]) -> HashSet<G::NodeId>
297where
298    G: GraphRef + IntoNeighbors,
299    G::NodeId: Eq + Hash + Debug,
300{
301    let mut stack = VecDeque::new();
302    let mut reachable = HashSet::new();
303    for node in nodes.iter() {
304        stack.push_front(*node);
305        reachable.insert(*node);
306        while let Some(nx) = stack.pop_front() {
307            for succ in graph.neighbors(nx) {
308                if !reachable.contains(&succ) {
309                    reachable.insert(succ);
310                    stack.push_back(succ);
311                }
312            }
313        }
314    }
315    reachable
316}
317
318pub fn flatten_to_interval_tree(
319    graph: &GenGraph,
320    remove_ambiguous_positions: bool,
321) -> IntervalTree<i64, NodeIntervalBlock> {
322    #[derive(Clone, Debug, Ord, PartialOrd, Eq, Hash, PartialEq)]
323    struct NodeP {
324        x: i64,
325        y: i64,
326    }
327    let mut excluded_nodes = HashSet::new();
328    let mut node_tree: HashMap<HashId, IT2<NodeP, HashId>> = HashMap::new();
329
330    let mut start_nodes = vec![];
331    let mut end_nodes = vec![];
332    for node in graph.nodes() {
333        if is_start_node(node.node_id) {
334            start_nodes.push(node);
335        }
336        if is_end_node(node.node_id) {
337            end_nodes.push(node);
338        }
339    }
340
341    let mut spans: HashSet<NodeIntervalBlock> = HashSet::new();
342
343    for start in start_nodes.iter() {
344        for end_node in end_nodes.iter() {
345            for path in all_simple_paths_by_edge(&graph, *start, *end_node) {
346                let mut offset = 0;
347                for (source_node, target_node, edges) in path.iter() {
348                    let block_len = source_node.length();
349                    let node_start = offset;
350                    let node_end = offset + block_len;
351                    // Use the first edge in the vector for strand information
352                    let edge = &edges[0];
353                    spans.insert(NodeIntervalBlock {
354                        node_id: source_node.node_id,
355                        start: node_start,
356                        end: node_end,
357                        sequence_start: source_node.sequence_start,
358                        sequence_end: source_node.sequence_end,
359                        strand: edge.source_strand,
360                    });
361                    spans.insert(NodeIntervalBlock {
362                        node_id: target_node.node_id,
363                        start: node_end,
364                        end: node_end + target_node.length(),
365                        sequence_start: target_node.sequence_start,
366                        sequence_end: target_node.sequence_end,
367                        strand: edge.target_strand,
368                    });
369                    if remove_ambiguous_positions {
370                        for (node_id, node_range) in [
371                            (
372                                source_node.node_id,
373                                NodeP {
374                                    x: node_start,
375                                    y: source_node.sequence_start,
376                                }..NodeP {
377                                    x: node_end,
378                                    y: source_node.sequence_end,
379                                },
380                            ),
381                            (
382                                target_node.node_id,
383                                NodeP {
384                                    x: node_end,
385                                    y: target_node.sequence_start,
386                                }..NodeP {
387                                    x: node_end + target_node.length(),
388                                    y: target_node.sequence_end,
389                                },
390                            ),
391                        ] {
392                            // TODO; This could be a bit better by trying to conserve subregions
393                            // within a node that are not ambiguous instead of kicking the entire
394                            // node out.
395                            node_tree
396                                .entry(node_id)
397                                .and_modify(|tree| {
398                                    for (stored_range, _stored_node_id) in
399                                        tree.iter_overlaps(&node_range)
400                                    {
401                                        if *stored_range != node_range {
402                                            excluded_nodes.insert(node_id);
403                                            break;
404                                        }
405                                    }
406                                    tree.insert(node_range.clone(), node_id);
407                                })
408                                .or_insert_with(|| {
409                                    let mut t = IT2::default();
410                                    t.insert(node_range.clone(), node_id);
411                                    t
412                                });
413                        }
414                    }
415                    offset += block_len;
416                }
417            }
418        }
419    }
420
421    let segment_length = spans
422        .iter()
423        .filter(|block| block.node_id != PATH_START_NODE_ID && block.node_id != PATH_END_NODE_ID)
424        .map(|block| block.end)
425        .max()
426        .unwrap_or(0);
427    let tree: IntervalTree<i64, NodeIntervalBlock> = spans
428        .iter()
429        .filter(|block| !remove_ambiguous_positions || !excluded_nodes.contains(&block.node_id))
430        .map(|block| {
431            let block = normalize_terminal_block(block, segment_length);
432            (block.start..block.end, block)
433        })
434        .collect();
435    tree
436}
437
438pub fn graph_from_interval_tree(tree: &IntervalTree<i64, NodeIntervalBlock>) -> GenGraph {
439    let mut graph = GenGraph::new();
440    let tree_length = tree
441        .iter()
442        .map(|item| &item.value)
443        .filter(|block| block.node_id != PATH_START_NODE_ID && block.node_id != PATH_END_NODE_ID)
444        .map(|block| block.end)
445        .max()
446        .unwrap_or(0);
447    let mut blocks: Vec<NodeIntervalBlock> = tree
448        .iter()
449        .map(|item| normalize_terminal_block(&item.value, tree_length))
450        .collect();
451    blocks.sort_by_key(|b| b.start);
452
453    for block in &blocks {
454        graph.add_node(GraphNode {
455            node_id: block.node_id,
456            sequence_start: block.sequence_start,
457            sequence_end: block.sequence_end,
458        });
459    }
460
461    for window in blocks.windows(2) {
462        let source = &window[0];
463        let target = &window[1];
464        let source_node = GraphNode {
465            node_id: source.node_id,
466            sequence_start: source.sequence_start,
467            sequence_end: source.sequence_end,
468        };
469        let target_node = GraphNode {
470            node_id: target.node_id,
471            sequence_start: target.sequence_start,
472            sequence_end: target.sequence_end,
473        };
474        let edge_id = HashId(calculate_hash(&format!(
475            "{}:{}->{}:{}",
476            source.node_id, source.sequence_end, target.node_id, target.sequence_start
477        )));
478        let graph_edge = GraphEdge {
479            edge_id,
480            source_strand: source.strand,
481            target_strand: target.strand,
482            chromosome_index: 0,
483            phased: 0,
484            created_on: 0,
485        };
486        graph.add_edge(source_node, target_node, vec![graph_edge]);
487    }
488
489    graph
490}
491
492fn normalize_terminal_block(block: &NodeIntervalBlock, total_length: i64) -> NodeIntervalBlock {
493    if block.node_id == PATH_START_NODE_ID {
494        NodeIntervalBlock {
495            start: i64::MIN + 1,
496            end: 0,
497            ..*block
498        }
499    } else if block.node_id == PATH_END_NODE_ID {
500        NodeIntervalBlock {
501            start: total_length,
502            end: i64::MAX - 1,
503            ..*block
504        }
505    } else {
506        *block
507    }
508}
509
510pub fn project_path(graph: &GenGraph, path_blocks: &[PathBlock]) -> Vec<(GraphNode, Strand)> {
511    // When a path is created, it will refer to node positions in the graph as it exists then.
512    // If the graph is then updated, the path nodes may be split and the graph no longer contains
513    // the corresponding nodes in the initial path. This takes the initial path and identifies the
514    // set of nodes in the current graph corresponding to the path using a depth first search
515    // approach.
516
517    #[derive(Debug)]
518    struct PathNode {
519        node: (GraphNode, Strand),
520        // path_index serves as a pointer at which path block the added node was at. This is because
521        // in a DFS, we may reset to a previous position for a search and need to reset the position
522        // in the path as well.
523        path_index: usize,
524        prev: Option<Rc<PathNode>>,
525    }
526
527    let start_nodes = graph
528        .nodes()
529        .filter(|node| node.node_id == PATH_START_NODE_ID)
530        .collect::<Vec<GraphNode>>();
531    let start_node = start_nodes.first().unwrap();
532
533    let mut final_path = vec![];
534    let mut stack: VecDeque<Rc<PathNode>> = VecDeque::new();
535    let mut visited: HashSet<(GraphNode, Strand)> = HashSet::new();
536    let mut path_index = 0;
537    let mut current_pos;
538
539    // Start with the initial path containing only the start node
540    stack.push_back(Rc::new(PathNode {
541        node: (*start_node, Strand::Forward),
542        path_index,
543        prev: None,
544    }));
545
546    while let Some(current_node) = stack.pop_back() {
547        let current = current_node.node;
548        let mut current_block = &path_blocks[current_node.path_index];
549
550        if !visited.insert(current) {
551            continue;
552        }
553
554        // if current completes the current block, move to the next path block
555        if current.0.sequence_end == current_block.sequence_end {
556            path_index += 1;
557            if path_index < path_blocks.len() {
558                current_block = &path_blocks[path_index];
559                current_pos = current_block.sequence_start;
560            } else {
561                // we're done, path_block is fully consumed
562                let mut path = vec![];
563                let mut path_ref = Some(Rc::clone(&current_node));
564                while let Some(pn) = path_ref {
565                    path.push(pn.node);
566                    path_ref = pn.prev.clone();
567                }
568                final_path = path.into_iter().rev().collect();
569                break;
570            }
571        } else {
572            current_pos = current.0.sequence_end;
573        }
574
575        for (_src, neighbor, edges) in graph.edges(current.0) {
576            // Use the first edge in the vector for strand information
577            if neighbor.node_id == current_block.node_id
578                && neighbor.sequence_start == current_pos
579                && edges
580                    .iter()
581                    .any(|edge| current_block.strand == edge.target_strand)
582            {
583                stack.push_back(Rc::new(PathNode {
584                    node: (neighbor, current_block.strand),
585                    path_index,
586                    prev: Some(Rc::clone(&current_node)),
587                }));
588            }
589        }
590    }
591    final_path
592}
593
594/// Find the articulation points of a directed graph using a non-recursive approach
595/// This is a modified version of the algorithm found here:
596/// https://en.wikipedia.org/wiki/Biconnected_component#Articulation_points
597pub fn find_articulation_points(graph: &GenGraph) -> Vec<GraphNode> {
598    let mut articulation_points: Vec<GraphNode> = Vec::new();
599    let mut discovery_time: HashMap<GraphNode, usize> = HashMap::new();
600    let mut low: HashMap<GraphNode, usize> = HashMap::new();
601    let mut parent: HashMap<GraphNode, Option<GraphNode>> = HashMap::new();
602    let mut time = 0;
603
604    for node in graph.nodes() {
605        if !discovery_time.contains_key(&node) {
606            let mut stack = vec![(node, None, true)];
607            while let Some((u, p, is_first_time)) = stack.pop() {
608                if is_first_time {
609                    // Initialize discovery time and low value
610                    discovery_time.insert(u, time);
611                    low.insert(u, time);
612                    time += 1;
613                    parent.insert(u, p);
614
615                    // Push the node back with is_first_time = false to process after its neighbors
616                    stack.push((u, p, false));
617
618                    // Consider both incoming and outgoing edges as undirected
619                    let neighbors: Vec<_> = graph
620                        .neighbors_directed(u, Direction::Outgoing)
621                        .chain(graph.neighbors_directed(u, Direction::Incoming))
622                        .collect();
623
624                    for v in neighbors {
625                        if !discovery_time.contains_key(&v) {
626                            stack.push((v, Some(u), true));
627                        } else if Some(v) != p {
628                            // Update low[u] if v is not parent
629                            let current_low = low.get(&u).cloned().unwrap_or(usize::MAX);
630                            let v_disc = discovery_time.get(&v).cloned().unwrap_or(usize::MAX);
631                            low.insert(u, current_low.min(v_disc));
632                        }
633                    }
634                } else {
635                    // Post-processing after visiting all neighbors
636                    let mut is_articulation = false;
637                    let mut child_count = 0;
638
639                    let neighbors: Vec<_> = graph
640                        .neighbors_directed(u, Direction::Outgoing)
641                        .chain(graph.neighbors_directed(u, Direction::Incoming))
642                        .collect();
643
644                    for v in neighbors {
645                        if parent.get(&v).cloned() == Some(Some(u)) {
646                            child_count += 1;
647                            let v_low = low.get(&v).cloned().unwrap_or(usize::MAX);
648                            let u_disc = discovery_time.get(&u).cloned().unwrap_or(usize::MAX);
649                            if v_low >= u_disc {
650                                is_articulation = true;
651                            }
652                            let current_low = low.get(&u).cloned().unwrap_or(usize::MAX);
653                            let v_low = low.get(&v).cloned().unwrap_or(usize::MAX);
654                            low.insert(u, current_low.min(v_low));
655                        } else if Some(v) != parent.get(&u).cloned().unwrap_or(None) {
656                            let v_disc = discovery_time.get(&v).cloned().unwrap_or(usize::MAX);
657                            let current_low = low.get(&u).cloned().unwrap_or(usize::MAX);
658                            low.insert(u, current_low.min(v_disc));
659                        }
660                    }
661
662                    let u_parent = parent.get(&u).cloned().unwrap_or(None);
663                    if (u_parent.is_some() && is_articulation)
664                        || (u_parent.is_none() && child_count > 1)
665                    {
666                        articulation_points.push(u);
667                    }
668                }
669            }
670        }
671    }
672
673    articulation_points.sort();
674    articulation_points.dedup();
675    articulation_points
676}
677
678#[cfg(test)]
679mod tests {
680    use std::collections::HashSet;
681
682    use petgraph::graphmap::DiGraphMap;
683
684    use super::*;
685
686    #[test]
687    fn test_path_graph() {
688        let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
689        graph.add_node(1);
690        graph.add_node(2);
691        graph.add_node(3);
692
693        graph.add_edge(1, 2, ());
694        graph.add_edge(2, 3, ());
695
696        let paths = all_simple_paths(&graph, 1, 3).collect::<Vec<Vec<i64>>>();
697        assert_eq!(paths.len(), 1);
698        let path = paths.first().unwrap().clone();
699        assert_eq!(path, vec![1, 2, 3]);
700    }
701
702    #[test]
703    fn test_get_simple_paths_by_edge() {
704        let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
705        graph.add_node(1);
706        graph.add_node(2);
707        graph.add_node(3);
708        graph.add_node(4);
709        graph.add_node(5);
710        graph.add_node(6);
711        graph.add_node(7);
712        graph.add_node(8);
713        graph.add_node(9);
714
715        graph.add_edge(1, 2, ());
716        graph.add_edge(2, 3, ());
717        graph.add_edge(3, 4, ());
718        graph.add_edge(4, 5, ());
719        graph.add_edge(2, 6, ());
720        graph.add_edge(6, 7, ());
721        graph.add_edge(7, 4, ());
722        graph.add_edge(6, 8, ());
723        graph.add_edge(8, 7, ());
724
725        let edge_path =
726            all_simple_paths_by_edge(&graph, 1, 5).collect::<Vec<Vec<(i64, i64, &())>>>();
727        assert_eq!(
728            edge_path,
729            vec![
730                vec![(1, 2, &()), (2, 3, &()), (3, 4, &()), (4, 5, &())],
731                vec![
732                    (1, 2, &()),
733                    (2, 6, &()),
734                    (6, 7, &()),
735                    (7, 4, &()),
736                    (4, 5, &())
737                ],
738                vec![
739                    (1, 2, &()),
740                    (2, 6, &()),
741                    (6, 8, &()),
742                    (8, 7, &()),
743                    (7, 4, &()),
744                    (4, 5, &())
745                ]
746            ]
747        );
748    }
749
750    #[test]
751    fn test_two_path_graph() {
752        let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
753        graph.add_node(1);
754        graph.add_node(2);
755        graph.add_node(3);
756        graph.add_node(4);
757
758        graph.add_edge(1, 2, ());
759        graph.add_edge(1, 3, ());
760        graph.add_edge(2, 4, ());
761        graph.add_edge(3, 4, ());
762
763        let paths = all_simple_paths(&graph, 1, 4).collect::<Vec<Vec<i64>>>();
764        assert_eq!(paths.len(), 2);
765        assert_eq!(
766            HashSet::<Vec<i64>>::from_iter::<Vec<Vec<i64>>>(paths),
767            HashSet::from_iter(vec![vec![1, 2, 4], vec![1, 3, 4]])
768        );
769    }
770
771    #[test]
772    fn test_two_by_two_combinatorial_graph() {
773        let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
774        graph.add_node(1);
775        graph.add_node(2);
776        graph.add_node(3);
777        graph.add_node(4);
778        graph.add_node(5);
779        graph.add_node(6);
780        graph.add_node(7);
781
782        graph.add_edge(1, 2, ());
783        graph.add_edge(1, 3, ());
784        graph.add_edge(2, 4, ());
785        graph.add_edge(3, 4, ());
786        graph.add_edge(4, 5, ());
787        graph.add_edge(4, 6, ());
788        graph.add_edge(5, 7, ());
789        graph.add_edge(6, 7, ());
790
791        let paths = all_simple_paths(&graph, 1, 7).collect::<Vec<Vec<i64>>>();
792        assert_eq!(paths.len(), 4);
793        assert_eq!(
794            HashSet::<Vec<i64>>::from_iter::<Vec<Vec<i64>>>(paths),
795            HashSet::from_iter(vec![
796                vec![1, 2, 4, 5, 7],
797                vec![1, 3, 4, 5, 7],
798                vec![1, 2, 4, 6, 7],
799                vec![1, 3, 4, 6, 7]
800            ])
801        );
802    }
803
804    #[test]
805    fn test_three_by_three_combinatorial_graph() {
806        let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
807        graph.add_node(1);
808        graph.add_node(2);
809        graph.add_node(3);
810        graph.add_node(4);
811        graph.add_node(5);
812        graph.add_node(6);
813        graph.add_node(7);
814        graph.add_node(8);
815        graph.add_node(9);
816
817        graph.add_edge(1, 2, ());
818        graph.add_edge(1, 3, ());
819        graph.add_edge(1, 4, ());
820        graph.add_edge(2, 5, ());
821        graph.add_edge(3, 5, ());
822        graph.add_edge(4, 5, ());
823        graph.add_edge(5, 6, ());
824        graph.add_edge(5, 7, ());
825        graph.add_edge(5, 8, ());
826        graph.add_edge(6, 9, ());
827        graph.add_edge(7, 9, ());
828        graph.add_edge(8, 9, ());
829
830        let paths = all_simple_paths(&graph, 1, 9).collect::<Vec<Vec<i64>>>();
831        assert_eq!(paths.len(), 9);
832        let expected_paths = vec![
833            vec![1, 2, 5, 6, 9],
834            vec![1, 3, 5, 6, 9],
835            vec![1, 4, 5, 6, 9],
836            vec![1, 2, 5, 7, 9],
837            vec![1, 3, 5, 7, 9],
838            vec![1, 4, 5, 7, 9],
839            vec![1, 2, 5, 8, 9],
840            vec![1, 3, 5, 8, 9],
841            vec![1, 4, 5, 8, 9],
842        ];
843        assert_eq!(
844            HashSet::<Vec<i64>>::from_iter::<Vec<Vec<i64>>>(paths),
845            HashSet::from_iter(expected_paths)
846        );
847    }
848
849    #[test]
850    fn test_super_bubble_path() {
851        // This graph looks like this:
852        //              8
853        //            /  \
854        //          6  -> 7
855        //         /        \
856        //    1 -> 2 -> 3 -> 4 -> 5
857        //
858        //  We ensure that we capture all 3 paths from 1 -> 5
859        let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
860        graph.add_node(1);
861        graph.add_node(2);
862        graph.add_node(3);
863        graph.add_node(4);
864        graph.add_node(5);
865        graph.add_node(6);
866        graph.add_node(7);
867        graph.add_node(8);
868        graph.add_node(9);
869
870        graph.add_edge(1, 2, ());
871        graph.add_edge(2, 3, ());
872        graph.add_edge(3, 4, ());
873        graph.add_edge(4, 5, ());
874        graph.add_edge(2, 6, ());
875        graph.add_edge(6, 7, ());
876        graph.add_edge(7, 4, ());
877        graph.add_edge(6, 8, ());
878        graph.add_edge(8, 7, ());
879
880        let paths = all_simple_paths(&graph, 1, 5).collect::<Vec<Vec<i64>>>();
881        assert_eq!(
882            HashSet::<Vec<i64>>::from_iter::<Vec<Vec<i64>>>(paths),
883            HashSet::from_iter(vec![
884                vec![1, 2, 3, 4, 5],
885                vec![1, 2, 6, 7, 4, 5],
886                vec![1, 2, 6, 8, 7, 4, 5]
887            ])
888        );
889    }
890
891    fn make_block(
892        node_id: &str,
893        start: i64,
894        end: i64,
895        seq_start: i64,
896        seq_end: i64,
897    ) -> (std::ops::Range<i64>, NodeIntervalBlock) {
898        (
899            start..end,
900            NodeIntervalBlock {
901                node_id: HashId::convert_str(node_id),
902                start,
903                end,
904                sequence_start: seq_start,
905                sequence_end: seq_end,
906                strand: Strand::Forward,
907            },
908        )
909    }
910
911    #[test]
912    fn test_graph_from_interval_tree_length_1() {
913        let tree: IntervalTree<i64, NodeIntervalBlock> =
914            vec![make_block("node-a", 0, 5, 0, 5)].into_iter().collect();
915
916        let graph = graph_from_interval_tree(&tree);
917
918        assert_eq!(graph.node_count(), 1);
919        assert_eq!(graph.edge_count(), 0);
920
921        let node = GraphNode {
922            node_id: HashId::convert_str("node-a"),
923            sequence_start: 0,
924            sequence_end: 5,
925        };
926        assert!(graph.contains_node(node));
927    }
928
929    #[test]
930    fn test_graph_from_interval_tree_length_2() {
931        let tree: IntervalTree<i64, NodeIntervalBlock> = vec![
932            make_block("node-a", 0, 5, 0, 5),
933            make_block("node-b", 5, 10, 0, 5),
934        ]
935        .into_iter()
936        .collect();
937
938        let graph = graph_from_interval_tree(&tree);
939
940        assert_eq!(graph.node_count(), 2);
941        assert_eq!(graph.edge_count(), 1);
942
943        let node_a = GraphNode {
944            node_id: HashId::convert_str("node-a"),
945            sequence_start: 0,
946            sequence_end: 5,
947        };
948        let node_b = GraphNode {
949            node_id: HashId::convert_str("node-b"),
950            sequence_start: 0,
951            sequence_end: 5,
952        };
953        assert!(graph.contains_node(node_a));
954        assert!(graph.contains_node(node_b));
955        assert!(graph.contains_edge(node_a, node_b));
956
957        let neighbors: Vec<_> = graph.neighbors(node_a).collect();
958        assert_eq!(neighbors, vec![node_b]);
959    }
960
961    #[test]
962    fn test_graph_from_interval_tree_length_3() {
963        let tree: IntervalTree<i64, NodeIntervalBlock> = vec![
964            make_block("node-a", 0, 5, 0, 5),
965            make_block("node-b", 5, 10, 0, 5),
966            make_block("node-c", 10, 15, 0, 5),
967        ]
968        .into_iter()
969        .collect();
970
971        let graph = graph_from_interval_tree(&tree);
972
973        assert_eq!(graph.node_count(), 3);
974        assert_eq!(graph.edge_count(), 2);
975
976        let node_a = GraphNode {
977            node_id: HashId::convert_str("node-a"),
978            sequence_start: 0,
979            sequence_end: 5,
980        };
981        let node_b = GraphNode {
982            node_id: HashId::convert_str("node-b"),
983            sequence_start: 0,
984            sequence_end: 5,
985        };
986        let node_c = GraphNode {
987            node_id: HashId::convert_str("node-c"),
988            sequence_start: 0,
989            sequence_end: 5,
990        };
991
992        assert!(graph.contains_edge(node_a, node_b));
993        assert!(graph.contains_edge(node_b, node_c));
994        assert!(!graph.contains_edge(node_a, node_c));
995
996        let a_neighbors: Vec<_> = graph.neighbors(node_a).collect();
997        assert_eq!(a_neighbors, vec![node_b]);
998
999        let b_incoming: Vec<_> = graph
1000            .neighbors_directed(node_b, petgraph::Direction::Incoming)
1001            .collect();
1002        assert_eq!(b_incoming, vec![node_a]);
1003
1004        let b_outgoing: Vec<_> = graph
1005            .neighbors_directed(node_b, petgraph::Direction::Outgoing)
1006            .collect();
1007        assert_eq!(b_outgoing, vec![node_c]);
1008    }
1009
1010    #[test]
1011    fn test_graph_from_interval_tree_length_4() {
1012        let tree: IntervalTree<i64, NodeIntervalBlock> = vec![
1013            make_block("node-a", 0, 3, 0, 3),
1014            make_block("node-b", 3, 8, 0, 5),
1015            make_block("node-c", 8, 11, 0, 3),
1016            make_block("node-d", 11, 16, 0, 5),
1017        ]
1018        .into_iter()
1019        .collect();
1020
1021        let graph = graph_from_interval_tree(&tree);
1022
1023        assert_eq!(graph.node_count(), 4);
1024        assert_eq!(graph.edge_count(), 3);
1025
1026        let node_a = GraphNode {
1027            node_id: HashId::convert_str("node-a"),
1028            sequence_start: 0,
1029            sequence_end: 3,
1030        };
1031        let node_b = GraphNode {
1032            node_id: HashId::convert_str("node-b"),
1033            sequence_start: 0,
1034            sequence_end: 5,
1035        };
1036        let node_c = GraphNode {
1037            node_id: HashId::convert_str("node-c"),
1038            sequence_start: 0,
1039            sequence_end: 3,
1040        };
1041        let node_d = GraphNode {
1042            node_id: HashId::convert_str("node-d"),
1043            sequence_start: 0,
1044            sequence_end: 5,
1045        };
1046
1047        assert!(graph.contains_edge(node_a, node_b));
1048        assert!(graph.contains_edge(node_b, node_c));
1049        assert!(graph.contains_edge(node_c, node_d));
1050
1051        // Verify no cross edges
1052        assert!(!graph.contains_edge(node_a, node_c));
1053        assert!(!graph.contains_edge(node_a, node_d));
1054        assert!(!graph.contains_edge(node_b, node_d));
1055
1056        // Verify node properties
1057        assert_eq!(node_a.length(), 3);
1058        assert_eq!(node_b.length(), 5);
1059        assert_eq!(node_c.length(), 3);
1060        assert_eq!(node_d.length(), 5);
1061
1062        // Verify linear chain: A only has outgoing to B, D only has incoming from C
1063        let a_out: Vec<_> = graph
1064            .neighbors_directed(node_a, petgraph::Direction::Outgoing)
1065            .collect();
1066        assert_eq!(a_out, vec![node_b]);
1067
1068        let a_in: Vec<_> = graph
1069            .neighbors_directed(node_a, petgraph::Direction::Incoming)
1070            .collect();
1071        assert!(a_in.is_empty());
1072
1073        let d_out: Vec<_> = graph
1074            .neighbors_directed(node_d, petgraph::Direction::Outgoing)
1075            .collect();
1076        assert!(d_out.is_empty());
1077
1078        let d_in: Vec<_> = graph
1079            .neighbors_directed(node_d, petgraph::Direction::Incoming)
1080            .collect();
1081        assert_eq!(d_in, vec![node_c]);
1082    }
1083
1084    #[test]
1085    fn test_graph_from_interval_tree_with_fragments() {
1086        // Nodes can be fragments: different (seq_start, seq_end) for the same node_id
1087        let tree: IntervalTree<i64, NodeIntervalBlock> = vec![
1088            make_block("node-a", 0, 3, 0, 3),  // full node A
1089            make_block("node-b", 3, 5, 1, 3),  // fragment of B (middle bases)
1090            make_block("node-c", 6, 11, 0, 5), // full node C
1091        ]
1092        .into_iter()
1093        .collect();
1094
1095        let graph = graph_from_interval_tree(&tree);
1096
1097        assert_eq!(graph.node_count(), 3);
1098        assert_eq!(graph.edge_count(), 2);
1099
1100        let node_a = GraphNode {
1101            node_id: HashId::convert_str("node-a"),
1102            sequence_start: 0,
1103            sequence_end: 3,
1104        };
1105        let node_b = GraphNode {
1106            node_id: HashId::convert_str("node-b"),
1107            sequence_start: 1,
1108            sequence_end: 3,
1109        };
1110        let node_c = GraphNode {
1111            node_id: HashId::convert_str("node-c"),
1112            sequence_start: 0,
1113            sequence_end: 5,
1114        };
1115
1116        assert_eq!(node_b.length(), 2);
1117        assert!(graph.contains_edge(node_a, node_b));
1118        assert!(graph.contains_edge(node_b, node_c));
1119    }
1120
1121    #[test]
1122    fn test_graph_from_interval_tree_keeps_terminals() {
1123        let tree: IntervalTree<i64, NodeIntervalBlock> = vec![
1124            (
1125                i64::MIN + 1..0,
1126                NodeIntervalBlock {
1127                    node_id: PATH_START_NODE_ID,
1128                    start: i64::MIN + 1,
1129                    end: 0,
1130                    sequence_start: 0,
1131                    sequence_end: 0,
1132                    strand: Strand::Forward,
1133                },
1134            ),
1135            make_block("node-a", 0, 5, 0, 5),
1136            make_block("node-b", 5, 10, 0, 5),
1137            (
1138                10..i64::MAX - 1,
1139                NodeIntervalBlock {
1140                    node_id: PATH_END_NODE_ID,
1141                    start: 10,
1142                    end: i64::MAX - 1,
1143                    sequence_start: 0,
1144                    sequence_end: 0,
1145                    strand: Strand::Forward,
1146                },
1147            ),
1148        ]
1149        .into_iter()
1150        .collect();
1151
1152        let graph = graph_from_interval_tree(&tree);
1153
1154        assert_eq!(graph.node_count(), 4);
1155        assert_eq!(graph.edge_count(), 3);
1156
1157        let start_node = GraphNode {
1158            node_id: PATH_START_NODE_ID,
1159            sequence_start: 0,
1160            sequence_end: 0,
1161        };
1162        let node_a = GraphNode {
1163            node_id: HashId::convert_str("node-a"),
1164            sequence_start: 0,
1165            sequence_end: 5,
1166        };
1167        let node_b = GraphNode {
1168            node_id: HashId::convert_str("node-b"),
1169            sequence_start: 0,
1170            sequence_end: 5,
1171        };
1172        let end_node = GraphNode {
1173            node_id: PATH_END_NODE_ID,
1174            sequence_start: 0,
1175            sequence_end: 0,
1176        };
1177        assert!(graph.contains_node(start_node));
1178        assert!(graph.contains_node(node_a));
1179        assert!(graph.contains_node(node_b));
1180        assert!(graph.contains_node(end_node));
1181        assert!(graph.contains_edge(start_node, node_a));
1182        assert!(graph.contains_edge(node_a, node_b));
1183        assert!(graph.contains_edge(node_b, end_node));
1184    }
1185
1186    #[test]
1187    fn test_flatten_to_interval_tree_normalizes_terminal_bounds() {
1188        let start_node = GraphNode {
1189            node_id: PATH_START_NODE_ID,
1190            sequence_start: 0,
1191            sequence_end: 0,
1192        };
1193        let node_a = GraphNode {
1194            node_id: HashId::convert_str("node-a"),
1195            sequence_start: 0,
1196            sequence_end: 5,
1197        };
1198        let end_node = GraphNode {
1199            node_id: PATH_END_NODE_ID,
1200            sequence_start: 0,
1201            sequence_end: 0,
1202        };
1203        let mut graph = GenGraph::new();
1204        graph.add_edge(
1205            start_node,
1206            node_a,
1207            vec![GraphEdge {
1208                edge_id: HashId::convert_str("edge-start-a"),
1209                source_strand: Strand::Forward,
1210                target_strand: Strand::Forward,
1211                chromosome_index: 0,
1212                phased: 0,
1213                created_on: 0,
1214            }],
1215        );
1216        graph.add_edge(
1217            node_a,
1218            end_node,
1219            vec![GraphEdge {
1220                edge_id: HashId::convert_str("edge-a-end"),
1221                source_strand: Strand::Forward,
1222                target_strand: Strand::Forward,
1223                chromosome_index: 0,
1224                phased: 0,
1225                created_on: 0,
1226            }],
1227        );
1228
1229        let tree = flatten_to_interval_tree(&graph, false);
1230        let start_block = tree
1231            .iter()
1232            .map(|item| item.value)
1233            .find(|block| block.node_id == PATH_START_NODE_ID)
1234            .expect("should contain start terminal block");
1235        let end_block = tree
1236            .iter()
1237            .map(|item| item.value)
1238            .find(|block| block.node_id == PATH_END_NODE_ID)
1239            .expect("should contain end terminal block");
1240
1241        assert_eq!(start_block.start, i64::MIN + 1);
1242        assert_eq!(start_block.end, 0);
1243        assert_eq!(end_block.start, 5);
1244        assert_eq!(end_block.end, i64::MAX - 1);
1245    }
1246
1247    #[test]
1248    fn test_finds_all_reachable_nodes() {
1249        //
1250        //   1 -> 2 -> 3 -> 4 -> 5
1251        //           /
1252        //   6 -> 7
1253        //
1254        let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
1255        graph.add_node(1);
1256        graph.add_node(2);
1257        graph.add_node(3);
1258        graph.add_node(4);
1259        graph.add_node(5);
1260        graph.add_node(6);
1261        graph.add_node(7);
1262
1263        graph.add_edge(1, 2, ());
1264        graph.add_edge(2, 3, ());
1265        graph.add_edge(3, 4, ());
1266        graph.add_edge(4, 5, ());
1267        graph.add_edge(6, 7, ());
1268        graph.add_edge(7, 3, ());
1269
1270        assert_eq!(
1271            all_reachable_nodes(&graph, &[1]),
1272            HashSet::from_iter(vec![1, 2, 3, 4, 5])
1273        );
1274
1275        assert_eq!(
1276            all_reachable_nodes(&graph, &[1, 6]),
1277            HashSet::from_iter(vec![1, 2, 3, 4, 5, 6, 7])
1278        );
1279
1280        assert_eq!(
1281            all_reachable_nodes(&graph, &[3]),
1282            HashSet::from_iter(vec![3, 4, 5])
1283        );
1284
1285        assert_eq!(
1286            all_reachable_nodes(&graph, &[5]),
1287            HashSet::from_iter(vec![5])
1288        );
1289    }
1290
1291    mod test_all_intermediate_edges {
1292        use super::*;
1293        #[test]
1294        fn test_one_part_group() {
1295            //
1296            //   1 -> 2 -> 3 -> 4 -> 5
1297            //         \-> 6 /
1298            //
1299            let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
1300            graph.add_node(1);
1301            graph.add_node(2);
1302            graph.add_node(3);
1303            graph.add_node(4);
1304            graph.add_node(5);
1305            graph.add_node(6);
1306
1307            graph.add_edge(1, 2, ());
1308            graph.add_edge(2, 3, ());
1309            graph.add_edge(3, 4, ());
1310            graph.add_edge(4, 5, ());
1311            graph.add_edge(2, 6, ());
1312            graph.add_edge(6, 4, ());
1313
1314            let result_edges = all_intermediate_edges(&graph, 2, 4);
1315            let intermediate_edges = result_edges
1316                .iter()
1317                .map(|(source, target, _weight)| (*source, *target))
1318                .collect::<Vec<(i64, i64)>>();
1319            assert_eq!(intermediate_edges, vec![(2, 3), (3, 4), (2, 6), (6, 4)]);
1320        }
1321
1322        #[test]
1323        fn test_two_part_groups() {
1324            //
1325            //   1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
1326            //         \-> 8 /    \-> 9 /
1327            //
1328            let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
1329            graph.add_node(1);
1330            graph.add_node(2);
1331            graph.add_node(3);
1332            graph.add_node(4);
1333            graph.add_node(5);
1334            graph.add_node(6);
1335            graph.add_node(7);
1336            graph.add_node(8);
1337            graph.add_node(9);
1338
1339            graph.add_edge(1, 2, ());
1340            graph.add_edge(2, 3, ());
1341            graph.add_edge(3, 4, ());
1342            graph.add_edge(4, 5, ());
1343            graph.add_edge(5, 6, ());
1344            graph.add_edge(6, 7, ());
1345            graph.add_edge(2, 8, ());
1346            graph.add_edge(8, 4, ());
1347            graph.add_edge(4, 9, ());
1348            graph.add_edge(9, 6, ());
1349
1350            let result_edges = all_intermediate_edges(&graph, 2, 6);
1351            let intermediate_edges = result_edges
1352                .iter()
1353                .map(|(source, target, _weight)| (*source, *target))
1354                .collect::<Vec<(i64, i64)>>();
1355            assert_eq!(
1356                intermediate_edges,
1357                vec![
1358                    (2, 3),
1359                    (3, 4),
1360                    (4, 5),
1361                    (5, 6),
1362                    (2, 8),
1363                    (8, 4),
1364                    (4, 9),
1365                    (9, 6)
1366                ]
1367            );
1368        }
1369
1370        #[test]
1371        fn test_one_part_group_with_unrelated_edges() {
1372            //
1373            //        / ------- 7 \
1374            //   1 -> 2 -> 3 -> 4 -> 5
1375            //         \-> 6 /
1376            //
1377            // Because 7 has 5 as a target, it is excluded from the subgraph from 2 to 4
1378            let mut graph: DiGraphMap<i64, ()> = DiGraphMap::new();
1379            graph.add_node(1);
1380            graph.add_node(2);
1381            graph.add_node(3);
1382            graph.add_node(4);
1383            graph.add_node(5);
1384            graph.add_node(6);
1385            graph.add_node(7);
1386
1387            graph.add_edge(1, 2, ());
1388            graph.add_edge(2, 3, ());
1389            graph.add_edge(3, 4, ());
1390            graph.add_edge(4, 5, ());
1391            graph.add_edge(2, 6, ());
1392            graph.add_edge(6, 4, ());
1393            graph.add_edge(2, 7, ());
1394            graph.add_edge(7, 5, ());
1395
1396            let result_edges = all_intermediate_edges(&graph, 2, 4);
1397            let intermediate_edges = result_edges
1398                .iter()
1399                .map(|(source, target, _weight)| (*source, *target))
1400                .collect::<Vec<(i64, i64)>>();
1401            assert_eq!(intermediate_edges, vec![(2, 3), (3, 4), (2, 6), (6, 4)]);
1402        }
1403    }
1404
1405    #[cfg(test)]
1406    mod project_path {
1407        use gen_core::PATH_END_NODE_ID;
1408
1409        use super::*;
1410
1411        #[test]
1412        fn test_simple_path_projection() {
1413            // graph looks like
1414            //
1415            //           /-> 4.3.5 -> 5.0.3 ---\
1416            //  s -> 3.0.5 -------------------> 3.5.15 -> e
1417            //  initial path is defined as 3.0.0 to 3.0.15
1418            let mut graph = GenGraph::new();
1419            graph.add_edge(
1420                GraphNode {
1421                    node_id: PATH_START_NODE_ID,
1422                    sequence_start: 0,
1423                    sequence_end: 0,
1424                },
1425                GraphNode {
1426                    node_id: HashId::convert_str("3"),
1427                    sequence_start: 0,
1428                    sequence_end: 5,
1429                },
1430                vec![GraphEdge {
1431                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1432                    source_strand: Strand::Forward,
1433                    target_strand: Strand::Forward,
1434                    chromosome_index: 0,
1435                    phased: 0,
1436                    created_on: 0,
1437                }],
1438            );
1439            graph.add_edge(
1440                GraphNode {
1441                    node_id: HashId::convert_str("3"),
1442                    sequence_start: 0,
1443                    sequence_end: 5,
1444                },
1445                GraphNode {
1446                    node_id: HashId::convert_str("4"),
1447                    sequence_start: 3,
1448                    sequence_end: 5,
1449                },
1450                vec![GraphEdge {
1451                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1452                    source_strand: Strand::Forward,
1453                    target_strand: Strand::Forward,
1454                    chromosome_index: 0,
1455                    phased: 0,
1456                    created_on: 0,
1457                }],
1458            );
1459            graph.add_edge(
1460                GraphNode {
1461                    node_id: HashId::convert_str("4"),
1462                    sequence_start: 3,
1463                    sequence_end: 5,
1464                },
1465                GraphNode {
1466                    node_id: HashId::convert_str("5"),
1467                    sequence_start: 0,
1468                    sequence_end: 3,
1469                },
1470                vec![GraphEdge {
1471                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1472                    source_strand: Strand::Forward,
1473                    target_strand: Strand::Forward,
1474                    chromosome_index: 0,
1475                    phased: 0,
1476                    created_on: 0,
1477                }],
1478            );
1479            graph.add_edge(
1480                GraphNode {
1481                    node_id: HashId::convert_str("5"),
1482                    sequence_start: 0,
1483                    sequence_end: 3,
1484                },
1485                GraphNode {
1486                    node_id: HashId::convert_str("6"),
1487                    sequence_start: 5,
1488                    sequence_end: 15,
1489                },
1490                vec![GraphEdge {
1491                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1492                    source_strand: Strand::Forward,
1493                    target_strand: Strand::Forward,
1494                    chromosome_index: 0,
1495                    phased: 0,
1496                    created_on: 0,
1497                }],
1498            );
1499            graph.add_edge(
1500                GraphNode {
1501                    node_id: HashId::convert_str("3"),
1502                    sequence_start: 0,
1503                    sequence_end: 5,
1504                },
1505                GraphNode {
1506                    node_id: HashId::convert_str("3"),
1507                    sequence_start: 5,
1508                    sequence_end: 15,
1509                },
1510                vec![GraphEdge {
1511                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1512                    source_strand: Strand::Forward,
1513                    target_strand: Strand::Forward,
1514                    chromosome_index: 0,
1515                    phased: 0,
1516                    created_on: 0,
1517                }],
1518            );
1519            graph.add_edge(
1520                GraphNode {
1521                    node_id: HashId::convert_str("3"),
1522                    sequence_start: 5,
1523                    sequence_end: 15,
1524                },
1525                GraphNode {
1526                    node_id: PATH_END_NODE_ID,
1527                    sequence_start: 0,
1528                    sequence_end: 0,
1529                },
1530                vec![GraphEdge {
1531                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1532                    source_strand: Strand::Forward,
1533                    target_strand: Strand::Forward,
1534                    chromosome_index: 0,
1535                    phased: 0,
1536                    created_on: 0,
1537                }],
1538            );
1539            let path_blocks = vec![
1540                PathBlock {
1541                    node_id: PATH_START_NODE_ID,
1542                    block_sequence: "".to_string(),
1543                    sequence_start: 0,
1544                    sequence_end: 0,
1545                    path_start: 0,
1546                    path_end: 0,
1547                    strand: Strand::Forward,
1548                },
1549                PathBlock {
1550                    node_id: HashId::convert_str("3"),
1551                    block_sequence: "".to_string(),
1552                    sequence_start: 0,
1553                    sequence_end: 15,
1554                    path_start: 0,
1555                    path_end: 0,
1556                    strand: Strand::Forward,
1557                },
1558                PathBlock {
1559                    node_id: PATH_END_NODE_ID,
1560                    block_sequence: "".to_string(),
1561                    sequence_start: 0,
1562                    sequence_end: 0,
1563                    path_start: 0,
1564                    path_end: 0,
1565                    strand: Strand::Forward,
1566                },
1567            ];
1568            let projection = project_path(&graph, &path_blocks);
1569            assert_eq!(
1570                projection,
1571                [
1572                    (
1573                        GraphNode {
1574                            node_id: PATH_START_NODE_ID,
1575                            sequence_start: 0,
1576                            sequence_end: 0
1577                        },
1578                        Strand::Forward
1579                    ),
1580                    (
1581                        GraphNode {
1582                            node_id: HashId::convert_str("3"),
1583                            sequence_start: 0,
1584                            sequence_end: 5
1585                        },
1586                        Strand::Forward
1587                    ),
1588                    (
1589                        GraphNode {
1590                            node_id: HashId::convert_str("3"),
1591                            sequence_start: 5,
1592                            sequence_end: 15
1593                        },
1594                        Strand::Forward
1595                    ),
1596                    (
1597                        GraphNode {
1598                            node_id: PATH_END_NODE_ID,
1599                            sequence_start: 0,
1600                            sequence_end: 0
1601                        },
1602                        Strand::Forward
1603                    )
1604                ]
1605            )
1606        }
1607
1608        #[test]
1609        fn test_nested_path_projection() {
1610            // graph looks like
1611            //                                                /-> 7.0.2 -\
1612            //           /-> 4.3.5 -> 5.0.3 ---\     /-> 6.0.3----------->6.3.7 -\
1613            //  s -> 3.0.5 -------------------> 3.5.10 ------------------------> 3.10.15 -> e
1614            //  initial path is defined as 3.0.0 -> 3.5.10 -> 6.0.7 -> 3.10.15
1615            let mut graph = GenGraph::new();
1616            graph.add_edge(
1617                GraphNode {
1618                    node_id: PATH_START_NODE_ID,
1619                    sequence_start: 0,
1620                    sequence_end: 0,
1621                },
1622                GraphNode {
1623                    node_id: HashId::convert_str("3"),
1624                    sequence_start: 0,
1625                    sequence_end: 5,
1626                },
1627                vec![GraphEdge {
1628                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1629                    source_strand: Strand::Forward,
1630                    target_strand: Strand::Forward,
1631                    chromosome_index: 0,
1632                    phased: 0,
1633                    created_on: 0,
1634                }],
1635            );
1636            graph.add_edge(
1637                GraphNode {
1638                    node_id: HashId::convert_str("3"),
1639                    sequence_start: 0,
1640                    sequence_end: 5,
1641                },
1642                GraphNode {
1643                    node_id: HashId::convert_str("4"),
1644                    sequence_start: 3,
1645                    sequence_end: 5,
1646                },
1647                vec![GraphEdge {
1648                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1649                    source_strand: Strand::Forward,
1650                    target_strand: Strand::Forward,
1651                    chromosome_index: 0,
1652                    phased: 0,
1653                    created_on: 0,
1654                }],
1655            );
1656            graph.add_edge(
1657                GraphNode {
1658                    node_id: HashId::convert_str("4"),
1659                    sequence_start: 3,
1660                    sequence_end: 5,
1661                },
1662                GraphNode {
1663                    node_id: HashId::convert_str("5"),
1664                    sequence_start: 0,
1665                    sequence_end: 3,
1666                },
1667                vec![GraphEdge {
1668                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1669                    source_strand: Strand::Forward,
1670                    target_strand: Strand::Forward,
1671                    chromosome_index: 0,
1672                    phased: 0,
1673                    created_on: 0,
1674                }],
1675            );
1676            graph.add_edge(
1677                GraphNode {
1678                    node_id: HashId::convert_str("5"),
1679                    sequence_start: 0,
1680                    sequence_end: 3,
1681                },
1682                GraphNode {
1683                    node_id: HashId::convert_str("3"),
1684                    sequence_start: 5,
1685                    sequence_end: 10,
1686                },
1687                vec![GraphEdge {
1688                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1689                    source_strand: Strand::Forward,
1690                    target_strand: Strand::Forward,
1691                    chromosome_index: 0,
1692                    phased: 0,
1693                    created_on: 0,
1694                }],
1695            );
1696            graph.add_edge(
1697                GraphNode {
1698                    node_id: HashId::convert_str("3"),
1699                    sequence_start: 0,
1700                    sequence_end: 5,
1701                },
1702                GraphNode {
1703                    node_id: HashId::convert_str("3"),
1704                    sequence_start: 5,
1705                    sequence_end: 10,
1706                },
1707                vec![GraphEdge {
1708                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1709                    source_strand: Strand::Forward,
1710                    target_strand: Strand::Forward,
1711                    chromosome_index: 0,
1712                    phased: 0,
1713                    created_on: 0,
1714                }],
1715            );
1716
1717            graph.add_edge(
1718                GraphNode {
1719                    node_id: HashId::convert_str("3"),
1720                    sequence_start: 5,
1721                    sequence_end: 10,
1722                },
1723                GraphNode {
1724                    node_id: HashId::convert_str("3"),
1725                    sequence_start: 10,
1726                    sequence_end: 15,
1727                },
1728                vec![GraphEdge {
1729                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1730                    source_strand: Strand::Forward,
1731                    target_strand: Strand::Forward,
1732                    chromosome_index: 0,
1733                    phased: 0,
1734                    created_on: 0,
1735                }],
1736            );
1737
1738            graph.add_edge(
1739                GraphNode {
1740                    node_id: HashId::convert_str("3"),
1741                    sequence_start: 5,
1742                    sequence_end: 10,
1743                },
1744                GraphNode {
1745                    node_id: HashId::convert_str("6"),
1746                    sequence_start: 0,
1747                    sequence_end: 3,
1748                },
1749                vec![GraphEdge {
1750                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1751                    source_strand: Strand::Forward,
1752                    target_strand: Strand::Forward,
1753                    chromosome_index: 0,
1754                    phased: 0,
1755                    created_on: 0,
1756                }],
1757            );
1758
1759            graph.add_edge(
1760                GraphNode {
1761                    node_id: HashId::convert_str("6"),
1762                    sequence_start: 0,
1763                    sequence_end: 3,
1764                },
1765                GraphNode {
1766                    node_id: HashId::convert_str("6"),
1767                    sequence_start: 3,
1768                    sequence_end: 7,
1769                },
1770                vec![GraphEdge {
1771                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1772                    source_strand: Strand::Forward,
1773                    target_strand: Strand::Forward,
1774                    chromosome_index: 0,
1775                    phased: 0,
1776                    created_on: 0,
1777                }],
1778            );
1779
1780            graph.add_edge(
1781                GraphNode {
1782                    node_id: HashId::convert_str("6"),
1783                    sequence_start: 0,
1784                    sequence_end: 3,
1785                },
1786                GraphNode {
1787                    node_id: HashId::convert_str("7"),
1788                    sequence_start: 0,
1789                    sequence_end: 2,
1790                },
1791                vec![GraphEdge {
1792                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1793                    source_strand: Strand::Forward,
1794                    target_strand: Strand::Forward,
1795                    chromosome_index: 0,
1796                    phased: 0,
1797                    created_on: 0,
1798                }],
1799            );
1800            graph.add_edge(
1801                GraphNode {
1802                    node_id: HashId::convert_str("7"),
1803                    sequence_start: 0,
1804                    sequence_end: 2,
1805                },
1806                GraphNode {
1807                    node_id: HashId::convert_str("6"),
1808                    sequence_start: 3,
1809                    sequence_end: 7,
1810                },
1811                vec![GraphEdge {
1812                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1813                    source_strand: Strand::Forward,
1814                    target_strand: Strand::Forward,
1815                    chromosome_index: 0,
1816                    phased: 0,
1817                    created_on: 0,
1818                }],
1819            );
1820
1821            graph.add_edge(
1822                GraphNode {
1823                    node_id: HashId::convert_str("6"),
1824                    sequence_start: 3,
1825                    sequence_end: 7,
1826                },
1827                GraphNode {
1828                    node_id: HashId::convert_str("3"),
1829                    sequence_start: 10,
1830                    sequence_end: 15,
1831                },
1832                vec![GraphEdge {
1833                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1834                    source_strand: Strand::Forward,
1835                    target_strand: Strand::Forward,
1836                    chromosome_index: 0,
1837                    phased: 0,
1838                    created_on: 0,
1839                }],
1840            );
1841
1842            graph.add_edge(
1843                GraphNode {
1844                    node_id: HashId::convert_str("3"),
1845                    sequence_start: 10,
1846                    sequence_end: 15,
1847                },
1848                GraphNode {
1849                    node_id: PATH_END_NODE_ID,
1850                    sequence_start: 0,
1851                    sequence_end: 0,
1852                },
1853                vec![GraphEdge {
1854                    edge_id: "00000000000000000000000000000000".try_into().unwrap(),
1855                    source_strand: Strand::Forward,
1856                    target_strand: Strand::Forward,
1857                    chromosome_index: 0,
1858                    phased: 0,
1859                    created_on: 0,
1860                }],
1861            );
1862            let path_blocks = vec![
1863                PathBlock {
1864                    node_id: PATH_START_NODE_ID,
1865                    block_sequence: "".to_string(),
1866                    sequence_start: 0,
1867                    sequence_end: 0,
1868                    path_start: 0,
1869                    path_end: 0,
1870                    strand: Strand::Forward,
1871                },
1872                PathBlock {
1873                    node_id: HashId::convert_str("3"),
1874                    block_sequence: "".to_string(),
1875                    sequence_start: 0,
1876                    sequence_end: 5,
1877                    path_start: 0,
1878                    path_end: 5,
1879                    strand: Strand::Forward,
1880                },
1881                PathBlock {
1882                    node_id: HashId::convert_str("3"),
1883                    block_sequence: "".to_string(),
1884                    sequence_start: 5,
1885                    sequence_end: 10,
1886                    path_start: 5,
1887                    path_end: 10,
1888                    strand: Strand::Forward,
1889                },
1890                PathBlock {
1891                    node_id: HashId::convert_str("6"),
1892                    block_sequence: "".to_string(),
1893                    sequence_start: 0,
1894                    sequence_end: 7,
1895                    path_start: 10,
1896                    path_end: 17,
1897                    strand: Strand::Forward,
1898                },
1899                PathBlock {
1900                    node_id: HashId::convert_str("3"),
1901                    block_sequence: "".to_string(),
1902                    sequence_start: 10,
1903                    sequence_end: 15,
1904                    path_start: 17,
1905                    path_end: 23,
1906                    strand: Strand::Forward,
1907                },
1908                PathBlock {
1909                    node_id: PATH_END_NODE_ID,
1910                    block_sequence: "".to_string(),
1911                    sequence_start: 0,
1912                    sequence_end: 0,
1913                    path_start: 0,
1914                    path_end: 0,
1915                    strand: Strand::Forward,
1916                },
1917            ];
1918            let projection = project_path(&graph, &path_blocks);
1919            assert_eq!(
1920                projection,
1921                [
1922                    (
1923                        GraphNode {
1924                            node_id: PATH_START_NODE_ID,
1925                            sequence_start: 0,
1926                            sequence_end: 0
1927                        },
1928                        Strand::Forward
1929                    ),
1930                    (
1931                        GraphNode {
1932                            node_id: HashId::convert_str("3"),
1933                            sequence_start: 0,
1934                            sequence_end: 5
1935                        },
1936                        Strand::Forward
1937                    ),
1938                    (
1939                        GraphNode {
1940                            node_id: HashId::convert_str("3"),
1941                            sequence_start: 5,
1942                            sequence_end: 10
1943                        },
1944                        Strand::Forward
1945                    ),
1946                    (
1947                        GraphNode {
1948                            node_id: HashId::convert_str("6"),
1949                            sequence_start: 0,
1950                            sequence_end: 3
1951                        },
1952                        Strand::Forward
1953                    ),
1954                    (
1955                        GraphNode {
1956                            node_id: HashId::convert_str("6"),
1957                            sequence_start: 3,
1958                            sequence_end: 7
1959                        },
1960                        Strand::Forward
1961                    ),
1962                    (
1963                        GraphNode {
1964                            node_id: HashId::convert_str("3"),
1965                            sequence_start: 10,
1966                            sequence_end: 15
1967                        },
1968                        Strand::Forward
1969                    ),
1970                    (
1971                        GraphNode {
1972                            node_id: PATH_END_NODE_ID,
1973                            sequence_start: 0,
1974                            sequence_end: 0
1975                        },
1976                        Strand::Forward
1977                    )
1978                ]
1979            )
1980        }
1981    }
1982}