-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclip-vg.cpp
More file actions
1732 lines (1601 loc) · 82.6 KB
/
Copy pathclip-vg.cpp
File metadata and controls
1732 lines (1601 loc) · 82.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Chop regions (from BED File) out of paths in vg graphs, creating subpath names and cutting out nodes or parts of nodes
// Assumes that:
// - regions don't overlap (error otherwise)
// - regions are only ever part of at most one path each (assert false otherwise)
//#define debug
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <fstream>
#include <deque>
#include <unordered_map>
#include <unistd.h>
#include <getopt.h>
#include <limits>
#include <cmath>
#include "bdsg/packed_graph.hpp"
#include "bdsg/hash_graph.hpp"
using namespace std;
using namespace handlegraph;
using namespace bdsg;
void help(char** argv) {
cerr << "usage: " << argv[0] << " [options] <graph>" << endl
<< "Chop out path intervals from a vg graph" << endl
<< endl
<< "options: " << endl
<< " -b, --bed FILE Intervals to clip in BED format" << endl
<< " -m, --min-length N Only clip paths of length < N" << endl
<< " -u, --max-unaligned N Clip out unaligned regions of length > N" << endl
<< " -a, --anchor PREFIX If set, consider regions not aligned to a path with PREFIX unaligned (with -u)" << endl
<< " -k, --flank N Extend each clipped interval outward by up to N bp for as long as" << endl
<< " unaligned sequence stays dense (see -T), using the same test for" << endl
<< " unaligned that -u does. Removes the fringe left where an aligner" << endl
<< " extended anchors into a repeat but not far enough to be clipped." << endl
<< " N is the main control: inside a repeat the gate seldom closes" << endl
<< " on its own, so the cap is what decides how much goes." << endl
<< " -T, --flank-threshold F Keep extending while more than this fraction of bases are" << endl
<< " unaligned (0-1). Negative means calibrate against this graph," << endl
<< " which is strongly advisable: how much unaligned sequence a" << endl
<< " pangenome carries varies several-fold between graphs and is" << endl
<< " not predictable from any input property [-1]" << endl
<< " -e, --ref-prefix STR Forwardize (but don't clip) paths whose name begins with STR" << endl
<< " -F, --forwardize-nonref Also forwardize any node that no path visits forward. Needs -e." << endl
<< " This mints new node ids, so it must not be used on a graph whose" << endl
<< " id space has to stay compatible with one produced earlier." << endl
<< " -c, --allow-cycle Do not fail with error when reference cycle detected" << endl
<< " -f, --force-clip Don't abort with error if clipped node overlapped by multiple paths" << endl
<< " -r, --name-replace S1>S2 Replace (first occurrence of) S1 with S2 in all path names" << endl
<< " -n, --no-orphan-filter Don't filter out new subpaths that don't align to anything" << endl
<< " -d, --drop-path PREFIX Remove all paths with given PREFIX, and all nodes that are on no other paths (done after other filters)" << endl
<< " -L, --leave-aligned When used in conjunction with -d, paths are prserved if they align to a non-dropped path" << endl
<< " -o, --out-bed FILE Save all clipped intervals here" << endl
<< " -p, --progress Print progress" << endl
<< endl;
}
static unordered_map<string, vector<pair<int64_t, int64_t>>> load_bed(istream& bed_stream, const string& ref_prefix);
static unordered_map<string, vector<pair<int64_t, int64_t>>> find_unaligned(const PathHandleGraph* graph, int64_t max_unaligned,
const string& ref_prefix, const string& anchor_prefix,
const unordered_set<nid_t>& anchor_nodes);
static void build_anchor_nodes(const PathHandleGraph* graph, const string& anchor_prefix,
unordered_set<nid_t>& anchor_nodes_out);
static unique_ptr<MutablePathMutableHandleGraph> load_graph(istream& graph_stream);
static vector<string> &split_delims(const string &s, const string& delims, vector<string> &elems);
static void chop_path_intervals(MutablePathMutableHandleGraph* graph,
const unordered_map<string, vector<pair<int64_t, int64_t>>>& bed_intervals,
bool force_clip, bool orphan_filter,
const string& ref_prefix,
bool progress);
static pair<unordered_set<handle_t>, vector<path_handle_t>> chop_path(MutablePathMutableHandleGraph* graph,
path_handle_t path_handle,
const vector<pair<int64_t, int64_t>>& intervals);
static void replace_path_name_substrings(MutablePathMutableHandleGraph* graph, const vector<string>& to_replace,
bool progress);
static void forwardize_paths(MutablePathMutableHandleGraph* graph, const string& ref_prefix, bool allow_ref_cycles, bool progress);
static void forwardize_nonref_paths(MutablePathMutableHandleGraph* graph, const string& ref_prefix, bool progress);
static void flip_node(MutablePathMutableHandleGraph* graph, nid_t node_id);
static vector<unordered_set<nid_t>> weakly_connected_components(const HandleGraph* graph);
static void drop_paths(MutablePathMutableHandleGraph* graph, const string& drop_prefix, bool leave_aligned, bool progress);
// Is this step aligned? With an anchor prefix that means the node sits on one of those paths;
// without one it means some other path visits the node. find_unaligned uses this to cut intervals
// and extend_flanks uses it to decide how far to extend them, so they never disagree.
static bool step_is_aligned(const PathHandleGraph* graph, handle_t handle, path_handle_t path_handle,
const unordered_set<nid_t>& anchor_nodes, bool have_anchor_prefix) {
if (anchor_nodes.count(graph->get_id(handle))) {
return true;
}
if (have_anchor_prefix) {
return false;
}
bool aligned = false;
graph->for_each_step_on_handle(handle, [&](step_handle_t other) {
if (graph->get_path_handle_of_step(other) != path_handle) {
aligned = true;
}
return !aligned;
});
return aligned;
}
static void extend_flanks(const PathHandleGraph* graph,
unordered_map<string, vector<pair<int64_t, int64_t>>>& intervals,
int64_t max_flank, double threshold,
const unordered_set<nid_t>& anchor_nodes, bool have_anchor_prefix,
bool progress);
static unordered_map<string, vector<pair<int64_t, int64_t>>> get_path_intervals(const PathHandleGraph* graph);
static unordered_map<string, vector<pair<int64_t, int64_t>>> get_clipped_intervals(
const unordered_map<string, vector<pair<int64_t, int64_t>>>& input_intervals,
const unordered_map<string, vector<pair<int64_t, int64_t>>>& output_intervals);
// A path's name with any subrange stripped off, so that an input path and the subpaths clipped
// out of it share a key. get_path_name() spells the subrange out as "name[start-end]", which would
// file every output subpath under a key no input path has.
static inline string strip_subpath_name(const string& path_name) {
PathSense sense;
string sample;
string locus;
size_t haplotype;
size_t phase_block;
subrange_t subrange;
PathMetadata::parse_path_name(path_name, sense, sample, locus, haplotype, phase_block, subrange);
return PathMetadata::create_path_name(sense, sample, locus, haplotype, phase_block,
PathMetadata::NO_SUBRANGE);
}
// Create a subpath name (todo: make same function in vg consistent (it only includes start))
static inline string make_subpath_name(const string& path_name, size_t offset, size_t length) {
PathSense sense;
string sample;
string locus;
size_t haplotype;
size_t phase_block;
subrange_t subrange;
PathMetadata::parse_path_name(path_name, sense, sample, locus, haplotype, phase_block, subrange);
subrange.first = subrange != PathMetadata::NO_SUBRANGE ? subrange.first : 0;
subrange.first += offset;
subrange.second = subrange.first + length;
return PathMetadata::create_path_name(sense, sample, locus, haplotype, phase_block, subrange);
}
int main(int argc, char** argv) {
string bed_path;
// shared by find_unaligned and extend_flanks so both agree on what unaligned means
unordered_set<nid_t> anchor_nodes;
int64_t min_length = 0;
int64_t max_unaligned = 0;
int64_t flank = 0;
double flank_threshold = -1.;
bool flank_threshold_set = false;
string anchor_prefix;
string ref_prefix;
bool forwardize_nonref = false;
bool allow_ref_cycles = false;
size_t input_count = 0;
bool force_clip = false;
bool orphan_filter = true;
bool progress = false;
vector<string> replace_list;
string drop_prefix;
bool leave_aligned_drop_paths = false;
string out_bed_path;
int c;
optind = 1;
while (true) {
static const struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"bed", required_argument, 0, 'b'},
{"min-length", required_argument, 0, 'm'},
{"max-unaligned", required_argument, 0, 'u'},
{"anchor", required_argument, 0, 'a'},
{"flank", required_argument, 0, 'k'},
{"flank-threshold", required_argument, 0, 'T'},
{"ref-prefix", required_argument, 0, 'e'},
{"forwardize-nonref", no_argument, 0, 'F'},
{"allow-cycle", no_argument, 0, 'c'},
{"force-clip", no_argument, 0, 'f'},
{"name-replace", required_argument, 0, 'r'},
{"no-orphan-filter", no_argument, 0, 'n'},
// the spelling that shipped, kept working so nobody's script breaks
{"no-orphan_filter", no_argument, 0, 'n'},
{"drop-prefix", required_argument, 0, 'd'},
{"leave-aligned", no_argument, 0, 'L'},
{"out-bed", required_argument, 0, 'o'},
{"progress", no_argument, 0, 'p'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "hpb:m:u:a:k:T:e:Fcfnr:d:Lo:",
long_options, &option_index);
// Detect the end of the options.
if (c == -1)
break;
switch (c)
{
case 'b':
bed_path = optarg;
++input_count;
break;
case 'm':
min_length = stol(optarg);
++input_count;
break;
case 'u':
max_unaligned = stol(optarg);
++input_count;
break;
case 'a':
anchor_prefix = optarg;
break;
case 'k':
flank = stol(optarg);
break;
case 'T':
flank_threshold = stod(optarg);
flank_threshold_set = true;
break;
case 'e':
ref_prefix = optarg;
break;
case 'F':
forwardize_nonref = true;
break;
case 'c':
allow_ref_cycles = true;
break;
case 'f':
force_clip = true;
break;
case 'n':
orphan_filter = false;
break;
case 'r':
replace_list.push_back(optarg);
break;
case 'd':
drop_prefix = optarg;
break;
case 'L':
leave_aligned_drop_paths = true;
break;
case 'o':
out_bed_path = optarg;
break;
case 'p':
progress = true;
break;
case 'h':
case '?':
/* getopt_long already printed an error message. */
help(argv);
exit(1);
break;
default:
abort ();
}
}
if (argc <= 1) {
help(argv);
return 1;
}
// Parse the positional argument
if (optind >= argc) {
cerr << "[clip-vg] error: too few arguments" << endl;
help(argv);
return 1;
}
if (optind != argc - 1) {
cerr << "[clip-vg] error: too many arguments" << endl;
help(argv);
return 1;
}
if (forwardize_nonref && ref_prefix.empty()) {
cerr << "[clip-vg] error: -F/--forwardize-nonref requires -e/--ref-prefix" << endl;
return 1;
}
if (input_count > 1) {
cerr << "[clip-vg] error: at most one of -b, -m or -u can be used at a time" << endl;
return 1;
}
if (input_count == 0 && replace_list.empty() && ref_prefix.empty()) {
cerr << "[clip-vg] error: at east one of -b, -m, -u, -e or -r must be specified" << endl;
return 1;
}
if (!anchor_prefix.empty() && max_unaligned <= 0 && flank <= 0) {
// -a used to matter only to -u. It now also picks the test -k extends on, so it is
// meaningful alongside -b, where the intervals come from a file but the gate still has to
// decide what counts as unaligned.
cerr << "[clip-vg] error: -a cannot be used without -u or -k" << endl;
return 1;
}
if (leave_aligned_drop_paths && drop_prefix.empty()) {
cerr << "[clip-vg] error: -L can only be used with -d" << endl;
return 1;
}
// -0.0 is not less than zero, so it would slip past the "negative means calibrate" test in
// extend_flanks() and land on threshold 0 -- the most aggressive setting there is, where a long
// node scores 0 rather than negative and the walk can never die on clean sequence. Python's
// str(-0.0) is "-0.0", so a config carrying it reaches us in this form. Normalise it here.
if (std::signbit(flank_threshold)) {
flank_threshold = -1.;
}
if (std::isnan(flank_threshold)) {
cerr << "[clip-vg] error: -T/--flank-threshold is not a number. Every node would score NaN,"
<< " no comparison against the running maximum would ever be true, and -k would do"
<< " nothing at all without saying so. Use a negative value to calibrate." << endl;
return 1;
}
if (flank_threshold >= 1.) {
cerr << "[clip-vg] error: -T/--flank-threshold must be less than 1: at 1 or above every"
<< " node scores negative and no flank is ever trimmed. Use a negative value to"
<< " calibrate against the graph." << endl;
return 1;
}
// -k reshapes clipped intervals, so it needs a source of them. -m makes exactly one interval
// per path, spanning the whole path, which leaves nothing outside to extend into. Warn rather
// than fail: a wrapper may pass -k unconditionally and turn it off with -k 0, and failing a
// multi-hour job over that would be worse.
if (flank > 0) {
if (input_count == 0) {
cerr << "[clip-vg] warning: -k/--flank needs clipped intervals to act on, but none of"
<< " -b, -m or -u was given" << endl;
} else if (min_length != 0) {
cerr << "[clip-vg] warning: -k/--flank has no effect with -m/--min-length, which clips"
<< " whole paths" << endl;
}
}
if (flank_threshold_set && flank <= 0) {
cerr << "[clip-vg] warning: -T/--flank-threshold only applies with -k/--flank" << endl;
}
// 0 is in the documented range and is a coherent thing to ask for -- extend unconditionally,
// which is the no-gate control -- but it does not read that way, so say what it does. An
// aligned base scores exactly 0 at this threshold rather than negative, so the running total
// never falls and the walk cannot die on aligned sequence.
if (flank > 0 && flank_threshold == 0.) {
cerr << "[clip-vg] warning: -T 0 gates nothing: aligned sequence scores 0 rather than"
<< " negative, so every trim runs out to the -k cap. Pass a positive threshold to"
<< " gate on unaligned density, or a negative one to calibrate." << endl;
}
string graph_path = argv[optind++];
ifstream graph_stream(graph_path);
if (!graph_stream) {
cerr << "[clip-vg] error: Unable to open input graph " << graph_path << endl;
return 1;
}
unique_ptr<MutablePathMutableHandleGraph> graph = load_graph(graph_stream);
graph_stream.close();
if (progress) {
cerr << "[clip-vg]: Loaded graph" << endl;
}
// Both the interval search and the flank gate ask the same question of a node, so build the
// table once here. -k can be used with -b, where find_unaligned never runs, and an empty
// table would make every node look unaligned.
build_anchor_nodes(graph.get(), anchor_prefix, anchor_nodes);
// Catch a mistyped -e here, before anything has been clipped. Unaligned regions are measured
// against the reference, so a prefix that matches no path makes every base look unaligned and
// the orphan filter then removes the entire graph -- silently, with exit 0.
if (!ref_prefix.empty()) {
bool found_ref_path = false;
graph->for_each_path_handle([&](path_handle_t path_handle) {
if (graph->get_path_name(path_handle).substr(0, ref_prefix.length()) == ref_prefix) {
found_ref_path = true;
}
return !found_ref_path;
});
if (!found_ref_path) {
cerr << "[clip-vg] error: No path name begins with \"" << ref_prefix
<< "\" given with -e/--ref-prefix" << endl;
return 1;
}
}
unordered_map<string, vector<pair<int64_t, int64_t>>> input_graph_intervals;
if (!out_bed_path.empty()) {
input_graph_intervals = get_path_intervals(graph.get());
if (progress) {
cerr << "[clip-vg]: Graph has " << input_graph_intervals.size() << " paths." << endl;
}
}
unordered_map<string, vector<pair<int64_t, int64_t>>> bed_intervals;
if (!bed_path.empty()) {
ifstream bed_stream(bed_path);
if (!bed_stream) {
cerr << "[clip-vg] error: Unable to open input BED file " << bed_path << endl;
return 1;
}
bed_intervals = load_bed(bed_stream, ref_prefix);
} else if (min_length != 0) {
// apply min length to all paths to get intervals
graph->for_each_path_handle([&](path_handle_t path_handle) {
string path_name = graph->get_path_name(path_handle);
if (ref_prefix.empty() || path_name.substr(0, ref_prefix.length()) != ref_prefix) {
int64_t path_length = 0;
graph->for_each_step_in_path(path_handle, [&](step_handle_t step_handle) {
path_length += graph->get_length(graph->get_handle_of_step(step_handle));
return path_length < min_length;
});
if (path_length < min_length) {
bed_intervals[path_name].push_back(make_pair(0, path_length));
}
}
});
} else if (max_unaligned != 0) {
// apply max unaligned length to all paths
if (progress) {
cerr << "[clip-vg]: Finding unaligned intervals >= " << max_unaligned
<< " using anchor prefix " << anchor_prefix << " and ref prefix " << ref_prefix << endl;
}
bed_intervals = find_unaligned(graph.get(), max_unaligned, ref_prefix, anchor_prefix,
anchor_nodes);
}
if (flank > 0 && !bed_intervals.empty()) {
extend_flanks(graph.get(), bed_intervals, flank, flank_threshold, anchor_nodes,
!anchor_prefix.empty(), progress);
// Mott's rule walks past a locally aligned stretch when unaligned sequence resumes beyond
// it, so two intervals with a short gap between them can each extend across it and end up
// overlapping. chop_path requires sorted disjoint intervals, so collapse those. Measured
// 3 collapses on a 118-haplotype chrY and 93 on chr21, so this is not a corner case.
size_t num_overlaps = 0;
for (auto& bi : bed_intervals) {
vector<pair<int64_t, int64_t>>& intervals = bi.second;
if (intervals.size() < 2) {
continue;
}
sort(intervals.begin(), intervals.end());
vector<pair<int64_t, int64_t>> merged;
merged.push_back(intervals[0]);
for (size_t i = 1; i < intervals.size(); ++i) {
// Only an actual overlap. gap == 0 is book-ended, which load_bed has always
// accepted and chop_path has always handled -- merging those would drop a
// breakpoint and renumber the nodes a plain -b run has always emitted.
if (intervals[i].first < merged.back().second) {
++num_overlaps;
merged.back().second = max(merged.back().second, intervals[i].second);
} else {
merged.push_back(intervals[i]);
}
}
swap(intervals, merged);
}
if (progress && num_overlaps > 0) {
cerr << "[clip-vg]: Collapsed " << num_overlaps
<< " intervals that -k extended into each other" << endl;
}
}
if (progress) {
size_t num_intervals = 0;
for (auto& bi : bed_intervals) {
num_intervals += bi.second.size();
}
cerr << "[clip-vg]: Clipping " << num_intervals << " intervals over " << bed_intervals.size()
<< " sequences" << endl;
}
if (!bed_intervals.empty()) {
chop_path_intervals(graph.get(), bed_intervals, force_clip, orphan_filter, ref_prefix, progress);
}
if (!ref_prefix.empty()) {
forwardize_paths(graph.get(), ref_prefix, allow_ref_cycles, progress);
if (forwardize_nonref) {
forwardize_nonref_paths(graph.get(), ref_prefix, progress);
}
}
if (!replace_list.empty()) {
replace_path_name_substrings(graph.get(), replace_list, progress);
}
if (!drop_prefix.empty()) {
drop_paths(graph.get(), drop_prefix, leave_aligned_drop_paths, progress);
}
if (!out_bed_path.empty()) {
unordered_map<string, vector<pair<int64_t, int64_t>>> output_graph_intervals = get_path_intervals(graph.get());
#ifdef debug
for (const auto& xx : output_graph_intervals) {
cerr << " got output intervals " << xx.first << " count = " << xx.second.size() << endl;
}
#endif
unordered_map<string, vector<pair<int64_t, int64_t>>> clipped_graph_intervals = get_clipped_intervals(input_graph_intervals, output_graph_intervals);
ofstream out_bed_file(out_bed_path);
size_t icount = 0;
for (const auto& pi : clipped_graph_intervals) {
for (const auto& i : pi.second) {
out_bed_file << pi.first << "\t" << i.first << "\t" << i.second << "\n";
++icount;
}
}
out_bed_file.flush();
if (progress) {
cerr << "[clip-vg]: Outputted " << icount << " clipped intervals to " << out_bed_path << endl;
}
}
dynamic_cast<SerializableHandleGraph*>(graph.get())->serialize(cout);
return 0;
}
unordered_map<string, vector<pair<int64_t, int64_t>>> load_bed(istream& bed_stream, const string& ref_prefix) {
// load bed
unordered_map<string, vector<pair<int64_t, int64_t>>> intervals;
string buffer;
while (getline(bed_stream, buffer)) {
vector<string> toks;
split_delims(buffer, "\t\n", toks);
if (toks.size() >= 3) {
string& name = toks[0];
if (ref_prefix.empty() || name.substr(0, ref_prefix.length()) != ref_prefix) {
int64_t start = stol(toks[1]);
int64_t end = stol(toks[2]);
intervals[name].push_back(make_pair(start, end));
}
}
}
// verify bed
for (auto& seq_intervals : intervals) {
sort(seq_intervals.second.begin(), seq_intervals.second.end(),
[](const pair<int64_t, int64_t>& b1, const pair<int64_t, int64_t>& b2) {
return b1.first < b2.first || (b1.first == b2.first && b1.second < b2.second);
});
for (size_t i = 1; i < seq_intervals.second.size(); ++i) {
if (seq_intervals.second[i].first < seq_intervals.second[i-1].second) {
cerr << "Overlapping bed intervals found:\n"
<< " " << seq_intervals.first << "\t"
<< seq_intervals.second[i-1].first << "\t"
<< seq_intervals.second[i-1].second << endl
<< " " << seq_intervals.first << "\t"
<< seq_intervals.second[i].first << "\t"
<< seq_intervals.second[i].second << endl
<< "These are not supported. Please clean up (ex with bedools merge) first" << endl;
exit(1);
}
}
}
return intervals;
}
// anchor-prefix means we consider a node unaligned if it doesn't align to a path with that prefix,
// so we need a table of the nodes on those paths. Built here rather than inside find_unaligned
// because -k needs it too, and -k can be given with -b, where find_unaligned never runs.
void build_anchor_nodes(const PathHandleGraph* graph, const string& anchor_prefix,
unordered_set<nid_t>& anchor_nodes_out) {
if (anchor_prefix.empty()) {
return;
}
graph->for_each_path_handle([&](path_handle_t path_handle) {
string path_name = graph->get_path_name(path_handle);
if (path_name.compare(0, anchor_prefix.length(), anchor_prefix) == 0) {
graph->for_each_step_in_path(path_handle, [&](step_handle_t step_handle) {
anchor_nodes_out.insert(graph->get_id(graph->get_handle_of_step(step_handle)));
});
}
});
}
unordered_map<string, vector<pair<int64_t, int64_t>>> find_unaligned(const PathHandleGraph* graph, int64_t max_unaligned,
const string& ref_prefix, const string& anchor_prefix,
const unordered_set<nid_t>& anchor_nodes) {
unordered_map<string, vector<pair<int64_t, int64_t>>> intervals;
graph->for_each_path_handle([&](path_handle_t path_handle) {
string path_name = graph->get_path_name(path_handle);
if (ref_prefix.empty() || path_name.substr(0, ref_prefix.length()) != ref_prefix) {
int64_t offset = 0;
int64_t start = -1;
graph->for_each_step_in_path(path_handle, [&](step_handle_t step_handle) {
handle_t handle = graph->get_handle_of_step(step_handle);
int64_t len = (int64_t)graph->get_length(handle);
bool aligned = step_is_aligned(graph, handle, path_handle, anchor_nodes,
!anchor_prefix.empty());
// start an unaligned interval
if (start < 0 && aligned == false) {
start = offset;
}
// end an unaligned interval
if (aligned == true) {
if (start >= 0 && offset - start > max_unaligned) {
intervals[path_name].push_back(make_pair(start, offset));
}
start = -1;
}
offset += len;
});
if (start >= 0 && offset - start > max_unaligned) {
intervals[path_name].push_back(make_pair(start, offset));
}
}
});
return intervals;
}
unique_ptr<MutablePathMutableHandleGraph> load_graph(istream& graph_stream) {
char magic_bytes[4];
graph_stream.read(magic_bytes, 4);
uint32_t magic_number = ntohl(*((uint32_t*) magic_bytes));
graph_stream.clear();
graph_stream.seekg(0, ios::beg);
MutablePathMutableHandleGraph* graph;
if (magic_number == PackedGraph().get_magic_number()) {
graph = new PackedGraph();
} else if (magic_number == HashGraph().get_magic_number()) {
graph = new HashGraph();
} else {
cerr << "Unable to parse input graph with magic number " << magic_number << endl;
exit(1);
}
dynamic_cast<SerializableHandleGraph*>(graph)->deserialize(graph_stream);
return unique_ptr<MutablePathMutableHandleGraph>(graph);
}
vector<string> &split_delims(const string &s, const string& delims, vector<string> &elems) {
size_t start = string::npos;
for (size_t i = 0; i < s.size(); ++i) {
if (delims.find(s[i]) != string::npos) {
if (start != string::npos && i > start) {
elems.push_back(s.substr(start, i - start));
}
start = string::npos;
} else if (start == string::npos) {
start = i;
}
}
if (start != string::npos && start < s.size()) {
elems.push_back(s.substr(start, s.size() - start));
}
return elems;
}
void chop_path_intervals(MutablePathMutableHandleGraph* graph,
const unordered_map<string, vector<pair<int64_t, int64_t>>>& bed_intervals,
bool force_clip, bool orphan_filter, const string& ref_prefix,
bool progress) {
// keep some stats to print
size_t chopped_paths = 0;
size_t chopped_nodes = 0;
size_t chopped_bases = 0;
// careful not to iterate and chop, as we could hit new subpaths made
vector<path_handle_t> path_handles;
graph->for_each_path_handle([&](path_handle_t path_handle) {
path_handles.push_back(path_handle);
});
// when force_clip is true, store handles here to given them second chance at destruction
// after all paths are deleted
unordered_set<nid_t> to_destroy;
// newly created subpaths
vector<path_handle_t> subpaths;
// paths to destroy (faster to do in single api call)
vector<path_handle_t> paths_to_destroy;
for (auto path_handle : path_handles) {
string path_name = graph->get_path_name(path_handle);
auto it = bed_intervals.find(path_name);
bool was_chopped = false;
if (it != bed_intervals.end()) {
if (progress) {
cerr << "[clip-vg]: Clipping " << it->second.size() << " intervals from path " << path_name << endl;
}
auto chopped_handles_subpaths = chop_path(graph, path_handle, it->second);
auto& chopped_handles = chopped_handles_subpaths.first;
subpaths.insert(subpaths.end(), chopped_handles_subpaths.second.begin(), chopped_handles_subpaths.second.end());
if (!chopped_handles.empty()) {
#ifdef debug
cerr << "adding path to destroy list" << graph->get_path_name(path_handle) << endl;
#endif
paths_to_destroy.push_back(path_handle);
for (handle_t handle : chopped_handles) {
if (force_clip) {
to_destroy.insert(graph->get_id(handle));
} else {
vector<step_handle_t> steps = graph->steps_of_handle(handle);
bool aligned = false;
for (size_t i = 0; i < steps.size() && !aligned; ++i) {
string other_path_name = graph->get_path_name(graph->get_path_handle_of_step(steps[i]));
if (path_name.substr(0, path_name.rfind("[")) !=
other_path_name.substr(0, other_path_name.rfind("["))) {
aligned = true;
}
}
if (!aligned) {
chopped_bases += graph->get_length(handle);
was_chopped = true;
++chopped_nodes;
to_destroy.insert(graph->get_id(handle));
} else {
cerr << "[clip-vg]: Unable to clip node " << graph->get_id(handle) << ":" << graph->get_is_reverse(handle)
<< " in path " << path_name << " because it is found in the following other paths:\n";
for (step_handle_t step : graph->steps_of_handle(handle)) {
cerr <<"\t" << graph->get_path_name(graph->get_path_handle_of_step(step)) << endl;
}
cerr << " Use the -f option to not abort in this case" << endl;
exit(1);
}
}
}
}
}
if (was_chopped) {
++chopped_paths;
}
}
// delete all the paths
#ifdef debug
cerr << "destroying " << paths_to_destroy.size() << " paths" << endl;
#endif
graph->destroy_paths(paths_to_destroy);
paths_to_destroy.clear();
// trim out fragments between clipped regions that would otherwise be left disconnected from the graph
size_t removed_subpath_count = 0;
size_t removed_subpath_base_count = 0;
size_t removed_component_count = 0;
size_t removed_component_base_count = 0;
if (orphan_filter) {
for (path_handle_t subpath_handle : subpaths) {
bool connected = false;
graph->for_each_step_in_path(subpath_handle, [&](step_handle_t step_handle) {
connected = graph->steps_of_handle(graph->get_handle_of_step(step_handle)).size() > 1;
return !connected;
});
if (!connected) {
graph->for_each_step_in_path(subpath_handle, [&](step_handle_t step_handle) {
handle_t handle = graph->get_handle_of_step(step_handle);
to_destroy.insert(graph->get_id(handle));
removed_subpath_base_count += graph->get_length(handle);
});
paths_to_destroy.push_back(subpath_handle);
if (progress) {
cerr << "[clip-vg]: Removing orphaned subpath " << graph->get_path_name(subpath_handle) << endl;
}
++removed_subpath_count;
}
}
graph->destroy_paths(paths_to_destroy);
// use the reference path prefix (if given) to clip out components that aren't anchored to it
// (this would take care of above filter, but we leave that one as it's not dependent on path name)
if (!ref_prefix.empty()) {
vector<unordered_set<nid_t>> components = weakly_connected_components(graph);
for (auto& component : components) {
bool ref_anchored = false;
for (auto ni = component.begin(); !ref_anchored && ni != component.end(); ++ni) {
vector<step_handle_t> steps = graph->steps_of_handle(graph->get_handle(*ni));
for (size_t si = 0; !ref_anchored && si < steps.size(); ++si) {
string step_path_name = graph->get_path_name(graph->get_path_handle_of_step(steps[si]));
if (step_path_name.substr(0, ref_prefix.length()) == ref_prefix) {
ref_anchored = true;
}
}
}
if (!ref_anchored) {
++removed_component_count;
for (auto node_id : component) {
handle_t node_handle = graph->get_handle(node_id);
removed_component_base_count += graph->get_length(node_handle);
// destroy here instead of adding to to_destroy, becuase we don't care
// if there are paths or not (so don't require -f)
dynamic_cast<DeletableHandleGraph*>(graph)->destroy_handle(node_handle);
if (to_destroy.count(node_id)) {
to_destroy.erase(node_id);
}
}
}
}
}
}
for (nid_t nid : to_destroy) {
assert(graph->has_node(nid));
handle_t handle = graph->get_handle(nid);
if (graph->steps_of_handle(handle).empty()) {
chopped_bases += graph->get_length(handle);
++chopped_nodes;
dynamic_cast<DeletableHandleGraph*>(graph)->destroy_handle(handle);
#ifdef debug
cerr << "force destroying handle " << graph->get_id(handle) << ":" << graph->get_is_reverse(handle) << endl;
#endif
}
}
if (progress) {
cerr << "[clip-vg]: Clipped "
<< chopped_bases << " bases from "
<< chopped_nodes << " nodes";
if (!force_clip) {
cerr << " in " << chopped_paths << " paths";
}
cerr << endl;
if (removed_subpath_count > 0) {
cerr << "[clip-vg]: " << removed_subpath_count << " orphaned subpaths were removed with total "
<< removed_subpath_base_count << " bases" << endl;
}
if (removed_component_count > 0) {
cerr << "[clip-vg]: " << removed_component_count << " orphaned connected components were removed with total "
<< removed_component_base_count << " bases" << endl;
}
}
}
pair<unordered_set<handle_t>, vector<path_handle_t>> chop_path(MutablePathMutableHandleGraph* graph,
path_handle_t path_handle,
const vector<pair<int64_t, int64_t>>& intervals) {
// get the breakpoints
set<int64_t> breakpoints;
for (const pair<int64_t, int64_t>& interval : intervals) {
breakpoints.insert(interval.first);
breakpoints.insert(interval.second); // we're cutting before offset, so the open coordinate is what we want
}
// to be safe, don't cut and iterate at the same time, so load up steps here
vector<handle_t> steps;
graph->for_each_step_in_path(path_handle, [&](step_handle_t step_handle) {
steps.push_back(graph->get_handle_of_step(step_handle));
});
// cut the nodes to ensure breakpoints at node boundaries
int64_t offset = 0;
for (auto handle : steps) {
int64_t len = graph->get_length(handle);
// find breakpoints in node
vector<size_t> cut_points;
for (auto i = breakpoints.lower_bound(offset); i != breakpoints.end() && *i - offset < len; ++i) {
int64_t cut_point = *i - offset;
// libbdsg is buggy and can't accept cutpoints on ends on reverse strand
if (cut_point > 0 && cut_point < len) {
cut_points.push_back(cut_point);
}
}
// chop the node
if (!cut_points.empty()) {
#ifdef debug
cerr << "dividing node_id=" << graph->get_id(handle) << ":" << graph->get_is_reverse(handle) << " seq=" << graph->get_sequence(handle)
<< " for path " << graph->get_path_name(path_handle) << " at cut points:";
for (auto cp : cut_points) {
cerr << " " << cp;
}
cerr << endl;
#endif
size_t total_pieces_length = 0;
vector<handle_t> pieces = graph->divide_handle(handle, cut_points) ;
for (size_t i = 0; i < pieces.size(); ++i) {
handle_t& piece = pieces[i];
size_t piece_length = graph->get_length(piece);
if (i == 0) {
assert(piece_length == cut_points[0]);
} else if (i < pieces.size() - 1) {
assert(piece_length == cut_points[i] - cut_points[i-1]);
}
total_pieces_length += piece_length;
#ifdef debug
cerr << " piece " << graph->get_id(piece) << ":" << graph->get_is_reverse(piece) << " " << graph->get_sequence(piece)
<< " tlen=" << total_pieces_length << "/" << len << endl;
#endif
}
// bugs in divide-handle turning out to be a real issue. add this sanity check to catch them early.
assert(total_pieces_length == (size_t)len);
}
offset += len;
}
steps.clear();
int64_t original_path_length = offset;
unordered_set<handle_t> chopped_handles;
offset = 0;
step_handle_t current_step = graph->path_begin(path_handle);
#ifdef debug
cerr << "init step to " << graph->get_id(graph->get_handle_of_step(current_step)) << ":" << graph->get_is_reverse(graph->get_handle_of_step(current_step))
<< " seq=" <<graph->get_sequence(graph->get_handle_of_step(current_step)) << endl;
#endif
vector<path_handle_t> subpaths;
// cut out a subpath and make a new path out of it
function<void(int64_t)> cut_to = [&](int64_t end_offset) {
#ifdef debug
cerr << "\ncut_to " << end_offset << " where current offset is " << offset << endl;
#endif
vector<handle_t> steps;
int64_t start_offset = offset;
int64_t path_length = 0;
while (offset < end_offset && current_step != graph->path_end(path_handle)) {
handle_t handle = graph->get_handle_of_step(current_step);
steps.push_back(handle);
offset += graph->get_length(handle);
current_step = graph->get_next_step(current_step);
path_length += graph->get_length(handle);
}
#ifdef debug
cerr << "start offset=" << start_offset << " path length=" << path_length << " end offset=" << end_offset << endl;
#endif
assert(start_offset + path_length == end_offset);
if (path_length > 0) {
path_handle_t subpath_handle = graph->create_path_handle(make_subpath_name(graph->get_path_name(path_handle), start_offset, path_length));
for (auto step : steps) {
#ifdef debug
cerr << " pushing subpath step " << graph->get_id(step) << ":" << graph->get_is_reverse(step)
<< " len=" << graph->get_length(step) << " to " << graph->get_path_name(subpath_handle) << endl;
#endif
graph->append_step(subpath_handle, step);
}
subpaths.push_back(subpath_handle);
}
};
for (size_t i = 0; i < intervals.size(); ++i) {
if (intervals[i].first > offset) {
// cut everythign left of the interval
cut_to(intervals[i].first);
}
// scan past the interval
while (offset < intervals[i].second && current_step != graph->path_end(path_handle)) {
handle_t handle = graph->get_handle_of_step(current_step);
offset += graph->get_length(handle);
current_step = graph->get_next_step(current_step);
#ifdef debug
cerr << "adding to delete set: " << graph->get_id(handle) << endl;
#endif
chopped_handles.insert(handle);
}
}
// cut the last bit
if (offset < original_path_length) {
cut_to(original_path_length);
}
return make_pair(chopped_handles, subpaths);
}
void replace_path_name_substrings(MutablePathMutableHandleGraph* graph, const vector<string>& to_replace,
bool progress) {
// parse the strings
vector<pair<string, string>> replace;
for (const string& repstring : to_replace) {
size_t sep = repstring.find('>');
if (sep == string::npos || sep == 0 || sep == repstring.length() - 1) {
cerr << "[clip-vg]: Unable to find separator '>' in " << repstring << ". Replacement must be"
<< " specified with \"s1>s2\"" << endl;
exit(1);
}
replace.push_back(make_pair(repstring.substr(0, sep), repstring.substr(sep + 1)));
if (replace.back().first == replace.back().second) {
replace.pop_back();
}
}
size_t replacement_count = 0;
size_t path_count = 0;
// take care to not modify path handles while iterating path handles, just in case
vector<string> path_names;
graph->for_each_path_handle([&](path_handle_t path_handle) {
path_names.push_back(graph->get_path_name(path_handle));
});
vector<path_handle_t> paths_to_destroy;
for (string& path_name : path_names) {
path_handle_t path_handle = graph->get_path_handle(path_name);
bool changed = false;
for (auto& rep : replace) {
size_t p = path_name.find(rep.first);
if (p != string::npos) {