Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
114 commits
Select commit Hold shift + click to select a range
4320afb
intend to bitpack these fields
faithokamoto Jan 26, 2026
bbdb763
use helper function more places
faithokamoto Jan 26, 2026
195b1d4
update debug statements
faithokamoto Jan 26, 2026
7c90a81
add into node/snarl code structs
faithokamoto Jan 26, 2026
dda5ec4
add more accessors
faithokamoto Jan 27, 2026
b149398
nodes work better
faithokamoto Jan 29, 2026
80cf179
it doesn't crash (it's still wrong)
faithokamoto Jan 29, 2026
25f51c1
fix snarls
faithokamoto Jan 29, 2026
41cd375
fix reversedness for regular snarls
faithokamoto Jan 30, 2026
31febce
add tests (not yet passing)
faithokamoto Jan 31, 2026
9404c7a
fix tests
faithokamoto Feb 2, 2026
e90977a
toggle to count reversals stored in zipcodes
faithokamoto Feb 4, 2026
0b98399
declare intent
faithokamoto Feb 4, 2026
13cce61
adjust test cases (currently failure)
faithokamoto Feb 4, 2026
eafb6ec
please let me merge this
faithokamoto Feb 27, 2026
ef0f416
Merge branch 'master' into reversals
faithokamoto Feb 27, 2026
4df47e4
and we're back
faithokamoto Feb 27, 2026
9608c48
Merge branch 'master' into reversals
faithokamoto Mar 2, 2026
884b002
stub in rev loops
faithokamoto Mar 4, 2026
335b45f
Merge branch 'master' into reversals
faithokamoto Apr 27, 2026
ffe9374
simplify logic
faithokamoto Apr 27, 2026
05c8381
weird whitespace
faithokamoto Apr 27, 2026
9d5778a
attempt at forward loops
faithokamoto Apr 27, 2026
4babc50
silly
faithokamoto Apr 28, 2026
73fe8ae
well it builds a ziptree now (incorrectly)
faithokamoto Apr 28, 2026
d826d50
orientation changes
faithokamoto Apr 28, 2026
0cefb96
store a top level chain memory
faithokamoto Apr 28, 2026
5d531ec
format fix
faithokamoto Apr 28, 2026
510ba29
passes that one test case
faithokamoto Apr 28, 2026
7b6f5da
new test case & tweak to pass
faithokamoto Apr 29, 2026
af32921
misread some things
faithokamoto Apr 29, 2026
f6b1ee0
these moved
faithokamoto Apr 29, 2026
297b4bf
verbose for readability
faithokamoto Apr 29, 2026
17fcdcb
counting badly
faithokamoto Apr 30, 2026
b0ad927
bugfix
faithokamoto Apr 30, 2026
59a3781
more test cases pass
faithokamoto May 4, 2026
40a63c6
a little more test
faithokamoto May 4, 2026
a81f09d
avoid doing math on inf
faithokamoto May 4, 2026
fee2814
shift past loops to get to seeds
faithokamoto May 4, 2026
944a120
new test case
faithokamoto May 4, 2026
0bd956f
whoops
faithokamoto May 4, 2026
695f347
new test and code to partially pass
faithokamoto May 5, 2026
11918c8
messing up this merging case
faithokamoto May 5, 2026
0fb57bc
better merging
faithokamoto May 5, 2026
3b836d7
oops forgot this reset
faithokamoto May 5, 2026
cc7f378
new test case & tweak to pass
faithokamoto May 5, 2026
7b7f43a
new test case & tweak to pass
faithokamoto May 5, 2026
afcac2a
fixing random case 52
faithokamoto May 5, 2026
8f36b47
proper consolidation
faithokamoto May 5, 2026
15bf99f
first attempt at loop iteration
faithokamoto May 6, 2026
7defb64
bugfix for if we skip when never having left
faithokamoto May 6, 2026
538e0e8
when we take a reversal we want to start again
faithokamoto May 6, 2026
b2e735d
no longer need this special handling
faithokamoto May 6, 2026
38aada9
save a better index
faithokamoto May 6, 2026
9e2226e
this case never did what it was supposed to
faithokamoto May 6, 2026
0444c58
test case tweaks for loops
faithokamoto May 7, 2026
3631726
minor speed up
faithokamoto May 7, 2026
56eb782
Merge branch 'master' into reversals
faithokamoto May 7, 2026
8ff4514
Merge branch 'master' into reversals
faithokamoto May 8, 2026
289b737
Merge branch 'master' into reversals
faithokamoto May 11, 2026
dd49a67
Merge branch 'master' into reversals
faithokamoto May 21, 2026
95187d5
Merge branch 'master' into reversals
faithokamoto May 21, 2026
4bf1916
fix sorting
faithokamoto May 22, 2026
1acc57e
should also handle this case
faithokamoto May 26, 2026
383e1ad
add better forward loop handling
faithokamoto May 26, 2026
8688e5b
making some tests know about the new behavior
faithokamoto May 26, 2026
a2c2433
Merge branch 'master' into reversals
faithokamoto May 26, 2026
60ccdb4
make stuff match each other
faithokamoto Jun 1, 2026
4b569f1
only print if needed
faithokamoto Jun 1, 2026
578e20e
Merge branch 'master' into reversals
faithokamoto Jun 4, 2026
3f81a2d
Merge branch 'master' into reversals
faithokamoto Jun 10, 2026
f39d4d8
get rid of helper
faithokamoto Jun 17, 2026
9d0365c
Merge branch 'master' into reversals
faithokamoto Jun 17, 2026
68c0bc7
add ability to go through end node
faithokamoto Jun 17, 2026
d16ec86
just be told where the ends are
faithokamoto Jun 17, 2026
166b080
get rid of fake returns
faithokamoto Jun 18, 2026
96dbc89
double-guess
faithokamoto Jun 18, 2026
41ce14b
split fields
faithokamoto Jun 18, 2026
c5bcb2e
add in graph dist memory
faithokamoto Jun 18, 2026
0dc8bf2
pass graph dist mem furhter
faithokamoto Jun 18, 2026
a684a67
pass graph dist along far enough to use it
faithokamoto Jun 18, 2026
5e5dda0
oops
faithokamoto Jun 18, 2026
199a346
these need to remember graph dist too
faithokamoto Jun 18, 2026
db3199f
correct nowhere
faithokamoto Jun 18, 2026
659b215
bit better graph dist
faithokamoto Jun 18, 2026
725f395
save the correct distance
faithokamoto Jun 19, 2026
a9b6fc4
Merge branch 'master' into reversals
faithokamoto Jun 19, 2026
af96255
separate state for simplicity
faithokamoto Jun 24, 2026
133a360
not needed
faithokamoto Jun 24, 2026
dfe3a52
Merge branch 'master' into reversals
faithokamoto Jun 24, 2026
82d4a95
Merge branch 'master' into reversals
faithokamoto Jun 25, 2026
00bf3bb
save when possible
faithokamoto Jun 25, 2026
ccb4634
Merge branch 'master' into reversals
faithokamoto Jul 2, 2026
9238008
oops
faithokamoto Jul 2, 2026
00a2830
fix payload creation
faithokamoto Jul 2, 2026
73ab7fd
usually don't do extra tracking
faithokamoto Jul 2, 2026
899d71f
update test expectation
faithokamoto Jul 2, 2026
384b547
these don't need to be fancy
faithokamoto Jul 7, 2026
fb6a4ea
rename
faithokamoto Jul 7, 2026
2e96d57
don't call it memory
faithokamoto Jul 7, 2026
858348a
rename
faithokamoto Jul 7, 2026
f684ab9
use constants vs bit lookup
faithokamoto Jul 7, 2026
b246766
better export
faithokamoto Jul 7, 2026
3c01571
explain new behavior and put behind a flag
faithokamoto Jul 7, 2026
15ac453
Merge branch 'master' into reversals
faithokamoto Jul 8, 2026
3ba5d65
use hint dist
faithokamoto Jul 8, 2026
b0b8fe4
get rid of TracedItem
faithokamoto Jul 9, 2026
43d9984
subtypes
faithokamoto Jul 9, 2026
421033e
oops
faithokamoto Jul 9, 2026
6a67434
actually pass those values through
faithokamoto Jul 9, 2026
596652a
simpler
faithokamoto Jul 9, 2026
54af48d
need to move the iterator silly
faithokamoto Jul 9, 2026
6112246
and move here too
faithokamoto Jul 9, 2026
b5f3c45
wrong word silly
faithokamoto Jul 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 85 additions & 84 deletions src/algorithms/chain_items.cpp

