Debian Codegraph @

src/scan.h

raw symbols SCIP
1 #ifndef SCAN_H
2 #define SCAN_H
3
4 #include <limits>
5
6 #include <boost/icl/split_interval_map.hpp>
7 #include <boost/dynamic_bitset.hpp>
8 #include <boost/unordered_map.hpp>
9 #include <boost/date_time/posix_time/posix_time.hpp>
10 #include <boost/date_time/gregorian/gregorian.hpp>
11
12 #include <htslib/sam.h>
13
14 #include "version.h"
15 #include "util.h"
16
17
18 namespace torali
19 {
20
21 struct ScanWindow {
22 bool select;
23 int32_t start;
24 int32_t end;
25 uint32_t cov;
26 uint32_t uniqcov;
27
28 ScanWindow() : select(false), start(0), end(0), cov(0), uniqcov(0) {}
29 explicit ScanWindow(int32_t const s) : select(false), start(s), end(s+1), cov(0), uniqcov(0) {}
30
31 bool operator<(const ScanWindow& sw2) const {
32 return ((start<sw2.start) || ((start == sw2.start) && (end < sw2.end)));
33 }
34 };
35
36 template<typename TConfig>
37 inline int32_t
38 _findScanWindow(TConfig const& c, uint32_t const reflen, std::vector<uint16_t> const& binMap, int32_t const midPoint) {
39 if (c.hasScanFile) {
40 if (binMap[midPoint] == LAST_BIN) return -1;
41 else return binMap[midPoint];
42 } else {
43 uint32_t bin = midPoint / c.scanWindow;
44 uint32_t allbins = reflen / c.scanWindow;
45 if (bin >= allbins) return -1;
46 else return bin;
47 }
48 return -1;
49 }
50
51
52 inline std::pair<uint32_t, uint32_t>
53 estCountBounds(std::vector< std::vector<ScanWindow> > const& scanCounts) {
54 std::vector<uint32_t> all;
55 for(uint32_t refIndex = 0; refIndex < scanCounts.size(); ++refIndex) {
56 for(uint32_t i = 0; i<scanCounts[refIndex].size(); ++i) {
57 if (scanCounts[refIndex][i].select) all.push_back(scanCounts[refIndex][i].cov);
58 }
59 }
60 std::sort(all.begin(), all.end());
61 uint32_t median = all[all.size() / 2];
62 std::vector<uint32_t> absdev;
63 for(uint32_t i = 0; i<all.size(); ++i) absdev.push_back(std::abs((int32_t) all[i] - (int32_t) median));
64 std::sort(absdev.begin(), absdev.end());
65 uint32_t mad = absdev[absdev.size() / 2];
66 uint32_t lowerBound = 0;
67 if (mad < median) lowerBound = median - mad;
68 uint32_t upperBound = median + mad;
69 return std::make_pair(lowerBound, upperBound);
70 }
71
72 template<typename TConfig>
73 inline void
74 scan(TConfig const& c, LibraryInfo const& li, std::vector< std::vector<ScanWindow> >& scanCounts) {
75
76 // Load bam file
77 samFile* samfile = sam_open(c.bamFile.string().c_str(), "r");
78 hts_set_fai_filename(samfile, c.genome.string().c_str());
79 hts_idx_t* idx = sam_index_load(samfile, c.bamFile.string().c_str());
80 bam_hdr_t* hdr = sam_hdr_read(samfile);
81
82 // Pre-defined scanning windows
83 if (c.hasScanFile) {
84 typedef boost::icl::interval_set<uint32_t> TChrIntervals;
85 typedef std::vector<TChrIntervals> TRegionsGenome;
86 TRegionsGenome scanRegions;
87 if (!_parseBedIntervals(c.scanFile.string(), c.hasScanFile, hdr, scanRegions)) {
88 std::cerr << "Warning: Couldn't parse BED intervals. Do the chromosome names match?" << std::endl;
89 }
90 for (int32_t refIndex = 0; refIndex < hdr->n_targets; ++refIndex) {
91 for(typename TChrIntervals::iterator it = scanRegions[refIndex].begin(); it != scanRegions[refIndex].end(); ++it) {
92 if (it->lower() < it->upper()) {
93 if (it->upper() < hdr->target_len[refIndex]) {
94 ScanWindow sw;
95 sw.start = it->lower();
96 sw.end = it->upper();
97 sw.select = true;
98 scanCounts[refIndex].push_back(sw);
99 }
100 }
101 }
102 // Sort scan windows
103 sort(scanCounts[refIndex].begin(), scanCounts[refIndex].end());
104 }
105 }
106
107 // Parse BAM file
108 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
109 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Scanning Windows" << std::endl;
110
111 // Iterate chromosomes
112 uint64_t totalCov = 0;
113 faidx_t* faiMap = fai_load(c.mapFile.string().c_str());
114 for(int32_t refIndex=0; refIndex < (int32_t) hdr->n_targets; ++refIndex) {
115 if (chrNoData(c, refIndex, idx)) continue;
116 // Exclude small chromosomes
117 if ((hdr->target_len[refIndex] < c.minChrLen) && (totalCov > 1000000)) continue;
118 // Exclude sex chromosomes
119 if ((std::string(hdr->target_name[refIndex]) == "chrX") || (std::string(hdr->target_name[refIndex]) == "chrY") || (std::string(hdr->target_name[refIndex]) == "X") || (std::string(hdr->target_name[refIndex]) == "Y")) continue;
120
121 // Check presence in mappability map
122 std::string tname(hdr->target_name[refIndex]);
123 int32_t seqlen = faidx_seq_len(faiMap, tname.c_str());
124 if (seqlen == -1) continue;
125 else seqlen = -1;
126 char* seq = faidx_fetch_seq(faiMap, tname.c_str(), 0, faidx_seq_len(faiMap, tname.c_str()), &seqlen);
127
128 // Get Mappability
129 std::vector<uint16_t> uniqContent(hdr->target_len[refIndex], 0);
130 {
131 // Mappability map
132 typedef boost::dynamic_bitset<> TBitSet;
133 TBitSet uniq(hdr->target_len[refIndex], false);
134 for(uint32_t i = 0; i < hdr->target_len[refIndex]; ++i) {
135 if (seq[i] == 'C') uniq[i] = 1;
136 }
137
138 // Sum across fragments
139 int32_t halfwin = (int32_t) (c.meanisize / 2);
140 int32_t usum = 0;
141 for(int32_t pos = halfwin; pos < (int32_t) hdr->target_len[refIndex] - halfwin; ++pos) {
142 if (pos == halfwin) {
143 for(int32_t i = pos - halfwin; i<=pos+halfwin; ++i) usum += uniq[i];
144 } else {
145 usum -= uniq[pos - halfwin - 1];
146 usum += uniq[pos + halfwin];
147 }
148 uniqContent[pos] = usum;
149 }
150 }
151
152 // Bins on this chromosome
153 std::vector<uint16_t> binMap;
154 if (!c.hasScanFile) {
155 uint32_t allbins = hdr->target_len[refIndex] / c.scanWindow;
156 scanCounts[refIndex].resize(allbins, ScanWindow());
157 for(uint32_t i = 0; i < allbins; ++i) {
158 scanCounts[refIndex][i].start = i * c.scanWindow;
159 scanCounts[refIndex][i].end = (i+1) * c.scanWindow;
160 }
161 } else {
162 // Fill bin map
163 binMap.resize(hdr->target_len[refIndex], LAST_BIN);
164 if (scanCounts[refIndex].size() >= LAST_BIN) {
165 std::cerr << "Warning: Too many scan windows on " << hdr->target_name[refIndex] << std::endl;
166 }
167 for(uint32_t bin = 0;((bin < scanCounts[refIndex].size()) && (bin < LAST_BIN)); ++bin) {
168 for(int32_t k = scanCounts[refIndex][bin].start; k < scanCounts[refIndex][bin].end; ++k) binMap[k] = bin;
169 }
170 }
171
172 // Mate map
173 typedef boost::unordered_map<std::size_t, bool> TMateMap;
174 TMateMap mateMap;
175
176 // Count reads
177 hts_itr_t* iter = sam_itr_queryi(idx, refIndex, 0, hdr->target_len[refIndex]);
178 bam1_t* rec = bam_init1();
179 int32_t lastAlignedPos = 0;
180 std::set<std::size_t> lastAlignedPosReads;
181 while (sam_itr_next(samfile, iter, rec) >= 0) {
182 if (rec->core.flag & (BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP | BAM_FSUPPLEMENTARY | BAM_FUNMAP)) continue;
183 if ((rec->core.flag & BAM_FPAIRED) && ((rec->core.flag & BAM_FMUNMAP) || (rec->core.tid != rec->core.mtid))) continue;
184 if (rec->core.qual < c.minQual) continue;
185 if (getSVType(rec) != 2) continue;
186
187 int32_t midPoint = rec->core.pos + halfAlignmentLength(rec);
188 if (rec->core.flag & BAM_FPAIRED) {
189 // Clean-up the read store for identical alignment positions
190 if (rec->core.pos > lastAlignedPos) {
191 lastAlignedPosReads.clear();
192 lastAlignedPos = rec->core.pos;
193 }
194
195 if ((rec->core.pos < rec->core.mpos) || ((rec->core.pos == rec->core.mpos) && (lastAlignedPosReads.find(hash_string(bam_get_qname(rec))) == lastAlignedPosReads.end()))) {
196 // First read
197 lastAlignedPosReads.insert(hash_string(bam_get_qname(rec)));
198 std::size_t hv = hash_pair(rec);
199 mateMap[hv] = true;
200 continue;
201 } else {
202 // Second read
203 std::size_t hv = hash_pair_mate(rec);
204 if ((mateMap.find(hv) == mateMap.end()) || (!mateMap[hv])) continue; // Mate discarded
205 mateMap[hv] = false;
206 }
207
208 // Insert size filter
209 int32_t isize = (rec->core.pos + alignmentLength(rec)) - rec->core.mpos;
210 if ((li.minNormalISize < isize) && (isize < li.maxNormalISize)) midPoint = rec->core.mpos + (int32_t) (isize/2);
211 else continue;
212 }
213
214 // Count fragment
215 if ((midPoint >= 0) && (midPoint < (int32_t) hdr->target_len[refIndex])) {
216 int32_t bin = _findScanWindow(c, hdr->target_len[refIndex], binMap, midPoint);
217 if (bin >= 0) {
218 ++scanCounts[refIndex][bin].cov;
219
220 if (uniqContent[midPoint] >= c.fragmentUnique * c.meanisize) ++scanCounts[refIndex][bin].uniqcov;
221 ++totalCov;
222 }
223 }
224 }
225 // Clean-up
226 bam_destroy1(rec);
227 hts_itr_destroy(iter);
228 if (seq != NULL) free(seq);
229 }
230
231 // clean-up
232 fai_destroy(faiMap);
233 bam_hdr_destroy(hdr);
234 hts_idx_destroy(idx);
235 sam_close(samfile);
236 }
237
238
239 template<typename TConfig>
240 inline void
241 selectWindows(TConfig const& c, std::vector< std::vector<ScanWindow> >& scanCounts) {
242 if (c.noScanWindowSelection) {
243 // Select all windows
244 for(uint32_t refIndex = 0; refIndex < scanCounts.size(); ++refIndex) {
245 for(uint32_t i = 0; i<scanCounts[refIndex].size(); ++i) {
246 scanCounts[refIndex][i].select = true;
247 }
248 }
249 } else {
250 // Pre-screen using PE layout, uniqueness and percent identity
251 for(uint32_t refIndex = 0; refIndex < scanCounts.size(); ++refIndex) {
252 for(uint32_t i = 0; i<scanCounts[refIndex].size(); ++i) {
253 // Uniqueness
254 double uniqratio = 0;
255 if (scanCounts[refIndex][i].cov > 0) uniqratio = (double) scanCounts[refIndex][i].uniqcov / scanCounts[refIndex][i].cov;
256 if (uniqratio > c.uniqueToTotalCovRatio) scanCounts[refIndex][i].select = true;
257 else scanCounts[refIndex][i].select = false;
258 }
259 }
260
261 // Normalize user-defined scan windows to same length (10,000bp)
262 if (c.hasScanFile) {
263 for(uint32_t refIndex = 0; refIndex < scanCounts.size(); ++refIndex) {
264 for(uint32_t i = 0; i<scanCounts[refIndex].size(); ++i) {
265 double scale = (double) 10000 / (double) (scanCounts[refIndex][i].end - scanCounts[refIndex][i].start);
266 scanCounts[refIndex][i].uniqcov *= scale;
267 scanCounts[refIndex][i].cov *= scale;
268 }
269 }
270 }
271
272 // Get "normal" coverage windows of CN2
273 typedef std::pair<uint32_t, uint32_t> TCountBounds;
274 TCountBounds cb = estCountBounds(scanCounts);
275
276 // Select CN2 windows
277 for(uint32_t refIndex = 0; refIndex < scanCounts.size(); ++refIndex) {
278 for(uint32_t i = 0; i<scanCounts[refIndex].size(); ++i) {
279 if (scanCounts[refIndex][i].select) {
280 if ((scanCounts[refIndex][i].cov > cb.first) && (scanCounts[refIndex][i].cov < cb.second)) scanCounts[refIndex][i].select = true;
281 else scanCounts[refIndex][i].select = false;
282 }
283 }
284 }
285 }
286 }
287
288 }
289
290 #endif