Debian Codegraph @

src/shortpe.h

raw symbols SCIP
1 #ifndef SHORTPE_H
2 #define SHORTPE_H
3
4
5 #include <iostream>
6 #include <fstream>
7
8 #include <boost/graph/adjacency_list.hpp>
9 #include <boost/graph/graphviz.hpp>
10 #include <boost/graph/connected_components.hpp>
11 #include <boost/container/flat_set.hpp>
12 #include <boost/unordered_map.hpp>
13 #include <boost/program_options/cmdline.hpp>
14 #include <boost/program_options/options_description.hpp>
15 #include <boost/program_options/parsers.hpp>
16 #include <boost/program_options/variables_map.hpp>
17 #include <boost/date_time/posix_time/posix_time.hpp>
18 #include <boost/date_time/gregorian/gregorian.hpp>
19 #include <boost/math/special_functions/pow.hpp>
20 #include <boost/icl/split_interval_map.hpp>
21 #include <boost/tokenizer.hpp>
22 #include <boost/functional/hash.hpp>
23 #include <boost/filesystem.hpp>
24
25 #include <htslib/faidx.h>
26 #include <htslib/vcf.h>
27 #include <htslib/sam.h>
28
29 #include "version.h"
30 #include "util.h"
31 #include "bolog.h"
32 #include "tags.h"
33 #include "coverage.h"
34 #include "msa.h"
35 #include "split.h"
36 #include "junction.h"
37 #include "cluster.h"
38
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
42 #include <zlib.h>
43 #include <stdio.h>
44
45 namespace torali
46 {
47
48 template<typename TConfig, typename TValidRegion, typename TSRStore, typename TStructuralVariantRecord>
49 inline void
50 assembleSplitReads(TConfig const& c, TValidRegion const& validRegions, TSRStore const& srStore, std::vector<TStructuralVariantRecord>& svs)
51 {
52 typedef typename TValidRegion::value_type TChrIntervals;
53 typedef typename TSRStore::value_type TPosReadSV;
54
55 // Open file handles
56 typedef std::vector<samFile*> TSamFile;
57 typedef std::vector<hts_idx_t*> TIndex;
58 TSamFile samfile(c.files.size());
59 TIndex idx(c.files.size());
60 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
61 samfile[file_c] = sam_open(c.files[file_c].string().c_str(), "r");
62 hts_set_fai_filename(samfile[file_c], c.genome.string().c_str());
63 idx[file_c] = sam_index_load(samfile[file_c], c.files[file_c].string().c_str());
64 }
65 bam_hdr_t* hdr = sam_hdr_read(samfile[0]);
66
67 // Reads per SV
68 typedef std::unordered_set<std::string> TSequences;
69 typedef std::vector<TSequences> TSVSequences;
70 TSVSequences traStore(svs.size(), TSequences());
71 typedef std::vector<uint8_t> TQualities;
72 typedef std::vector<TQualities> TQualVectors;
73 TQualVectors traQualStore(svs.size(), TQualities());
74
75 // Parse BAM
76 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
77 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Split-read assembly" << std::endl;
78
79 faidx_t* fai = fai_load(c.genome.string().c_str());
80 ThreadPool pool(c.maxThreads);
81 for(int32_t refIndex = 0; refIndex < hdr->n_targets; ++refIndex) {
82 if (validRegions[refIndex].empty()) continue;
83 if (srStore[refIndex].empty()) continue;
84
85 // Load sequence
86 int32_t seqlen = -1;
87 std::string tname(hdr->target_name[refIndex]);
88 char* seq = faidx_fetch_seq(fai, tname.c_str(), 0, hdr->target_len[refIndex], &seqlen);
89
90 // Collect all split-read pos
91 typedef boost::dynamic_bitset<> TBitSet;
92 TBitSet hits(hdr->target_len[refIndex]);
93 for(typename TPosReadSV::const_iterator it = srStore[refIndex].begin(); it != srStore[refIndex].end(); ++it) hits[it->first.first] = 1;
94
95 // Sequences
96 TSVSequences seqStore(svs.size(), TSequences());
97 TQualVectors qualStore(svs.size(), TQualities());
98
99 // Collect reads from all samples
100 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
101 // Read alignments
102 for(typename TChrIntervals::const_iterator vRIt = validRegions[refIndex].begin(); vRIt != validRegions[refIndex].end(); ++vRIt) {
103 hts_itr_t* iter = sam_itr_queryi(idx[file_c], refIndex, vRIt->lower(), vRIt->upper());
104 bam1_t* rec = bam_init1();
105 while (sam_itr_next(samfile[file_c], iter, rec) >= 0) {
106 if (rec->core.flag & (BAM_FQCFAIL | BAM_FDUP | BAM_FUNMAP | BAM_FSECONDARY | BAM_FSUPPLEMENTARY)) continue;
107 if ((rec->core.qual < c.minMapQual) || (rec->core.tid<0)) continue;
108 if (!hits[rec->core.pos]) continue;
109
110 // Valid split-read
111 std::size_t seed = hash_sr(rec);
112 typename TPosReadSV::const_iterator it = srStore[refIndex].find(std::make_pair(rec->core.pos, seed));
113 if (it != srStore[refIndex].end()) {
114 int32_t svid = it->second;
115
116 // Get the sequence
117 if (svid == (int32_t) svs[svid].id) { // Should be always true
118 std::string sequence;
119 sequence.resize(rec->core.l_qseq);
120 const uint8_t* seqptr = bam_get_seq(rec);
121 for (int i = 0; i < rec->core.l_qseq; ++i) sequence[i] = "=ACMGRSVTWYHKDBN"[bam_seqi(seqptr, i)];
122
123 // Adjust orientation
124 bool bpPoint = false;
125 if (_translocation(svs[svid].svt)) {
126 if (rec->core.tid == svs[svid].chr2) bpPoint = true;
127 } else {
128 // Only relevant for inversions
129 if (svs[svid].svt == 0) {
130 if (rec->core.pos + 25 > svs[svid].svStart) bpPoint = true;
131 else bpPoint = false;
132 } else if (svs[svid].svt == 1) {
133 if (rec->core.pos + 25 > svs[svid].svEnd) bpPoint = true;
134 else bpPoint = false;
135 }
136 }
137 _adjustOrientation(sequence, bpPoint, svs[svid].svt);
138
139 // At most n split-reads
140 if (seqStore[svid].size() < c.maxReadPerSV) {
141 bool insertSuccess = false;
142 if (_translocation(svs[svid].svt)) {
143 insertSuccess = traStore[svid].insert(std::move(sequence)).second;
144 if (insertSuccess) traQualStore[svid].push_back(rec->core.qual);
145 } else {
146 insertSuccess = seqStore[svid].insert(std::move(sequence)).second;
147 if (insertSuccess) qualStore[svid].push_back(rec->core.qual);
148 }
149 }
150 }
151 }
152 }
153 bam_destroy1(rec);
154 hts_itr_destroy(iter);
155 }
156 }
157
158 // Process all SVs on this chromosome
159 std::vector<uint32_t> svidsToProcess;
160 for(uint32_t svid = 0; svid < seqStore.size(); ++svid) {
161 if (_translocation(svs[svid].svt)) continue;
162 if (svs[svid].chr != refIndex) continue;
163
164 // MSA
165 if (seqStore[svid].size() <= 1) {
166 svs[svid].consensus = "";
167 svs[svid].srSupport = 0;
168 svs[svid].srAlignQuality = 0;
169 continue;
170 }
171 svidsToProcess.push_back(svid);
172 }
173
174 // Process in batches
175 std::atomic<uint32_t> next(0);
176 std::vector<std::future<void>> futures;
177 futures.reserve(c.maxThreads);
178 for(uint32_t t = 0; t < c.maxThreads; ++t) {
179 futures.push_back(pool.enqueue([&]() {
180 for(;;) {
181 uint32_t idx = next.fetch_add(1, std::memory_order_relaxed);
182 if (idx >= svidsToProcess.size()) break;
183 uint32_t svid = svidsToProcess[idx];
184
185 msa(c, seqStore[svid], svs[svid].consensus);
186 if (!alignConsensus(c, hdr, seq, NULL, svs[svid])) {
187 svs[svid].consensus = "";
188 svs[svid].srSupport = 0;
189 svs[svid].srAlignQuality = 0;
190 } else {
191 auto& qv = qualStore[svid];
192 svs[svid].mapq = 0;
193 for(uint8_t q : qv) svs[svid].mapq += q;
194 if (!qv.empty()) svs[svid].srMapQuality = medianVector(qv);
195 else svs[svid].srMapQuality = 0;
196 svs[svid].srSupport = seqStore[svid].size();
197 }
198 }
199 }));
200 }
201 for(auto &f : futures) f.get();
202
203 // Clean-up
204 if (seq != NULL) free(seq);
205 }
206
207 // Process translocations
208 for(int32_t refIndex2 = 0; refIndex2 < hdr->n_targets; ++refIndex2) {
209 if (validRegions[refIndex2].empty()) continue;
210 char* sndSeq = NULL;
211 for(int32_t refIndex = refIndex2 + 1; refIndex < hdr->n_targets; ++refIndex) {
212 if (validRegions[refIndex].empty()) continue;
213 char* seq = NULL;
214
215 // Iterate SVs
216 std::vector<uint32_t> traToProcess;
217 for(uint32_t svid = 0; svid < traStore.size(); ++svid) {
218 if (!_translocation(svs[svid].svt)) continue;
219 if ((svs[svid].chr != refIndex) || (svs[svid].chr2 != refIndex2)) continue;
220
221 if (traStore[svid].size() <= 1) {
222 svs[svid].consensus = "";
223 svs[svid].srSupport = 0;
224 svs[svid].srAlignQuality = 0;
225 continue;
226 }
227 traToProcess.push_back(svid);
228 }
229
230 if (!traToProcess.empty()) {
231 // Lazy loading of references
232 if (seq == NULL) {
233 int32_t seqlen = -1;
234 std::string tname(hdr->target_name[refIndex]);
235 seq = faidx_fetch_seq(fai, tname.c_str(), 0, hdr->target_len[refIndex], &seqlen);
236 }
237 if (sndSeq == NULL) {
238 int32_t seqlen = -1;
239 std::string tname(hdr->target_name[refIndex2]);
240 sndSeq = faidx_fetch_seq(fai, tname.c_str(), 0, hdr->target_len[refIndex2], &seqlen);
241 }
242
243 std::atomic<uint32_t> nextTra(0);
244 std::vector<std::future<void>> futures;
245 futures.reserve(c.maxThreads);
246 for(uint32_t t = 0; t < c.maxThreads; ++t) {
247 futures.push_back(pool.enqueue([&, seq, sndSeq]() {
248 for(;;) {
249 uint32_t idx = nextTra.fetch_add(1, std::memory_order_relaxed);
250 if (idx >= traToProcess.size()) break;
251 uint32_t svid = traToProcess[idx];
252 msa(c, traStore[svid], svs[svid].consensus);
253 if (!alignConsensus(c, hdr, seq, sndSeq, svs[svid])) {
254 svs[svid].consensus = "";
255 svs[svid].srSupport = 0;
256 svs[svid].srAlignQuality = 0;
257 } else {
258 auto& qv = traQualStore[svid];
259 svs[svid].mapq = 0;
260 for(uint8_t q : qv) svs[svid].mapq += q;
261 if (!qv.empty()) svs[svid].srMapQuality = medianVector(qv);
262 else svs[svid].srMapQuality = 0;
263 svs[svid].srSupport = traStore[svid].size();
264 }
265 }
266 }));
267 }
268 for(auto &f : futures) f.get();
269 }
270 if (seq != NULL) free(seq);
271 }
272 if (sndSeq != NULL) free(sndSeq);
273 }
274
275 // Clean-up
276 fai_destroy(fai);
277 bam_hdr_destroy(hdr);
278 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
279 hts_idx_destroy(idx[file_c]);
280 sam_close(samfile[file_c]);
281 }
282 }
283
284
285 template<typename TConfig, typename TValidRegion, typename TSRStore, typename TSampleLib>
286 inline void
287 scanPEandSR(TConfig const& c, TValidRegion const& validRegions, std::vector<StructuralVariantRecord>& svs, std::vector<StructuralVariantRecord>& srSVs, TSRStore& srStore, TSampleLib& sampleLib)
288 {
289 typedef typename TValidRegion::value_type TChrIntervals;
290
291 // Open file handles
292 typedef std::vector<samFile*> TSamFile;
293 typedef std::vector<hts_idx_t*> TIndex;
294 TSamFile samfile(c.files.size());
295 TIndex idx(c.files.size());
296 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
297 samfile[file_c] = sam_open(c.files[file_c].string().c_str(), "r");
298 hts_set_fai_filename(samfile[file_c], c.genome.string().c_str());
299 idx[file_c] = sam_index_load(samfile[file_c], c.files[file_c].string().c_str());
300 }
301 bam_hdr_t* hdr = sam_hdr_read(samfile[0]);
302
303 // Split-read and BAM alignment records
304 typedef std::vector<SRBamRecord> TSRBamRecord;
305 typedef std::vector<TSRBamRecord> TSvtSRBamRecord;
306 typedef std::vector<BamAlignRecord> TBamRecord;
307 typedef std::vector<TBamRecord> TSvtBamRecord;
308
309 // Parse genome, process chromosome by chromosome
310 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
311 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Paired-end and split-read scanning" << std::endl;
312
313 // Iterate all samples
314 ThreadPool pool(c.maxThreads);
315 std::vector<TSvtSRBamRecord> perFileSrBR(c.files.size(), TSvtSRBamRecord(2 * DELLY_SVT_TRANS));
316 std::vector<TSvtBamRecord> perFileBamRecord(c.files.size(), TSvtBamRecord(2 * DELLY_SVT_TRANS));
317 std::vector<std::future<void>> futures;
318 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
319 futures.push_back(pool.enqueue([&, file_c]() {
320 // Inter-chromosomal mate map and alignment length
321 typedef std::pair<uint8_t, int32_t> TQualLen;
322 typedef boost::unordered_map<std::size_t, TQualLen> TMateMap;
323 TMateMap matetra;
324
325 // Split-read junctions
326 typedef std::vector<Junction> TJunctionVector;
327 typedef boost::unordered_map<std::size_t, TJunctionVector> TReadBp;
328 TReadBp readBp;
329
330 // Iterate all chromosomes for that sample
331 for(int32_t refIndex=0; refIndex < (int32_t) hdr->n_targets; ++refIndex) {
332
333 // Any data?
334 if (validRegions[refIndex].empty()) continue;
335 bool nodata = true;
336 std::string suffix("cram");
337 std::string str(c.files[file_c].string());
338 if ((str.size() >= suffix.size()) && (str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0)) nodata = false;
339 uint64_t mapped = 0;
340 uint64_t unmapped = 0;
341 hts_idx_get_stat(idx[file_c], refIndex, &mapped, &unmapped);
342 if (mapped) nodata = false;
343 if (nodata) continue;
344
345 // Intra-chromosomal mate map and alignment length
346 TMateMap mateMap;
347
348 // Read alignments
349 for(typename TChrIntervals::const_iterator vRIt = validRegions[refIndex].begin(); vRIt != validRegions[refIndex].end(); ++vRIt) {
350 hts_itr_t* iter = sam_itr_queryi(idx[file_c], refIndex, vRIt->lower(), vRIt->upper());
351 bam1_t* rec = bam_init1();
352 int32_t lastAlignedPos = 0;
353 std::unordered_set<std::size_t> lastAlignedPosReads;
354 while (sam_itr_next(samfile[file_c], iter, rec) >= 0) {
355 if (rec->core.flag & (BAM_FQCFAIL | BAM_FDUP | BAM_FUNMAP)) continue;
356 if ((rec->core.qual < c.minMapQual) || (rec->core.tid<0)) continue;
357
358 std::size_t seed = hash_sr(rec);
359 // SV detection using single-end read
360 uint32_t rp = rec->core.pos; // reference pointer
361 uint32_t sp = 0; // sequence pointer
362
363 // Parse the CIGAR
364 const uint32_t* cigar = bam_get_cigar(rec);
365 for (std::size_t i = 0; i < rec->core.n_cigar; ++i) {
366 if ((bam_cigar_op(cigar[i]) == BAM_CMATCH) || (bam_cigar_op(cigar[i]) == BAM_CEQUAL) || (bam_cigar_op(cigar[i]) == BAM_CDIFF)) {
367 sp += bam_cigar_oplen(cigar[i]);
368 rp += bam_cigar_oplen(cigar[i]);
369 } else if (bam_cigar_op(cigar[i]) == BAM_CDEL) {
370 if (bam_cigar_oplen(cigar[i]) > c.minRefSep) _insertJunction(readBp, seed, rec, rp, sp, false);
371 rp += bam_cigar_oplen(cigar[i]);
372 if (bam_cigar_oplen(cigar[i]) > c.minRefSep) _insertJunction(readBp, seed, rec, rp, sp, true);
373 } else if (bam_cigar_op(cigar[i]) == BAM_CINS) {
374 if (bam_cigar_oplen(cigar[i]) > c.minRefSep) _insertJunction(readBp, seed, rec, rp, sp, false);
375 sp += bam_cigar_oplen(cigar[i]);
376 if (bam_cigar_oplen(cigar[i]) > c.minRefSep) _insertJunction(readBp, seed, rec, rp, sp, true);
377 } else if ((bam_cigar_op(cigar[i]) == BAM_CSOFT_CLIP) || (bam_cigar_op(cigar[i]) == BAM_CHARD_CLIP)) {
378 int32_t finalsp = sp;
379 bool scleft = false;
380 if (sp == 0) {
381 finalsp += bam_cigar_oplen(cigar[i]); // Leading soft-clip / hard-clip
382 scleft = true;
383 }
384 sp += bam_cigar_oplen(cigar[i]);
385 if (bam_cigar_oplen(cigar[i]) > c.minClip) _insertJunction(readBp, seed, rec, rp, finalsp, scleft);
386 } else if (bam_cigar_op(cigar[i]) == BAM_CREF_SKIP) {
387 rp += bam_cigar_oplen(cigar[i]);
388 }
389 }
390
391 // Paired-end clustering
392 if (rec->core.flag & BAM_FPAIRED) {
393 // Single-end library
394 if (sampleLib[file_c].median == 0) continue; // Single-end library
395
396 // Secondary/supplementary alignments, mate unmapped or blacklisted chr
397 if (rec->core.flag & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY)) continue;
398 if ((rec->core.mtid<0) || (rec->core.flag & BAM_FMUNMAP)) continue;
399 if (validRegions[rec->core.mtid].empty()) continue;
400 if ((_translocation(rec)) && (rec->core.qual < c.minTraQual)) continue;
401
402 // SV type
403 int32_t svt = _isizeMappingPos(rec, sampleLib[file_c].maxISizeCutoff);
404 if (svt == -1) continue;
405 if ((!c.svtset.empty()) && (c.svtset.find(svt) == c.svtset.end())) continue;
406
407 // Check library-specific insert size for deletions
408 if ((svt == 2) && (sampleLib[file_c].maxISizeCutoff > std::abs(rec->core.isize))) continue;
409
410 // Clean-up the read store for identical alignment positions
411 if (rec->core.pos > lastAlignedPos) {
412 lastAlignedPosReads.clear();
413 lastAlignedPos = rec->core.pos;
414 }
415
416 // Get or store the mapping quality for the partner
417 if (_firstPairObs(rec, lastAlignedPosReads)) {
418 // First read
419 lastAlignedPosReads.insert(seed);
420 std::size_t hv = hash_pair(rec);
421 if (_translocation(svt)) matetra[hv]= std::make_pair((uint8_t) rec->core.qual, alignmentLength(rec));
422 else mateMap[hv]= std::make_pair((uint8_t) rec->core.qual, alignmentLength(rec));
423 } else {
424 // Second read
425 std::size_t hv = hash_pair_mate(rec);
426 int32_t alenmate = 0;
427 uint8_t pairQuality = 0;
428 if (_translocation(svt)) {
429 // Inter-chromosomal
430 auto itMM = matetra.find(hv);
431 if ((itMM == matetra.end()) || (!(itMM->second.first))) continue; // Mate discarded
432 pairQuality = std::min((uint8_t) itMM->second.first, (uint8_t) rec->core.qual);
433 alenmate = itMM->second.second;
434 matetra.erase(itMM);
435 } else {
436 // Intra-chromosomal
437 auto itMM = mateMap.find(hv);
438 if ((itMM == mateMap.end()) || (!(itMM->second.first))) continue; // Mate discarded
439 pairQuality = std::min((uint8_t) itMM->second.first, (uint8_t) rec->core.qual);
440 alenmate = itMM->second.second;
441 mateMap.erase(itMM);
442 }
443 perFileBamRecord[file_c][svt].push_back(BamAlignRecord(rec, pairQuality, alignmentLength(rec), alenmate, sampleLib[file_c].median, sampleLib[file_c].mad, sampleLib[file_c].maxNormalISize));
444 ++sampleLib[file_c].abnormal_pairs;
445 }
446 }
447 }
448 bam_destroy1(rec);
449 hts_itr_destroy(iter);
450 }
451 }
452
453 // Process all junctions for this BAM file
454 for(typename TReadBp::iterator it = readBp.begin(); it != readBp.end(); ++it) std::sort(it->second.begin(), it->second.end());
455
456 // Collect split-read SVs
457 if ((c.svtset.empty()) || (c.svtset.find(2) != c.svtset.end())) selectDeletions(c, readBp, perFileSrBR[file_c]);
458 if ((c.svtset.empty()) || (c.svtset.find(3) != c.svtset.end())) selectDuplications(c, readBp, perFileSrBR[file_c]);
459 if ((c.svtset.empty()) || (c.svtset.find(0) != c.svtset.end()) || (c.svtset.find(1) != c.svtset.end())) selectInversions(c, readBp, perFileSrBR[file_c]);
460 if ((c.svtset.empty()) || (c.svtset.find(4) != c.svtset.end())) selectInsertions(c, readBp, perFileSrBR[file_c]);
461 if ((c.svtset.empty()) || (c.svtset.find(DELLY_SVT_TRANS) != c.svtset.end()) || (c.svtset.find(DELLY_SVT_TRANS + 1) != c.svtset.end()) || (c.svtset.find(DELLY_SVT_TRANS + 2) != c.svtset.end()) || (c.svtset.find(DELLY_SVT_TRANS + 3) != c.svtset.end())) selectTranslocations(c, readBp, perFileSrBR[file_c]);
462 }));
463 }
464 // Wait and merge
465 for(auto &f : futures) f.get();
466 TSvtSRBamRecord srBR(2 * DELLY_SVT_TRANS, TSRBamRecord());
467 TSvtBamRecord bamRecord(2 * DELLY_SVT_TRANS, TBamRecord());
468 for(uint32_t file_c = 0; file_c < c.files.size(); ++file_c) {
469 for(uint32_t svt = 0; svt < perFileBamRecord[file_c].size(); ++svt) {
470 if (!perFileBamRecord[file_c][svt].empty()) {
471 bamRecord[svt].insert(bamRecord[svt].end(), std::make_move_iterator(perFileBamRecord[file_c][svt].begin()), std::make_move_iterator(perFileBamRecord[file_c][svt].end()));
472 }
473 if (!perFileSrBR[file_c][svt].empty()) {
474 srBR[svt].insert(srBR[svt].end(), std::make_move_iterator(perFileSrBR[file_c][svt].begin()), std::make_move_iterator(perFileSrBR[file_c][svt].end()));
475 }
476 }
477 }
478
479 // Debug abnormal paired-ends and split-reads
480 //outputSRBamRecords(c, srBR, false);
481
482 // Cluster split-read records
483 now = boost::posix_time::second_clock::local_time();
484 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Split-read clustering" << std::endl;
485 for(uint32_t svt = 0; svt < srBR.size(); ++svt) {
486 if ((!c.svtset.empty()) && (c.svtset.find(svt) == c.svtset.end())) continue;
487 if (srBR[svt].empty()) continue;
488
489 // Sort
490 std::sort(srBR[svt].begin(), srBR[svt].end());
491
492 // Cluster
493 cluster(c, srBR[svt], srSVs, svt);
494 }
495
496 // Cluster paired-end records
497 now = boost::posix_time::second_clock::local_time();
498 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Paired-end clustering" << std::endl;
499
500 // Maximum variability in insert size
501 int32_t varisize = getVariability(c, sampleLib);
502 for(int32_t svt = 0; svt < (int32_t) bamRecord.size(); ++svt) {
503 if ((!c.svtset.empty()) && (c.svtset.find(svt) == c.svtset.end())) continue;
504 if (bamRecord[svt].empty()) continue;
505
506 // Sort BAM records according to position
507 std::sort(bamRecord[svt].begin(), bamRecord[svt].end());
508
509 // Cluster
510 cluster(c, bamRecord[svt], svs, varisize, svt);
511 }
512
513 // Track split-reads
514 for(uint32_t svt = 0; svt < srBR.size(); ++svt) {
515 for(uint32_t i = 0; i < srBR[svt].size(); ++i) {
516 // Read assigned?
517 if ((srBR[svt][i].svid != -1) && (srBR[svt][i].rstart != -1)) {
518 if (srBR[svt][i].rstart < (int32_t) hdr->target_len[srBR[svt][i].chr]) srStore[srBR[svt][i].chr].insert(std::make_pair(std::make_pair(srBR[svt][i].rstart, srBR[svt][i].id), srBR[svt][i].svid));
519 if (srBR[svt][i].chr != srBR[svt][i].chr2) {
520 // Unclear which chr was primary alignment so insert both if and only if rstart < reference length
521 if (srBR[svt][i].rstart < (int32_t) hdr->target_len[srBR[svt][i].chr2]) srStore[srBR[svt][i].chr2].insert(std::make_pair(std::make_pair(srBR[svt][i].rstart, srBR[svt][i].id), srBR[svt][i].svid));
522 }
523 }
524 }
525 }
526
527 // Clean-up
528 bam_hdr_destroy(hdr);
529 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
530 hts_idx_destroy(idx[file_c]);
531 sam_close(samfile[file_c]);
532 }
533 }
534
535
536 inline void
537 mergeSort(std::vector<StructuralVariantRecord>& pe, std::vector<StructuralVariantRecord>& sr) {
538 typedef std::vector<StructuralVariantRecord> TVariants;
539 // Sort PE records for look-up
540 sort(pe.begin(), pe.end());
541
542 // Sort SR records for look-up
543 sort(sr.begin(), sr.end());
544
545 // Augment PE SVs and append missing SR SVs
546 for(int32_t svt = 0; svt < 10; ++svt) {
547 for(int32_t i = 0; i < (int32_t) sr.size(); ++i) {
548 if (sr[i].svt != svt) continue;
549 if ((sr[i].srSupport == 0) || (sr[i].srAlignQuality == 0)) continue; // SR assembly failed
550
551 // Precise duplicates
552 int32_t searchWindow = 500;
553 bool svExists = false;
554 TVariants::iterator itOther = std::lower_bound(pe.begin(), pe.end(), StructuralVariantRecord(sr[i].chr, std::max(0, sr[i].svStart - searchWindow), sr[i].svEnd));
555 for(; ((itOther != pe.end()) && (std::abs(itOther->svStart - sr[i].svStart) < searchWindow)); ++itOther) {
556 if ((itOther->svt != svt) || (itOther->precise)) continue;
557 if ((sr[i].chr != itOther->chr) || (sr[i].chr2 != itOther->chr2)) continue; // Mismatching chr
558
559 // Breakpoints within PE confidence interval?
560 if ((itOther->svStart + itOther->ciposlow < sr[i].svStart) && (sr[i].svStart < itOther->svStart + itOther->ciposhigh)) {
561 if ((itOther->svEnd + itOther->ciendlow < sr[i].svEnd) && (sr[i].svEnd < itOther->svEnd + itOther->ciendhigh)) {
562 svExists = true;
563 // Augment PE record
564 itOther->svStart = sr[i].svStart;
565 itOther->svEnd = sr[i].svEnd;
566 itOther->ciposlow = sr[i].ciposlow;
567 itOther->ciposhigh = sr[i].ciposhigh;
568 itOther->ciendlow = sr[i].ciendlow;
569 itOther->ciendhigh = sr[i].ciendhigh;
570 itOther->srMapQuality = sr[i].srMapQuality;
571 itOther->srSupport = sr[i].srSupport;
572 itOther->insLen = sr[i].insLen;
573 itOther->homLen = sr[i].homLen;
574 itOther->srAlignQuality = sr[i].srAlignQuality;
575 itOther->precise = true;
576 itOther->consensus = sr[i].consensus;
577 itOther->consBp = sr[i].consBp;
578 itOther->mapq += sr[i].mapq;
579 }
580 }
581 }
582
583 // SR only SV
584 if (!svExists) {
585 // Make sure there is no PRECISE duplicate
586 int32_t precSearchWindow = 10;
587 bool preciseDuplicate = false;
588 for(int32_t j = i + 1; j < (int32_t) sr.size(); ++j) {
589 if (std::abs(sr[i].svStart - sr[j].svStart) > precSearchWindow) break;
590 if (sr[i].svt != sr[j].svt) continue; // Mismatching SV types
591 if ((sr[i].chr != sr[j].chr) || (sr[i].chr2 != sr[j].chr2)) continue; // Mismatching chr
592
593 // Breakpoints within PE confidence interval?
594 if ((sr[j].svStart + sr[j].ciposlow <= sr[i].svStart) && (sr[i].svStart <= sr[j].svStart + sr[j].ciposhigh)) {
595 if ((sr[j].svEnd + sr[j].ciendlow <= sr[i].svEnd) && (sr[i].svEnd <= sr[j].svEnd + sr[j].ciendhigh)) {
596 // Duplicate, keep better call
597 if ((sr[i].srSupport < sr[j].srSupport) || ((i < j) && (sr[i].srSupport == sr[j].srSupport))) preciseDuplicate = true;
598 }
599 }
600 }
601 for(int32_t j = i - 1; j>=0; --j) {
602 if (std::abs(sr[i].svStart - sr[j].svStart) > precSearchWindow) break;
603 if (sr[i].svt != sr[j].svt) continue; // Mismatching SV types
604 if ((sr[i].chr != sr[j].chr) || (sr[i].chr2 != sr[j].chr2)) continue; // Mismatching chr
605
606 // Breakpoints within PE confidence interval?
607 if ((sr[j].svStart + sr[j].ciposlow < sr[i].svStart) && (sr[i].svStart < sr[j].svStart + sr[j].ciposhigh)) {
608 if ((sr[j].svEnd + sr[j].ciendlow < sr[i].svEnd) && (sr[i].svEnd < sr[j].svEnd + sr[j].ciendhigh)) {
609 // Duplicate, keep better call
610 if ((sr[i].srSupport < sr[j].srSupport) || ((i < j) && (sr[i].srSupport == sr[j].srSupport))) preciseDuplicate = true;
611 }
612 }
613 }
614 if (!preciseDuplicate) {
615 pe.push_back(sr[i]);
616 sort(pe.begin(), pe.end());
617 }
618 }
619 }
620 }
621 }
622
623
624 }
625
626 #endif