Skip to main content

gen_models/
graph.rs

1use std::collections::{HashMap, HashSet, VecDeque};
2
3use gen_core::{HashId, NodeIntervalBlock, is_terminal};
4use gen_graph::{GenGraph, GraphError, GraphNode, GraphNodePosition, MergeGraph};
5use intervaltree::IntervalTree;
6use petgraph::Direction;
7
8use crate::{
9    block_group::BlockGroup, block_group_edge::AugmentedEdge, db::GraphConnection, edge::Edge,
10    node::Node,
11};
12
13pub struct ResolvedGraph {
14    pub graph: GenGraph,
15    pub interval_tree: IntervalTree<i64, NodeIntervalBlock>,
16    pub block_group_id: HashId,
17}
18
19/// Identify all edges leading to and from a provided node_id in a block_group and merge them into an existing GenGraph.
20/// Returns true if the graph was expanded, false if no new edges were added.
21pub fn expand(
22    conn: &GraphConnection,
23    graph: &mut GenGraph,
24    block_group_id: &HashId,
25    node_id: HashId,
26) -> bool {
27    let edges_1hop =
28        Edge::edges_for_block_group_nodes(conn, block_group_id, &[node_id]).unwrap_or_default();
29
30    let mut neighbor_ids: Vec<HashId> = edges_1hop
31        .iter()
32        .flat_map(|ae| [ae.edge.source_node_id, ae.edge.target_node_id])
33        .filter(|id| *id != node_id)
34        .collect();
35    neighbor_ids.sort();
36    neighbor_ids.dedup();
37
38    let mut all_edges: HashMap<HashId, AugmentedEdge> =
39        edges_1hop.into_iter().map(|ae| (ae.edge.id, ae)).collect();
40    if !neighbor_ids.is_empty() {
41        let neighbor_edges = Edge::edges_for_block_group_nodes(conn, block_group_id, &neighbor_ids)
42            .unwrap_or_default();
43        for ae in neighbor_edges {
44            all_edges.entry(ae.edge.id).or_insert(ae);
45        }
46    }
47
48    let existing_edge_ids: HashSet<HashId> = graph
49        .all_edges()
50        .flat_map(|(_, _, edges)| edges.iter().map(|e| e.edge_id))
51        .collect();
52
53    let new_edges: Vec<AugmentedEdge> = all_edges
54        .into_values()
55        .filter(|ae| !existing_edge_ids.contains(&ae.edge.id))
56        .collect();
57
58    if new_edges.is_empty() {
59        return false;
60    }
61
62    let fragment = match BlockGroup::get_graph_from_edges(conn, block_group_id, &new_edges) {
63        Ok(g) => g,
64        Err(_) => return false,
65    };
66    graph.merge_graph(&fragment);
67    true
68}
69
70/// From a given position in a graph, find positions a given number of characters away. An
71/// expand function can be given that specifies how to expand the input graph when it is exhausted.
72/// By default, this function searches along the known graph, and if a matching position cannot be found
73/// it will expand until it is not possible to grow the graph anymore.
74/// Returns a Result<Vec<GraphNodePosition>>, given a list of matching GraphNodePositions at the requested distance.
75pub fn find_offset(
76    graph: &mut GenGraph,
77    // The position to begin the search from
78    anchor: &GraphNodePosition,
79    // How far from the anchor the position of interst is. negative means search upstream of the graph position.
80    // positive means search downstream.
81    distance: i64,
82    mut expand: impl FnMut(&mut GenGraph, HashId) -> bool,
83) -> Result<Vec<GraphNodePosition>, GraphError> {
84    if distance == 0 {
85        return Ok(vec![*anchor]);
86    }
87
88    match find_offset_with_optional_expansion(graph, anchor, distance, false, &mut expand) {
89        Ok(results) => Ok(results),
90        Err(GraphError::OutOfBounds(_)) => {
91            find_offset_with_optional_expansion(graph, anchor, distance, true, &mut expand)
92        }
93        Err(err) => Err(err),
94    }
95}
96
97/// The actual function doing the work from `find_offset`. See docs in `find_offset` for explanation.
98fn find_offset_with_optional_expansion(
99    graph: &mut GenGraph,
100    anchor: &GraphNodePosition,
101    distance: i64,
102    // If true, expand the graph if search leads to the end of a graph.
103    expand_through_existing_paths: bool,
104    expand: &mut impl FnMut(&mut GenGraph, HashId) -> bool,
105) -> Result<Vec<GraphNodePosition>, GraphError> {
106    let forward = distance > 0;
107    let mut queue = VecDeque::new();
108    let mut visited = HashSet::new();
109    let mut results = Vec::new();
110    let mut result_seen = HashSet::new();
111
112    queue.push_back((*anchor, distance));
113    visited.insert((*anchor, distance));
114
115    while let Some((pos, remaining)) = queue.pop_front() {
116        let node = pos.graph_node;
117        let node_len = node.length();
118
119        if remaining == 0 {
120            if result_seen.insert(pos) {
121                results.push(pos);
122            }
123            continue;
124        }
125
126        if forward {
127            let in_node = node_len - pos.offset;
128            if remaining <= in_node {
129                let result = GraphNodePosition {
130                    graph_node: node,
131                    offset: pos.offset + remaining,
132                };
133                if result_seen.insert(result) {
134                    results.push(result);
135                }
136                continue;
137            }
138
139            // Outgoing nodes means downstream nodes to search for.
140            let mut neighbors: Vec<GraphNode> = graph
141                .neighbors_directed(node, Direction::Outgoing)
142                .collect();
143
144            if (neighbors.is_empty() || expand_through_existing_paths)
145                && expand(graph, node.node_id)
146            {
147                neighbors = graph
148                    .neighbors_directed(node, Direction::Outgoing)
149                    .collect();
150            }
151
152            for neighbor in neighbors {
153                let next_pos = GraphNodePosition {
154                    graph_node: neighbor,
155                    offset: 0,
156                };
157                let next_remaining = remaining - in_node;
158                if visited.insert((next_pos, next_remaining)) {
159                    queue.push_back((next_pos, next_remaining));
160                }
161            }
162        } else {
163            let in_node = pos.offset;
164            let abs_remaining = -remaining;
165            if abs_remaining <= in_node {
166                let result = GraphNodePosition {
167                    graph_node: node,
168                    offset: pos.offset + remaining,
169                };
170                if result_seen.insert(result) {
171                    results.push(result);
172                }
173                continue;
174            }
175
176            // Incoming edges means upstream nodes to traverse
177            let mut neighbors: Vec<GraphNode> = graph
178                .neighbors_directed(node, Direction::Incoming)
179                .collect();
180
181            if (neighbors.is_empty() || expand_through_existing_paths)
182                && expand(graph, node.node_id)
183            {
184                neighbors = graph
185                    .neighbors_directed(node, Direction::Incoming)
186                    .collect();
187            }
188
189            for neighbor in neighbors {
190                let next_pos = GraphNodePosition {
191                    graph_node: neighbor,
192                    offset: neighbor.length(),
193                };
194                let next_remaining = remaining + in_node;
195                if visited.insert((next_pos, next_remaining)) {
196                    queue.push_back((next_pos, next_remaining));
197                }
198            }
199        }
200    }
201
202    if results.is_empty() {
203        return Err(GraphError::OutOfBounds(distance));
204    }
205
206    Ok(results)
207}
208
209impl ResolvedGraph {
210    /// Find a postion in a graph according to a provided coordinate. This is generally utilized by the GenRegion machinery to identify the
211    /// positions a user requested.
212    pub fn resolve_anchor(
213        &self,
214        coord: i64,
215        conn: &GraphConnection,
216    ) -> Result<GraphNodePosition, GraphError> {
217        let mut block = None;
218        for item in self.interval_tree.query_point(coord) {
219            let b = &item.value;
220            if !is_terminal(b.node_id) {
221                block = Some(*b);
222                break;
223            }
224        }
225
226        if let Some(b) = block {
227            let offset = coord - b.start;
228            return Ok(GraphNodePosition {
229                graph_node: GraphNode {
230                    node_id: b.node_id,
231                    sequence_start: b.sequence_start,
232                    sequence_end: b.sequence_end,
233                },
234                offset,
235            });
236        }
237
238        let last_block = self
239            .interval_tree
240            .iter()
241            .map(|item| &item.value)
242            .filter(|b| !is_terminal(b.node_id))
243            .max_by_key(|b| b.end)
244            .copied();
245
246        let before_tree = coord < 0;
247        let after_tree = last_block.map(|b| coord >= b.end).unwrap_or(false);
248
249        let boundary_block = if before_tree {
250            self.interval_tree
251                .iter()
252                .map(|item| &item.value)
253                .filter(|b| !is_terminal(b.node_id))
254                .min_by_key(|b| b.start)
255                .copied()
256        } else if after_tree {
257            last_block
258        } else {
259            None
260        };
261
262        let boundary = boundary_block.ok_or(GraphError::NoPath)?;
263        let boundary_node = GraphNode {
264            node_id: boundary.node_id,
265            sequence_start: boundary.sequence_start,
266            sequence_end: boundary.sequence_end,
267        };
268
269        let boundary_anchor = GraphNodePosition {
270            graph_node: boundary_node,
271            offset: if before_tree {
272                0
273            } else {
274                boundary.sequence_end - boundary.sequence_start
275            },
276        };
277
278        let boundary_distance = if before_tree {
279            coord - boundary.start
280        } else {
281            coord - boundary.end
282        };
283
284        let same_node_coordinate = if before_tree {
285            boundary.sequence_start + boundary_distance
286        } else {
287            boundary.sequence_end + boundary_distance
288        };
289        if same_node_coordinate >= 0
290            && let Ok(node_lengths) = Node::query_nodes_length(conn, &[boundary.node_id])
291            && same_node_coordinate <= *node_lengths.get(&boundary.node_id).unwrap_or(&0)
292        {
293            return Ok(GraphNodePosition {
294                graph_node: boundary_node,
295                offset: boundary_anchor.offset + boundary_distance,
296            });
297        }
298
299        let mut expanded_graph = self.graph.clone();
300        expand(
301            conn,
302            &mut expanded_graph,
303            &self.block_group_id,
304            boundary_node.node_id,
305        );
306
307        let anchors = find_offset(
308            &mut expanded_graph,
309            &boundary_anchor,
310            boundary_distance,
311            |g, nid| expand(conn, g, &self.block_group_id, nid),
312        )?;
313
314        anchors.into_iter().next().ok_or(GraphError::NoPath)
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use std::collections::HashSet;
321
322    use gen_core::{PATH_END_NODE_ID, PATH_START_NODE_ID, Strand};
323    use gen_graph::{GraphEdge, graph_from_interval_tree};
324
325    use super::*;
326    use crate::{
327        block_group::{BlockGroup, NewBlockGroup},
328        block_group_edge::{BlockGroupEdge, BlockGroupEdgeData},
329        collection::Collection,
330        node::Node,
331        sample::{NewSample, Sample},
332        sequence::Sequence,
333        test_helpers::get_connection,
334    };
335
336    fn setup_subset_graph() -> (crate::db::GraphConnection, HashId) {
337        let conn = get_connection(None).unwrap();
338        Collection::get_or_create(&conn, "test").unwrap();
339        Sample::get_or_create(
340            &conn,
341            NewSample {
342                name: "test",
343                ..Default::default()
344            },
345        )
346        .unwrap();
347        let block_group = BlockGroup::create(
348            &conn,
349            NewBlockGroup {
350                collection_name: "test",
351                sample_name: "test",
352                name: "chr1",
353                ..Default::default()
354            },
355        )
356        .unwrap();
357
358        let seq_x = Sequence::new()
359            .sequence_type("DNA")
360            .sequence("XXXXX")
361            .save(&conn)
362            .unwrap();
363        let seq_y = Sequence::new()
364            .sequence_type("DNA")
365            .sequence("YYYYY")
366            .save(&conn)
367            .unwrap();
368        let seq_z = Sequence::new()
369            .sequence_type("DNA")
370            .sequence("ZZZZZ")
371            .save(&conn)
372            .unwrap();
373
374        let node_x = Node::create(&conn, &seq_x.hash, &HashId::convert_str("node-x")).unwrap();
375        let node_y = Node::create(&conn, &seq_y.hash, &HashId::convert_str("node-y")).unwrap();
376        let node_z = Node::create(&conn, &seq_z.hash, &HashId::convert_str("node-z")).unwrap();
377
378        let e_start = Edge::create(
379            &conn,
380            PATH_START_NODE_ID,
381            -1,
382            Strand::Forward,
383            node_x,
384            0,
385            Strand::Forward,
386        )
387        .unwrap();
388        let e_xy = Edge::create(
389            &conn,
390            node_x,
391            5,
392            Strand::Forward,
393            node_y,
394            0,
395            Strand::Forward,
396        )
397        .unwrap();
398        let e_yz = Edge::create(
399            &conn,
400            node_y,
401            5,
402            Strand::Forward,
403            node_z,
404            0,
405            Strand::Forward,
406        )
407        .unwrap();
408        let e_end = Edge::create(
409            &conn,
410            node_z,
411            5,
412            Strand::Forward,
413            PATH_END_NODE_ID,
414            0,
415            Strand::Forward,
416        )
417        .unwrap();
418
419        BlockGroupEdge::bulk_create(
420            &conn,
421            &[
422                BlockGroupEdgeData {
423                    block_group_id: block_group.id,
424                    edge_id: e_start.id,
425                    chromosome_index: 0,
426                    phased: 0,
427                },
428                BlockGroupEdgeData {
429                    block_group_id: block_group.id,
430                    edge_id: e_xy.id,
431                    chromosome_index: 0,
432                    phased: 0,
433                },
434                BlockGroupEdgeData {
435                    block_group_id: block_group.id,
436                    edge_id: e_yz.id,
437                    chromosome_index: 0,
438                    phased: 0,
439                },
440                BlockGroupEdgeData {
441                    block_group_id: block_group.id,
442                    edge_id: e_end.id,
443                    chromosome_index: 0,
444                    phased: 0,
445                },
446            ],
447        );
448
449        (conn, block_group.id)
450    }
451
452    fn subset_interval_tree() -> IntervalTree<i64, NodeIntervalBlock> {
453        vec![(
454            0..5,
455            NodeIntervalBlock {
456                node_id: HashId::convert_str("node-y"),
457                start: 0,
458                end: 5,
459                sequence_start: 0,
460                sequence_end: 5,
461                strand: Strand::Forward,
462            },
463        )]
464        .into_iter()
465        .collect()
466    }
467
468    fn test_edge(edge_id: &str) -> Vec<GraphEdge> {
469        vec![GraphEdge {
470            edge_id: HashId::convert_str(edge_id),
471            source_strand: Strand::Forward,
472            target_strand: Strand::Forward,
473            chromosome_index: 0,
474            phased: 0,
475            created_on: 0,
476        }]
477    }
478
479    fn variable_length_branched_graph() -> GenGraph {
480        let node_aaa = GraphNode {
481            node_id: HashId::convert_str("node-aaa"),
482            sequence_start: 0,
483            sequence_end: 3,
484        };
485        let node_cc = GraphNode {
486            node_id: HashId::convert_str("node-cc"),
487            sequence_start: 0,
488            sequence_end: 2,
489        };
490        let node_gggg = GraphNode {
491            node_id: HashId::convert_str("node-gggg"),
492            sequence_start: 0,
493            sequence_end: 4,
494        };
495        let node_ttt = GraphNode {
496            node_id: HashId::convert_str("node-ttt"),
497            sequence_start: 0,
498            sequence_end: 3,
499        };
500
501        let mut graph = GenGraph::new();
502        graph.add_edge(node_aaa, node_cc, test_edge("edge-aaa-cc"));
503        graph.add_edge(node_aaa, node_gggg, test_edge("edge-aaa-gggg"));
504        graph.add_edge(node_cc, node_ttt, test_edge("edge-cc-ttt"));
505        graph.add_edge(node_gggg, node_ttt, test_edge("edge-gggg-ttt"));
506        graph
507    }
508
509    fn position_set(positions: &[GraphNodePosition]) -> HashSet<(HashId, i64)> {
510        positions
511            .iter()
512            .map(|pos| (pos.graph_node.node_id, pos.offset))
513            .collect()
514    }
515
516    #[test]
517    fn test_find_offset_within_subset_node() {
518        let (conn, bg_id) = setup_subset_graph();
519        let tree = subset_interval_tree();
520        let mut graph = graph_from_interval_tree(&tree);
521
522        let y_node = GraphNode {
523            node_id: HashId::convert_str("node-y"),
524            sequence_start: 0,
525            sequence_end: 5,
526        };
527        let anchor = GraphNodePosition {
528            graph_node: y_node,
529            offset: 0,
530        };
531
532        let result = find_offset(&mut graph, &anchor, 3, |g, nid| {
533            expand(&conn, g, &bg_id, nid)
534        });
535        assert!(
536            result.is_ok(),
537            "find_offset(3) should succeed: {:?}",
538            result.err()
539        );
540        let positions = result.unwrap();
541        assert_eq!(positions.len(), 1);
542        assert_eq!(positions[0].graph_node, y_node);
543        assert_eq!(positions[0].offset, 3);
544    }
545
546    #[test]
547    fn test_find_offset_forward_expands_beyond_subset() {
548        let (conn, bg_id) = setup_subset_graph();
549        let tree = subset_interval_tree();
550        let mut graph = graph_from_interval_tree(&tree);
551
552        let y_node = GraphNode {
553            node_id: HashId::convert_str("node-y"),
554            sequence_start: 0,
555            sequence_end: 5,
556        };
557        let anchor = GraphNodePosition {
558            graph_node: y_node,
559            offset: 0,
560        };
561
562        let result = find_offset(&mut graph, &anchor, 7, |g, nid| {
563            expand(&conn, g, &bg_id, nid)
564        });
565        assert!(
566            result.is_ok(),
567            "find_offset(7) should expand to Z: {:?}",
568            result.err()
569        );
570        let positions = result.unwrap();
571        assert_eq!(positions.len(), 1);
572        assert_eq!(
573            positions[0].graph_node.node_id,
574            HashId::convert_str("node-z")
575        );
576        assert_eq!(positions[0].offset, 2);
577    }
578
579    #[test]
580    fn test_find_offset_forward_expands_after_existing_paths_fail() {
581        let (conn, bg_id) = setup_subset_graph();
582        let mut graph = GenGraph::new();
583
584        let y_node = GraphNode {
585            node_id: HashId::convert_str("node-y"),
586            sequence_start: 0,
587            sequence_end: 5,
588        };
589        let dead_end = GraphNode {
590            node_id: HashId::convert_str("dead-end"),
591            sequence_start: 0,
592            sequence_end: 1,
593        };
594        graph.add_edge(
595            y_node,
596            dead_end,
597            vec![GraphEdge {
598                edge_id: HashId::convert_str("edge-y-dead"),
599                source_strand: Strand::Forward,
600                target_strand: Strand::Forward,
601                chromosome_index: 0,
602                phased: 0,
603                created_on: 0,
604            }],
605        );
606        let anchor = GraphNodePosition {
607            graph_node: y_node,
608            offset: 0,
609        };
610
611        let result = find_offset(&mut graph, &anchor, 7, |g, nid| {
612            expand(&conn, g, &bg_id, nid)
613        });
614        assert!(
615            result.is_ok(),
616            "find_offset(7) should expand from Y after the existing path fails: {:?}",
617            result.err()
618        );
619        let positions = result.unwrap();
620        assert_eq!(positions.len(), 1);
621        assert_eq!(
622            positions[0].graph_node.node_id,
623            HashId::convert_str("node-z")
624        );
625        assert_eq!(positions[0].offset, 2);
626    }
627
628    #[test]
629    fn test_find_offset_backward_expands_beyond_subset() {
630        let (conn, bg_id) = setup_subset_graph();
631        let tree = subset_interval_tree();
632        let mut graph = graph_from_interval_tree(&tree);
633
634        let y_node = GraphNode {
635            node_id: HashId::convert_str("node-y"),
636            sequence_start: 0,
637            sequence_end: 5,
638        };
639        let anchor = GraphNodePosition {
640            graph_node: y_node,
641            offset: 0,
642        };
643
644        let result = find_offset(&mut graph, &anchor, -3, |g, nid| {
645            expand(&conn, g, &bg_id, nid)
646        });
647        assert!(
648            result.is_ok(),
649            "find_offset(-3) should expand to X: {:?}",
650            result.err()
651        );
652        let positions = result.unwrap();
653        assert_eq!(positions.len(), 1);
654        assert_eq!(
655            positions[0].graph_node.node_id,
656            HashId::convert_str("node-x")
657        );
658        assert_eq!(positions[0].offset, 2);
659    }
660
661    #[test]
662    fn test_find_offset_out_of_bounds_with_expansion() {
663        let (conn, bg_id) = setup_subset_graph();
664        let tree = subset_interval_tree();
665        let mut graph = graph_from_interval_tree(&tree);
666
667        let y_node = GraphNode {
668            node_id: HashId::convert_str("node-y"),
669            sequence_start: 0,
670            sequence_end: 5,
671        };
672        let anchor = GraphNodePosition {
673            graph_node: y_node,
674            offset: 0,
675        };
676
677        let result = find_offset(&mut graph, &anchor, 100, |g, nid| {
678            expand(&conn, g, &bg_id, nid)
679        });
680        assert!(result.is_err());
681    }
682
683    #[test]
684    fn test_find_offset_with_fragment_node() {
685        let (conn, bg_id) = setup_subset_graph();
686
687        let tree: IntervalTree<i64, NodeIntervalBlock> = vec![(
688            0..3,
689            NodeIntervalBlock {
690                node_id: HashId::convert_str("node-y"),
691                start: 0,
692                end: 3,
693                sequence_start: 0,
694                sequence_end: 3,
695                strand: Strand::Forward,
696            },
697        )]
698        .into_iter()
699        .collect();
700        let mut graph = graph_from_interval_tree(&tree);
701
702        let y_frag = GraphNode {
703            node_id: HashId::convert_str("node-y"),
704            sequence_start: 0,
705            sequence_end: 3,
706        };
707        let anchor = GraphNodePosition {
708            graph_node: y_frag,
709            offset: 0,
710        };
711
712        let result = find_offset(&mut graph, &anchor, 2, |g, nid| {
713            expand(&conn, g, &bg_id, nid)
714        });
715        assert!(result.is_ok());
716        let positions = result.unwrap();
717        assert_eq!(positions[0].graph_node, y_frag);
718        assert_eq!(positions[0].offset, 2);
719    }
720
721    #[test]
722    fn resolve_anchor_before_fragment_stays_on_same_backing_node() {
723        // The case is when we have a node fragment
724        // at the beginning of an accession. We don't know how far back to expand
725        // the fragment as there are no edges.
726        let (conn, bg_id) = setup_subset_graph();
727
728        let tree: IntervalTree<i64, NodeIntervalBlock> = vec![(
729            0..3,
730            NodeIntervalBlock {
731                node_id: HashId::convert_str("node-y"),
732                start: 0,
733                end: 3,
734                sequence_start: 2,
735                sequence_end: 5,
736                strand: Strand::Forward,
737            },
738        )]
739        .into_iter()
740        .collect();
741        let graph = graph_from_interval_tree(&tree);
742        let resolved = ResolvedGraph {
743            graph,
744            interval_tree: tree,
745            block_group_id: bg_id,
746        };
747
748        let position = resolved.resolve_anchor(-2, &conn).unwrap();
749
750        assert_eq!(
751            position.graph_node,
752            GraphNode {
753                node_id: HashId::convert_str("node-y"),
754                sequence_start: 2,
755                sequence_end: 5,
756            }
757        );
758        assert_eq!(position.offset, -2);
759        assert_eq!(position.coordinate(), 0);
760    }
761
762    #[test]
763    fn test_expand_adds_neighbors() {
764        let (conn, bg_id) = setup_subset_graph();
765        let tree = subset_interval_tree();
766        let mut graph = graph_from_interval_tree(&tree);
767
768        assert_eq!(graph.node_count(), 1);
769
770        let expanded = expand(&conn, &mut graph, &bg_id, HashId::convert_str("node-y"));
771        assert!(expanded, "expand should add new nodes");
772        assert!(
773            graph.node_count() > 1,
774            "graph should have more nodes after expansion"
775        );
776
777        let node_ids: Vec<HashId> = graph.nodes().map(|n| n.node_id).collect();
778        assert!(
779            node_ids.contains(&HashId::convert_str("node-x")),
780            "X should be added after expanding Y"
781        );
782        assert!(
783            node_ids.contains(&HashId::convert_str("node-z")),
784            "Z should be added after expanding Y"
785        );
786    }
787
788    #[test]
789    fn test_find_offset_in_variable_length_branch_finds_middle_nodes() {
790        let mut graph = variable_length_branched_graph();
791        let aaa_anchor = GraphNodePosition {
792            graph_node: GraphNode {
793                node_id: HashId::convert_str("node-aaa"),
794                sequence_start: 0,
795                sequence_end: 3,
796            },
797            offset: 2,
798        };
799
800        let from_aaa = find_offset(&mut graph, &aaa_anchor, 2, |_, _| false).unwrap();
801        assert_eq!(
802            position_set(&from_aaa),
803            HashSet::from([
804                (HashId::convert_str("node-cc"), 1),
805                (HashId::convert_str("node-gggg"), 1)
806            ])
807        );
808
809        let ttt_anchor = GraphNodePosition {
810            graph_node: GraphNode {
811                node_id: HashId::convert_str("node-ttt"),
812                sequence_start: 0,
813                sequence_end: 3,
814            },
815            offset: 0,
816        };
817        let from_ttt = find_offset(&mut graph, &ttt_anchor, -2, |_, _| false).unwrap();
818        assert_eq!(
819            position_set(&from_ttt),
820            HashSet::from([
821                (HashId::convert_str("node-cc"), 0),
822                (HashId::convert_str("node-gggg"), 2)
823            ])
824        );
825    }
826
827    #[test]
828    fn test_find_offset_in_variable_length_branch_returns_single_position_within_node() {
829        let mut graph = variable_length_branched_graph();
830        let anchor = GraphNodePosition {
831            graph_node: GraphNode {
832                node_id: HashId::convert_str("node-aaa"),
833                sequence_start: 0,
834                sequence_end: 3,
835            },
836            offset: 1,
837        };
838
839        let positions = find_offset(&mut graph, &anchor, 1, |_, _| false).unwrap();
840        assert_eq!(
841            position_set(&positions),
842            HashSet::from([(HashId::convert_str("node-aaa"), 2)])
843        );
844    }
845
846    #[test]
847    fn test_find_offset_in_variable_length_branch_finds_different_ttt_offsets() {
848        let mut graph = variable_length_branched_graph();
849        let anchor = GraphNodePosition {
850            graph_node: GraphNode {
851                node_id: HashId::convert_str("node-aaa"),
852                sequence_start: 0,
853                sequence_end: 3,
854            },
855            offset: 2,
856        };
857
858        let positions = find_offset(&mut graph, &anchor, 6, |_, _| false).unwrap();
859        assert_eq!(
860            position_set(&positions),
861            HashSet::from([
862                (HashId::convert_str("node-ttt"), 1),
863                (HashId::convert_str("node-ttt"), 3)
864            ])
865        );
866    }
867}