Debian Codegraph @

test/util.h

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #include <iostream>
2 #include <vector>
3 #include <string>
4 #include <thread>
5 #include <utility>
6 #include <chrono>
7 #include <functional>
8 #include <assert.h>
9 #include "kstring.h"
10 #include "tbx.h"
11 #include "ctpl_stl.h"
12 #include "iitii.h"
13
14 using namespace std;
15
16 // split s on delim & return strlen(s). s is damaged by side-effect
17 template<typename Out>
18 size_t split(char *s, char delim, Out result, uint64_t maxsplit = ULLONG_MAX) {
19 string delims("\n");
20 delims[0] = delim;
21 char *cursor = s;
22 char *token = strsep(&cursor, delims.c_str());
23 char *last_token = token;
24 uint64_t i = 0;
25 while (token) {
26 *(result++) = last_token = token;
27 if (++i < maxsplit) {
28 token = strsep(&cursor, delims.c_str());
29 } else {
30 if (cursor) {
31 *result = last_token = cursor;
32 }
33 break;
34 }
35 }
36 return last_token ? (last_token + strlen(last_token) - s) : 0;
37 }
38
39 template<typename Out>
40 size_t split(string& s, char delim, Out result, uint64_t maxsplit = ULLONG_MAX) {
41 return split(&s[0], delim, result, maxsplit);
42 }
43
44 // sugar for seeking into a htsFile with tabix & iterating through the relevant lines
45 class TabixIterator {
46 htsFile *fp_;
47 tbx_t *tbx_;
48
49 hts_itr_t *it_;
50 kstring_t str_ = {0,0,0};
51 bool valid_ = false;
52
53 TabixIterator(htsFile *fp, tbx_t *tbx, hts_itr_t *it) {
54 fp_ = fp;
55 tbx_ = tbx;
56 it_ = it;
57 assert(tbx_ && fp_ && it_);
58 }
59
60 public:
61 ~TabixIterator() {
62 tbx_itr_destroy(it_);
63 if (str_.s) {
64 free(str_.s);
65 }
66 }
67
68 static unique_ptr<TabixIterator> Open(htsFile *fp, tbx_t *tbx, int tid, int beg, int end) {
69 if (!tbx) {
70 return nullptr;
71 }
72 hts_itr_t *it = tbx_itr_queryi(tbx, tid, beg, end);
73 if (!it) {
74 return nullptr;
75 }
76 auto ans = unique_ptr<TabixIterator>(new TabixIterator(fp, tbx, it));
77 ans->Next();
78 return ans;
79 }
80
81 bool Valid() const {
82 return valid_ && str_.s;
83 }
84
85 const char* Line() const {
86 if (Valid()) {
87 assert(ks_len((kstring_t*)&str_) == strlen(str_.s));
88 return str_.s;
89 }
90 return nullptr;
91 }
92
93 void Next() {
94 valid_ = (tbx_itr_next(fp_, tbx_, it_, &str_) >= 0);
95 assert(!valid_ || str_.s);
96 }
97 };
98
99 uint32_t milliseconds_to(function<void()> f) {
100 chrono::steady_clock::time_point begin = chrono::steady_clock::now();
101 f();
102 chrono::steady_clock::time_point end = chrono::steady_clock::now();
103 return chrono::duration_cast<chrono::milliseconds>(end - begin).count();
104 }
105
106 // iit Item for testing with VCF variants
107 struct variant {
108 int rid;
109 int beg;
110 int end;
111 string id;
112 string ref;
113 vector<string> alt;
114
115 string str() const {
116 string ans = to_string(beg) + "/" + ref + "/";
117 bool first = true;
118 for (const auto& one_alt : alt) {
119 if (!first) {
120 ans += ",";
121 }
122 ans += one_alt;
123 }
124 if (id.size()) {
125 ans += "/" + id;
126 }
127 return ans;
128 }
129
130 bool operator==(const variant& rhs) const {
131 return rid == rhs.rid && beg == rhs.beg && ref == rhs.ref;
132 }
133 };
134
135 int variant_beg(const variant& v) { return v.beg; }
136 int variant_end(const variant& v) { return v.end; }
137
138 // use tabix to open VCF file & load variants overlapping given region
139 vector<variant> load_variants(const string& filename, int rid, int beg, int end) {
140 auto fp = shared_ptr<htsFile>(hts_open(filename.c_str(), "r"),
141 [] (htsFile* f) { if (f && hts_close(f)) throw runtime_error("hts_close"); });
142 if (!fp) {
143 throw runtime_error("Failed to open " + filename);
144 }
145 auto tbx = shared_ptr<tbx_t>(tbx_index_load(filename.c_str()), [] (tbx_t *t) { if (t) tbx_destroy(t); });
146 if (!tbx) {
147 throw runtime_error("Failed to open .tbi/.csi index of " + filename);
148 }
149 auto itr = TabixIterator::Open(fp.get(), tbx.get(), rid, beg, end);
150 if (!itr) {
151 throw runtime_error("Failed to seek position " + to_string(beg) + " using index of " + filename);
152 }
153
154 vector<char*> tokens;
155 vector<variant> variants;
156 for (; itr->Valid(); itr->Next()) {
157 string linecpy(itr->Line());
158 tokens.clear();
159 split(linecpy, '\t', back_inserter(tokens), 6);
160 if (tokens.size() < 6) {
161 throw runtime_error("invalid VCF line: " + string(itr->Line()));
162 }
163
164 variant vt;
165 vt.beg = atoi(tokens[1]);
166 if (vt.beg >= beg && vt.beg < end) { // exclude danglers
167 vt.rid = rid;
168 vt.id = strcmp(tokens[2], ".") ? string(tokens[2]) : "";
169 vt.ref = string(tokens[3]);
170 vt.end = vt.beg + vt.ref.size();
171 string altcpy(tokens[4]);
172 tokens.clear();
173 split(altcpy, ',', back_inserter(tokens));
174 for (auto alt : tokens) {
175 vt.alt.push_back(string(alt));
176 }
177 variants.push_back(move(vt));
178 }
179 }
180 return variants;
181 }
182
183 // read the first 'megabases' Mbp worth of variants from the file quickly, by parallelizing each
184 // megabase on a thread pool. results are unordered
185 vector<variant> load_variants_parallel(const string& filename, int rid, int megabases) {
186 ctpl::thread_pool pool(thread::hardware_concurrency());
187 mutex mu;
188 vector<future<void>> futures;
189 vector<variant> ans;
190
191 for (int mb = 0; mb < megabases; ++mb) {
192 auto fut = pool.push([&, mb](int tid) {
193 auto variants_i = load_variants(filename, rid, mb*1000000, (mb+1)*1000000);
194 lock_guard<mutex> lock(mu);
195 ans.insert(ans.end(), variants_i.begin(), variants_i.end());
196 });
197 futures.push_back(move(fut));
198 }
199
200 for (auto& fut : futures) {
201 fut.get();
202 }
203
204 return ans;
205 }
206
207 using variant_iit = iit<int, variant, variant_beg, variant_end>;
208 using variant_iitii = iitii<int, variant, variant_beg, variant_end>;