Large diffs are not rendered by default.

131 changes: 71 additions & 60 deletions src/algorithms/chain_items.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -291,8 +291,11 @@ class Anchor {
/// Explain an Anchor to the given stream
ostream& operator<<(ostream& out, const Anchor& anchor);

// For doing scores with backtracing, we use this type, which is a
// score and a number for the place we came from to get it.
// For doing scores with backtracing, we use this type, which is
// - a score
// - a number for the place we came from to get it
// - the graph distance from that point (ignored for comparison purposes
// as it's just an annotation for later lookup, not part of the tracing)
class TracedScore {
Comment thread
faithokamoto marked this conversation as resolved.
Resolved
public:
/// What is the sentinel for an empty provenance?
Expand All @@ -304,7 +307,7 @@ class TracedScore {
/// What's the default value for an empty table cell?
/// Use a function instead of a constant because that's easier when we're just a header.
inline static TracedScore unset() {
return {0, nowhere(), 0};
return {0, nowhere(), numeric_limits<size_t>::max(), 0};
}

/// Max in a score from a DP table. If it wins, record provenance.
Expand Down Expand Up @@ -348,6 +351,8 @@ class TracedScore {
int score;
// Index of source score among possibilities/traceback pointer
size_t source;
// Graph distance from source (not considered in equality/comparison)
size_t graph_distance;
/// Supported paths
path_flags_t paths;
size_t rec_num=0;
Expand Down Expand Up @@ -415,33 +420,36 @@ struct ChainScoringScheme {
int consistency_bonus = 0;
};

/// A single chain result: scored chain plus the recombination count observed
/// on its endpoint.
/// TODO: Is there a better name for the abstraction this is getting at?
struct ChainWithRec {
// TODO: Shouldn't we split this into 2 fields?
std::pair<int, std::vector<size_t>> scored_chain;
// Positions (anchor indices) in the chain that introduce a recombination
// event between anchors. These correspond to anchors where we had to
// reset supported paths because the previous path set did not overlap
// with the next anchor's start paths.
std::vector<size_t> rec_positions;
// For each recombination event, an interval [left, right] of anchor
// indices bounding where the event must lie. `right` is the same anchor
// recorded in `rec_positions` (forward pass: first anchor incompatible
// with the prefix). `left` comes from a symmetric backward pass: the
// last anchor (going right-to-left) incompatible with the suffix.
// May be empty when forward and backward counts disagree, e.g. when
// internally recombinant anchors break the symmetry.
std::vector<std::pair<size_t, size_t>> rec_intervals;
/// A single chain result, with:
/// - `score` for the seqeunce of anchors
/// - `anchors` as a vector of indexes
/// - `graph_dists` as a vector of graph distances between anchors
struct SparseAnchorChain {
/// The chain score
size_t score = 0;
/// The anchors in the chain
std::vector<size_t> anchors;
/// Graph distances between successive anchor pairs (length |anchors| - 1)
std::vector<size_t> graph_dists;
};

/// Result of finding best chains: a list of chains each paired with the
/// recombination count observed at that chain's endpoint.
/// TODO: Can we get rid of this once we're sure it won't need more fields?
/// TODO: Is there a better name for this?
struct ChainsResult {
std::vector<ChainWithRec> chains;
/// A SparseAnchorChain with recombination fields added:
/// - `rec_positions` for which spots in the chain force a recombination
/// - `rec_intervals` for ranges where the recombination could lie
struct SparseAnchorChainWithRec : SparseAnchorChain {
/// Positions (anchor indices) in the chain that introduce a recombination
/// event between anchors. These correspond to anchors where we had to
/// reset supported paths because the previous path set did not overlap
/// with the next anchor's start paths.
std::vector<size_t> rec_positions;
/// For each recombination event, an interval [left, right] of anchor
/// indices bounding where the event must lie. `right` is the same anchor
/// recorded in `rec_positions` (forward pass: first anchor incompatible
/// with the prefix). `left` comes from a symmetric backward pass: the
/// last anchor (going right-to-left) incompatible with the suffix.
/// May be empty when forward and backward counts disagree, e.g. when
/// internally recombinant anchors break the symmetry.
std::vector<std::pair<size_t, size_t>> rec_intervals;
};

/**
Expand Down Expand Up @@ -552,21 +560,21 @@ TracedScore chain_items_dp(vector<TracedScore>& chain_scores,
* Trace back through in the given DP table from the best chain score.
*
* Returns tracebacks that visit disjoint sets of items, in score order, along
* with their penalties from the optimal score. The best_past_ending_score_ever
* with their scores. The best_past_ending_score_ever
* is *not* always the source of the first traceback, if there is a tie.
*
* Tracebacks are constrained to be nonoverlapping by stopping each traceback
* when the optimum place to come from has already been used. The second-best
* place to come from is *not* considered. It might be possible that two
* returned tracebacks could be pasted together to get a higher score, but it
* won't be possible to recombine two tracebacks to get a higher score; no
* edges followed between items will ever need to be cut.
* Tracebacks are constrained to be nonoverlapping by stopping each traceback
* when the optimum place to come from has already been used. The second-best
* place to come from is *not* considered. It might be possible that two
* returned tracebacks could be pasted together to get a higher score, but it
* won't be possible to recombine two tracebacks to get a higher score; no
* edges followed between items will ever need to be cut.
*/
vector<pair<vector<size_t>, int>> chain_items_traceback(const vector<TracedScore>& chain_scores,
const VectorView<Anchor>& to_chain,
const TracedScore& best_past_ending_score_ever,
const ChainScoringScheme& scheme = ChainScoringScheme(),
size_t max_tracebacks = 1);
vector<SparseAnchorChain> chain_items_traceback(const vector<TracedScore>& chain_scores,
const VectorView<Anchor>& to_chain,
const TracedScore& best_past_ending_score_ever,
const ChainScoringScheme& scheme = ChainScoringScheme(),
size_t max_tracebacks = 1);


/**
Expand All @@ -578,16 +586,16 @@ vector<pair<vector<size_t>, int>> chain_items_traceback(const vector<TracedScore
* Returns the scores and the list of indexes of items visited to achieve
* that score, in order, with multiple tracebacks in descending score order.
*/
ChainsResult find_best_chains(const VectorView<Anchor>& to_chain,
const SnarlDistanceIndex& distance_index,
const HandleGraph& graph,
int gap_open,
int gap_extension,
const ChainScoringScheme& scheme = ChainScoringScheme(),
size_t max_chains = 1,
const transition_iterator& for_each_transition = lookback_transition_iterator(150, 0, 100),
size_t max_indel_bases = 100,
bool show_work = false);
std::vector<SparseAnchorChainWithRec> find_best_chains(const VectorView<Anchor>& to_chain,
const SnarlDistanceIndex& distance_index,
const HandleGraph& graph,
int gap_open,
int gap_extension,
const ChainScoringScheme& scheme = ChainScoringScheme(),
size_t max_chains = 1,
const transition_iterator& for_each_transition = lookback_transition_iterator(150, 0, 100),
size_t max_indel_bases = 100,
bool show_work = false);

/**
* Chain up the given group of items. Determines the best score and
Expand All @@ -598,14 +606,14 @@ ChainsResult find_best_chains(const VectorView<Anchor>& to_chain,
* Returns the score and the list of indexes of items visited to achieve
* that score, in order.
*/
pair<int, vector<size_t>> find_best_chain(const VectorView<Anchor>& to_chain,
const SnarlDistanceIndex& distance_index,
const HandleGraph& graph,
int gap_open,
int gap_extension,
const ChainScoringScheme& scheme = ChainScoringScheme(),
const transition_iterator& for_each_transition = lookback_transition_iterator(150, 0, 100),
size_t max_indel_bases = 100);
SparseAnchorChainWithRec find_best_chain(const VectorView<Anchor>& to_chain,
const SnarlDistanceIndex& distance_index,
const HandleGraph& graph,
int gap_open,
int gap_extension,
const ChainScoringScheme& scheme = ChainScoringScheme(),
const transition_iterator& for_each_transition = lookback_transition_iterator(150, 0, 100),
size_t max_indel_bases = 100);

/**
* Score the given group of items. Determines the best score that can be
Expand All @@ -624,10 +632,13 @@ int score_chain_gap(size_t distance_difference, size_t average_anchor_length);
/// Determine if adding the new anchor would cause a recombination event
/// with respect to the old anchor, given their supported paths.
/// Returns 0 if no recombination, or 1 if there is a recombination.
int check_recombination(const Anchor& from, const Anchor& to);
int score_recombination(const Anchor& from, const Anchor& to);

/// Get distance in the graph, or std::numeric_limits<size_t>::max() if unreachable or beyond the limit.
size_t get_graph_distance(const Anchor& from, const Anchor& to, const SnarlDistanceIndex& distance_index, const HandleGraph& graph, size_t distance_limit = std::numeric_limits<size_t>::max());
/// If distance_return is non-inf, abort right away
/// Otherwise calculate distance and stick it in the distance_return value
void get_graph_distance(const Anchor& from, const Anchor& to, const SnarlDistanceIndex& distance_index, const HandleGraph& graph,
size_t& distance_return, size_t distance_limit = std::numeric_limits<size_t>::max());

/// Get distance in the read, or std::numeric_limits<size_t>::max() if unreachable.
size_t get_read_distance(const Anchor& from, const Anchor& to);
Expand Down
42 changes: 35 additions & 7 deletions src/algorithms/extract_connecting_graph.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ unordered_map<id_t, id_t> extract_connecting_graph(const HandleGraph* source,
DeletableHandleGraph* into,
int64_t max_len,
pos_t pos_1, pos_t pos_2,
bool strict_max_len) {
bool strict_max_len,
bool preserve_cycles_on_src_nodes,
nid_t* new_start_id,
nid_t* new_end_id) {
#ifdef debug_vg_algorithms
cerr << "[extract_connecting_graph] max len: " << max_len << ", pos 1: " << pos_1 << ", pos 2: " << pos_2 << endl;
#endif
Expand Down Expand Up @@ -111,6 +114,9 @@ unordered_map<id_t, id_t> extract_connecting_graph(const HandleGraph* source,
// the max length of the part of a path preceding the final node in each direction
int64_t forward_max_len = max_len - last_traversal_length;
int64_t backward_max_len = max_len - first_traversal_length;

bool seen_pos_1_both_ways = false;
bool seen_pos_2_both_ways = false;

// STEP 1: FORWARD SEARCH (TO EXTRACT SUBGRAPH)
// separately handle (common) edge case that both positions are on the same node
Expand Down Expand Up @@ -159,7 +165,9 @@ unordered_map<id_t, id_t> extract_connecting_graph(const HandleGraph* source,
<< source->get_id(trav.handle) << " " << source->get_is_reverse(trav.handle)
<< " -> " << next_id << " " << next_rev << endl;
#endif
found_target = found_target || (next_id == id(pos_2) && next_rev == is_rev(pos_2));
found_target |= (next_id == id(pos_2) && next_rev == is_rev(pos_2));
seen_pos_1_both_ways |= (next_id == id(pos_1) && next_rev != is_rev(pos_1));
seen_pos_2_both_ways |= (next_id == id(pos_2) && next_rev != is_rev(pos_2));
max_id = max(max_id, next_id);

// make sure the node is in
Expand Down Expand Up @@ -282,14 +290,27 @@ unordered_map<id_t, id_t> extract_connecting_graph(const HandleGraph* source,
switch (colocation) {
case SeparateNodes:
{
// split the node, update the IDs, and clean up the other side
cut_handle_1 = into->truncate_handle(into_handle_1, true, offset(pos_1));
id_trans.erase(id(pos_1));
if (seen_pos_1_both_ways && preserve_cycles_on_src_nodes) {
// make a new node which will preserve edges on right
handle_t dup_node = duplicate_node(into_handle_1, false, true);
cut_handle_1 = into->truncate_handle(dup_node, true, offset(pos_1));
} else {
// split the node, update the IDs, and clean up the other side
cut_handle_1 = into->truncate_handle(into_handle_1, true, offset(pos_1));
id_trans.erase(id(pos_1));
}
id_trans[into->get_id(cut_handle_1)] = id(pos_1);

// repeat for the second position
cut_handle_2 = into->truncate_handle(into_handle_2, false, offset(pos_2));
id_trans.erase(id(pos_2));
if (seen_pos_2_both_ways && preserve_cycles_on_src_nodes) {
// make a new node which will preserve edges on left
handle_t dup_node = duplicate_node(into_handle_2, true, false);
cut_handle_2 = into->truncate_handle(dup_node, false, offset(pos_2));
} else {
// split the node, update the IDs, and clean up the other side
cut_handle_2 = into->truncate_handle(into_handle_2, false, offset(pos_2));
id_trans.erase(id(pos_2));
}
id_trans[into->get_id(cut_handle_2)] = id(pos_2);

break;
Expand Down Expand Up @@ -522,6 +543,13 @@ unordered_map<id_t, id_t> extract_connecting_graph(const HandleGraph* source,
// on the first node being offset (however this information is fully contained in the arguments of
// the function, which are obviously available in the environment that calls it)
crash_unless(id_trans.size() == into->get_node_count());
// Remembere where the edge nodes ended up
if (new_start_id != nullptr) {
*new_start_id = into->get_id(cut_handle_1);
}
if (new_end_id != nullptr) {
*new_end_id = into->get_id(cut_handle_2);
}
return id_trans;
}

Expand Down
31 changes: 20 additions & 11 deletions src/algorithms/extract_connecting_graph.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ namespace algorithms {
/// Fills a DeletableHandleGraph with the subgraph of a HandleGraph that connects two positions. The nodes
/// that contain the two positions will be 'cut' at the position and will be tips in the returned graph. The
/// algorithm guarantees that 'into' contains all walks between pos_1 and pos_2 under the maximum length
/// except walks that include a cycle involving either position. If no walk between the two positions under
/// the maximum length exists, 'into' will be left empty. An error is thrown if 'into' is not empty when
/// passed to function.
/// except walks that include a cycle involving either position (unless preserve_cycles_on_src_node is set,
/// in which case the cycle is kept and the node is duplicated as needed).
/// If no walk between the two positions under the maximum length exists, 'into' will be left empty.
/// An error is thrown if 'into' is not empty when passed to function.
///
/// If pos_1 and pos_2 face each other on the same node, the intervening
/// portion of the node is produced in into. If they are on the same node
Expand All @@ -37,22 +38,30 @@ namespace algorithms {
/// may be tips.
///
/// Args:
/// source graph to extract subgraph from
/// into graph to extract into
/// max_len guarantee finding walks along which pos_1 and pos_2 are this distance apart
/// pos_1 start position, subgraph walks begin from here in same orientation
/// pos_2 end position, subgraph walks end here in the same orientation
/// strict_max_len only extract nodes and edges if they fall on some walk between pos_1 and pos_2
/// that is under the maximum length (implies only_walks = true)
/// source graph to extract subgraph from
/// into graph to extract into
/// max_len guarantee finding walks along which pos_1 and pos_2 are this distance apart
/// pos_1 start position, subgraph walks begin from here in same orientation
/// pos_2 end position, subgraph walks end here in the same orientation
/// strict_max_len only extract nodes and edges if they fall on some walk between pos_1 and pos_2
/// that is under the maximum length (implies only_walks = true)
/// preserve_cycles_on_src_nodes whether to allow walks that cycle through source nodes
/// by duplicating as necessary
///
/// Returns: a map from node ids in the extracted graph to the node ids in
/// the original graph. The map and the graph will have the same number of
/// entries.
///
/// If new_start_id is not null it will become the start node's new ID.
/// If new_end_id is not null it will become the end node's new ID.
unordered_map<id_t, id_t> extract_connecting_graph(const HandleGraph* source,
DeletableHandleGraph* into,
int64_t max_len,
pos_t pos_1, pos_t pos_2,
bool strict_max_len = false);
bool strict_max_len = false,
bool preserve_cycles_on_src_nodes = false,
nid_t* new_start_id = nullptr,
nid_t* new_end_id = nullptr);

}
}
Expand Down
Loading
Loading