Debian Codegraph @

src/junction.h

raw symbols SCIP
1 #ifndef JUNCTION_H
2 #define JUNCTION_H
3
4 #include <boost/filesystem.hpp>
5 #include <boost/algorithm/string.hpp>
6 #include <boost/algorithm/string.hpp>
7 #include <boost/iostreams/filtering_streambuf.hpp>
8 #include <boost/iostreams/filtering_stream.hpp>
9 #include <boost/iostreams/copy.hpp>
10 #include <boost/iostreams/filter/gzip.hpp>
11 #include <boost/iostreams/device/file.hpp>
12
13 #include <htslib/sam.h>
14
15 #include "util.h"
16 #include "assemble.h"
17 #include "pangenome.h"
18
19 namespace torali
20 {
21
22 template<typename TReadBp>
23 inline void
24 _insertJunction(TReadBp& readBp, std::size_t const seed, bam1_t* rec, int32_t const rp, int32_t const sp, bool const scleft) {
25 bool fw = true;
26 if (rec->core.flag & BAM_FREVERSE) fw = false;
27 int32_t readStart = rec->core.pos;
28 if (rec->core.flag & (BAM_FQCFAIL | BAM_FDUP | BAM_FUNMAP | BAM_FSECONDARY | BAM_FSUPPLEMENTARY)) readStart = -1;
29 typedef typename TReadBp::mapped_type TJunctionVector;
30 typename TReadBp::iterator it = readBp.find(seed);
31 int32_t seqlen = readLength(rec);
32 if (sp <= seqlen) {
33 if (rec->core.flag & BAM_FREVERSE) {
34 if (it != readBp.end()) it->second.push_back(Junction(fw, scleft, rec->core.tid, readStart, rp, seqlen - sp, rec->core.qual));
35 else readBp.insert(std::make_pair(seed, TJunctionVector(1, Junction(fw, scleft, rec->core.tid, readStart, rp, seqlen - sp, rec->core.qual))));
36 } else {
37 if (it != readBp.end()) it->second.push_back(Junction(fw, scleft, rec->core.tid, readStart, rp, sp, rec->core.qual));
38 else readBp.insert(std::make_pair(seed, TJunctionVector(1, Junction(fw, scleft, rec->core.tid, readStart, rp, sp, rec->core.qual))));
39 }
40 }
41 }
42
43 inline int32_t
44 _selectReadStart(std::vector<Junction> const& jcvec) {
45 for(uint32_t i = 0; i < jcvec.size(); ++i) {
46 if (jcvec[i].rstart != -1) return jcvec[i].rstart;
47 }
48 return -1;
49 }
50
51 // Deletion junctions
52 template<typename TConfig, typename TReadBp>
53 inline void
54 selectDeletions(TConfig const& c, TReadBp const& readBp, std::vector<std::vector<SRBamRecord> >& br) {
55 for(typename TReadBp::const_iterator it = readBp.begin(); it != readBp.end(); ++it) {
56 if (it->second.size() > 1) {
57 int32_t rst = _selectReadStart(it->second);
58 for(uint32_t i = 0; i < it->second.size(); ++i) {
59 for(uint32_t j = i+1; j < it->second.size(); ++j) {
60 if ((uint32_t) (it->second[j].seqpos - it->second[i].seqpos) > c.maxReadSep) break;
61 // Same chr, same direction, opposing soft-clips
62 if ((it->second[j].refidx == it->second[i].refidx) && (it->second[j].forward == it->second[i].forward) && (it->second[i].scleft != it->second[j].scleft)) {
63 // Min. deletion size
64 int32_t dellen = 0;
65 if (it->second[i].forward) {
66 if (!it->second[i].scleft) {
67 if (it->second[i].refpos <= it->second[j].refpos) dellen = (it->second[j].refpos - it->second[i].refpos) - (it->second[j].seqpos - it->second[i].seqpos);
68 else dellen = 0;
69 } else {
70 if (it->second[i].refpos <= it->second[j].refpos) dellen = 0;
71 else dellen = (it->second[i].refpos - it->second[j].refpos) + (it->second[j].seqpos - it->second[i].seqpos);
72 }
73 } else {
74 if (it->second[i].scleft) {
75 if (it->second[i].refpos <= it->second[j].refpos) dellen = 0;
76 else dellen = (it->second[i].refpos - it->second[j].refpos) - (it->second[j].seqpos - it->second[i].seqpos);
77 } else {
78 if (it->second[i].refpos <= it->second[j].refpos) dellen = (it->second[j].refpos - it->second[i].refpos) + (it->second[j].seqpos - it->second[i].seqpos);
79 else dellen = 0;
80 }
81 }
82 if (dellen > (int32_t) c.minRefSep) {
83 // Avg. qval
84 int32_t qval = (int32_t) (((int32_t) it->second[i].qual + (int32_t) it->second[j].qual) / 2);
85 // Correct clipping architecture, note: soft-clipping of error-prone reads can lead to switching left/right breakpoints
86 if (it->second[i].refpos <= it->second[j].refpos) {
87 if ((!it->second[i].scleft) && (it->second[j].scleft)) {
88 br[2].push_back(SRBamRecord(it->second[i].refidx, it->second[i].refpos, it->second[j].refidx, it->second[j].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
89 }
90 } else {
91 if ((it->second[i].scleft) && (!it->second[j].scleft)) {
92 br[2].push_back(SRBamRecord(it->second[j].refidx, it->second[j].refpos, it->second[i].refidx, it->second[i].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
93 }
94 }
95 break; // Only report first SV split to avoid ambiguities
96 }
97 }
98 }
99 }
100 }
101 }
102 }
103
104
105 // Duplication junctions
106 template<typename TConfig, typename TReadBp>
107 inline void
108 selectDuplications(TConfig const& c, TReadBp const& readBp, std::vector<std::vector<SRBamRecord> >& br) {
109 for(typename TReadBp::const_iterator it = readBp.begin(); it != readBp.end(); ++it) {
110 if (it->second.size() > 1) {
111 int32_t rst = _selectReadStart(it->second);
112 for(uint32_t i = 0; i < it->second.size(); ++i) {
113 for(uint32_t j = i+1; j < it->second.size(); ++j) {
114 if ((uint32_t) (it->second[j].seqpos - it->second[i].seqpos) > c.maxReadSep) break;
115 // Same chr, same direction, opposing soft-clips
116 if ((it->second[j].refidx == it->second[i].refidx) && (it->second[j].forward == it->second[i].forward) && (it->second[i].scleft != it->second[j].scleft)) {
117 // Min. duplication size
118 if ( (uint32_t) std::abs(it->second[j].refpos - it->second[i].refpos) > c.minRefSep) {
119 // Avg. qval
120 int32_t qval = (int32_t) (((int32_t) it->second[i].qual + (int32_t) it->second[j].qual) / 2);
121 // Correct clipping architecture, note: soft-clipping of error-prone reads can lead to switching left/right breakpoints
122 if (it->second[i].refpos <= it->second[j].refpos) {
123 if ((it->second[i].scleft) && (!it->second[j].scleft)) {
124 br[3].push_back(SRBamRecord(it->second[i].refidx, it->second[i].refpos, it->second[j].refidx, it->second[j].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
125 }
126 } else {
127 if ((!it->second[i].scleft) && (it->second[j].scleft)) {
128 br[3].push_back(SRBamRecord(it->second[j].refidx, it->second[j].refpos, it->second[i].refidx, it->second[i].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
129 }
130 }
131 }
132 }
133 }
134 }
135 }
136 }
137 }
138
139 // Inversion junctions
140 template<typename TConfig, typename TReadBp>
141 inline void
142 selectInversions(TConfig const& c, TReadBp const& readBp, std::vector<std::vector<SRBamRecord> >& br) {
143 for(typename TReadBp::const_iterator it = readBp.begin(); it != readBp.end(); ++it) {
144 if (it->second.size() > 1) {
145 int32_t rst = _selectReadStart(it->second);
146 for(uint32_t i = 0; i < it->second.size(); ++i) {
147 for(uint32_t j = i+1; j < it->second.size(); ++j) {
148 if ((uint32_t) (it->second[j].seqpos - it->second[i].seqpos) > c.maxReadSep) break;
149 // Same chr, different direction, agreeing soft-clips
150 if ((it->second[j].refidx == it->second[i].refidx) && (it->second[j].forward != it->second[i].forward) && (it->second[i].scleft == it->second[j].scleft)) {
151 // Min. inversion size
152 if ( (uint32_t) std::abs(it->second[j].refpos - it->second[i].refpos) > c.minRefSep) {
153 // Avg. qval
154 int32_t qval = (int32_t) (((int32_t) it->second[i].qual + (int32_t) it->second[j].qual) / 2);
155 if (it->second[i].refpos <= it->second[j].refpos) {
156 // Need to differentiate 3to3 and 5to5
157 if (it->second[i].scleft) br[1].push_back(SRBamRecord(it->second[i].refidx, it->second[i].refpos, it->second[j].refidx, it->second[j].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
158 else br[0].push_back(SRBamRecord(it->second[i].refidx, it->second[i].refpos, it->second[j].refidx, it->second[j].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
159 } else {
160 // Need to differentiate 3to3 and 5to5
161 if (it->second[i].scleft) br[1].push_back(SRBamRecord(it->second[j].refidx, it->second[j].refpos, it->second[i].refidx, it->second[i].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
162 else br[0].push_back(SRBamRecord(it->second[j].refidx, it->second[j].refpos, it->second[i].refidx, it->second[i].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
163 }
164 }
165 }
166 }
167 }
168 }
169 }
170 }
171
172 // Insertion junctions
173 template<typename TConfig, typename TReadBp>
174 inline void
175 selectInsertions(TConfig const& c, TReadBp const& readBp, std::vector<std::vector<SRBamRecord> >& br) {
176 for(typename TReadBp::const_iterator it = readBp.begin(); it != readBp.end(); ++it) {
177 if (it->second.size() > 1) {
178 int32_t rst = _selectReadStart(it->second);
179 for(uint32_t i = 0; i < it->second.size(); ++i) {
180 for(uint32_t j = i+1; j < it->second.size(); ++j) {
181 // Same chr, same direction, opposing soft-clips
182 if ((it->second[j].refidx == it->second[i].refidx) && (it->second[j].forward == it->second[i].forward) && (it->second[i].scleft != it->second[j].scleft)) {
183 // Reference insertion footprint should be small
184 if ( (uint32_t) std::abs(it->second[j].refpos - it->second[i].refpos) < c.maxReadSep) {
185 // Large separation in sequence space
186 int32_t isizelen = 0;
187 if (it->second[i].forward) {
188 if (!it->second[i].scleft) {
189 if (it->second[i].refpos <= it->second[j].refpos) isizelen = (it->second[j].seqpos - it->second[i].seqpos) - (it->second[j].refpos - it->second[i].refpos);
190 else isizelen = (it->second[j].seqpos - it->second[i].seqpos) + (it->second[i].refpos - it->second[j].refpos);
191 } else isizelen = 0;
192 } else {
193 if (it->second[i].scleft) {
194 if (it->second[i].refpos <= it->second[j].refpos) isizelen = (it->second[j].seqpos - it->second[i].seqpos) + (it->second[j].refpos - it->second[i].refpos);
195 else isizelen = (it->second[j].seqpos - it->second[i].seqpos) - (it->second[i].refpos - it->second[j].refpos);
196 } else isizelen = 0;
197 }
198 if ((isizelen > (int32_t) c.minRefSep) && (isizelen < std::max(it->second[i].seqpos, it->second[j].seqpos))) {
199 // Avg. qval
200 int32_t qval = (int32_t) (((int32_t) it->second[i].qual + (int32_t) it->second[j].qual) / 2);
201 if (it->second[i].refpos <= it->second[j].refpos) {
202 br[4].push_back(SRBamRecord(it->second[i].refidx, it->second[i].refpos, it->second[j].refidx, it->second[j].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, isizelen, it->first));
203 } else {
204 br[4].push_back(SRBamRecord(it->second[j].refidx, it->second[j].refpos, it->second[i].refidx, it->second[i].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, isizelen, it->first));
205 }
206 break; // Only report first SV split to avoid ambiguities
207 }
208 }
209 }
210 }
211 }
212 }
213 }
214 }
215
216
217 // Translocation junctions
218 template<typename TConfig, typename TReadBp>
219 inline void
220 selectTranslocations(TConfig const& c, TReadBp const& readBp, std::vector<std::vector<SRBamRecord> >& br) {
221 for(typename TReadBp::const_iterator it = readBp.begin(); it != readBp.end(); ++it) {
222 if (it->second.size() > 1) {
223 int32_t rst = _selectReadStart(it->second);
224 for(uint32_t i = 0; i < it->second.size(); ++i) {
225 for(uint32_t j = i+1; j < it->second.size(); ++j) {
226 if ((uint32_t) (it->second[j].seqpos - it->second[i].seqpos) > c.maxReadSep) break;
227 // Different chr
228 if (it->second[j].refidx != it->second[i].refidx) {
229 int32_t chr1ev = j;
230 int32_t chr2ev = i;
231 if (it->second[i].refidx < it->second[j].refidx) {
232 chr1ev = i;
233 chr2ev = j;
234 }
235 // Avg. qval
236 int32_t qval = (int32_t) (((int32_t) it->second[i].qual + (int32_t) it->second[j].qual) / 2);
237 if (it->second[chr1ev].forward == it->second[chr2ev].forward) {
238 // Same direction, opposing soft-clips
239 if (it->second[chr1ev].scleft != it->second[chr2ev].scleft) {
240 if (it->second[chr1ev].scleft) {
241 // 3to5
242 br[DELLY_SVT_TRANS + 2].push_back(SRBamRecord(it->second[chr2ev].refidx, it->second[chr2ev].refpos, it->second[chr1ev].refidx, it->second[chr1ev].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
243 } else {
244 // 5to3
245 br[DELLY_SVT_TRANS + 3].push_back(SRBamRecord(it->second[chr2ev].refidx, it->second[chr2ev].refpos, it->second[chr1ev].refidx, it->second[chr1ev].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
246 }
247 }
248 } else {
249 // Opposing direction, same soft-clips
250 if (it->second[chr1ev].scleft == it->second[chr2ev].scleft) {
251 if (it->second[chr1ev].scleft) {
252 // 5to5
253 br[DELLY_SVT_TRANS + 1].push_back(SRBamRecord(it->second[chr2ev].refidx, it->second[chr2ev].refpos, it->second[chr1ev].refidx, it->second[chr1ev].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
254 } else {
255 // 3to3
256 br[DELLY_SVT_TRANS + 0].push_back(SRBamRecord(it->second[chr2ev].refidx, it->second[chr2ev].refpos, it->second[chr1ev].refidx, it->second[chr1ev].refpos, rst, std::min(it->second[j].seqpos, it->second[i].seqpos), qval, std::abs(it->second[j].seqpos - it->second[i].seqpos), it->first));
257 }
258 }
259 }
260 }
261 }
262 }
263 }
264 }
265 }
266
267
268 // Insertion junctions
269 template<typename TReadBp>
270 inline void
271 bridgeInsertions(TReadBp const& readBp, std::vector<std::vector<SRBamRecord> >& br) {
272 // Insertion map
273 std::unordered_set<std::size_t> readIds;
274 typedef std::pair<uint32_t, uint32_t> TRefCoord;
275 typedef std::map<TRefCoord, int32_t> TPosInsMap;
276 TPosInsMap pins;
277
278 // Iterate all split-reads with insertions
279 for(uint32_t i = 0; i < br[4].size(); ++i) {
280 readIds.insert(br[4][i].id);
281 for(int32_t k = br[4][i].pos; k <= br[4][i].pos2; ++k) {
282 TRefCoord rc = std::make_pair(br[4][i].chr, k);
283 typename TPosInsMap::iterator it = pins.find(rc);
284 if (it == pins.end()) pins.insert(std::make_pair(rc, br[4][i].inslen));
285 else it->second = (it->second + br[4][i].inslen) / 2;
286 }
287 }
288 if (!pins.empty()) {
289 for(typename TReadBp::const_iterator it = readBp.begin(); it != readBp.end(); ++it) {
290 if (readIds.find(it->first) == readIds.end()) {
291 for(uint32_t i = 0; i < it->second.size(); ++i) {
292 // Any insertion?
293 TRefCoord rc = std::make_pair(it->second[i].refidx, it->second[i].refpos);
294 if (pins.find(rc) != pins.end()) {
295 int32_t qval = (int32_t) it->second[i].qual;
296 int32_t rst = _selectReadStart(it->second);
297 br[4].push_back(SRBamRecord(it->second[i].refidx, it->second[i].refpos, it->second[i].refidx, it->second[i].refpos + 1, rst, it->second[i].seqpos, qval, pins[rc], it->first));
298 }
299 }
300 }
301 }
302 }
303 }
304
305
306 template<typename TConfig, typename TValidRegion, typename TReadBp>
307 inline void
308 findJunctions(TConfig const& c, TValidRegion const& validRegions, TReadBp& readBp, std::set<size_t>& validSR) {
309 typedef typename TValidRegion::value_type TChrIntervals;
310
311 // Open file handles
312 typedef std::vector<samFile*> TSamFile;
313 typedef std::vector<hts_idx_t*> TIndex;
314 TSamFile samfile(c.files.size());
315 TIndex idx(c.files.size());
316 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
317 samfile[file_c] = sam_open(c.files[file_c].string().c_str(), "r");
318 hts_set_fai_filename(samfile[file_c], c.genome.string().c_str());
319 idx[file_c] = sam_index_load(samfile[file_c], c.files[file_c].string().c_str());
320 }
321 bam_hdr_t* hdr = sam_hdr_read(samfile[0]);
322
323 // Parse genome chr-by-chr
324 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
325 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Split-read scanning" << std::endl;
326
327 // Iterate chromosomes
328 for(int32_t refIndex=0; refIndex < (int32_t) hdr->n_targets; ++refIndex) {
329 if (validRegions[refIndex].empty()) continue;
330
331 // Collect reads from all samples
332 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
333 // Read alignments
334 for(typename TChrIntervals::const_iterator vRIt = validRegions[refIndex].begin(); vRIt != validRegions[refIndex].end(); ++vRIt) {
335 hts_itr_t* iter = sam_itr_queryi(idx[file_c], refIndex, vRIt->lower(), vRIt->upper());
336 bam1_t* rec = bam_init1();
337 while (sam_itr_next(samfile[file_c], iter, rec) >= 0) {
338
339 // Keep secondary alignments
340 if (rec->core.flag & (BAM_FQCFAIL | BAM_FDUP | BAM_FUNMAP)) continue;
341 if ((rec->core.qual < c.minMapQual) || (rec->core.tid<0)) continue;
342
343 std::size_t seed = hash_lr(rec);
344 if ((!validSR.empty()) && (validSR.find(seed) == validSR.end())) continue;
345 //std::cerr << bam_get_qname(rec) << '\t' << seed << std::endl;
346 uint32_t rp = rec->core.pos; // reference pointer
347 uint32_t sp = 0; // sequence pointer
348
349 // Parse the CIGAR
350 const uint32_t* cigar = bam_get_cigar(rec);
351 for (std::size_t i = 0; i < rec->core.n_cigar; ++i) {
352 if ((bam_cigar_op(cigar[i]) == BAM_CMATCH) || (bam_cigar_op(cigar[i]) == BAM_CEQUAL) || (bam_cigar_op(cigar[i]) == BAM_CDIFF)) {
353 sp += bam_cigar_oplen(cigar[i]);
354 rp += bam_cigar_oplen(cigar[i]);
355 } else if (bam_cigar_op(cigar[i]) == BAM_CDEL) {
356 if (bam_cigar_oplen(cigar[i]) > c.minRefSep) _insertJunction(readBp, seed, rec, rp, sp, false);
357 rp += bam_cigar_oplen(cigar[i]);
358 if (bam_cigar_oplen(cigar[i]) > c.minRefSep) { // Try look-ahead
359 uint32_t spOrig = sp;
360 uint32_t rpTmp = rp;
361 uint32_t spTmp = sp;
362 uint32_t dlen = bam_cigar_oplen(cigar[i]);
363 for (std::size_t j = i + 1; j < rec->core.n_cigar; ++j) {
364 if ((bam_cigar_op(cigar[j]) == BAM_CMATCH) || (bam_cigar_op(cigar[j]) == BAM_CEQUAL) || (bam_cigar_op(cigar[j]) == BAM_CDIFF)) {
365 spTmp += bam_cigar_oplen(cigar[j]);
366 rpTmp += bam_cigar_oplen(cigar[j]);
367 if ((double) (spTmp - sp) / (double) (dlen + (rpTmp - rp)) > c.indelExtension) break;
368 } else if (bam_cigar_op(cigar[j]) == BAM_CDEL) {
369 rpTmp += bam_cigar_oplen(cigar[j]);
370 if (bam_cigar_oplen(cigar[j]) > c.minRefSep) {
371 // Extend deletion
372 dlen += (rpTmp - rp);
373 rp = rpTmp;
374 sp = spTmp;
375 i = j;
376 }
377 } else if (bam_cigar_op(cigar[j]) == BAM_CINS) {
378 if (bam_cigar_oplen(cigar[j]) > c.minRefSep) break; // No extension
379 spTmp += bam_cigar_oplen(cigar[j]);
380 } else break; // No extension
381 }
382 _insertJunction(readBp, seed, rec, rp, spOrig, true);
383 }
384 } else if (bam_cigar_op(cigar[i]) == BAM_CINS) {
385 if (bam_cigar_oplen(cigar[i]) > c.minRefSep) _insertJunction(readBp, seed, rec, rp, sp, false);
386 sp += bam_cigar_oplen(cigar[i]);
387 if (bam_cigar_oplen(cigar[i]) > c.minRefSep) { // Try look-ahead
388 uint32_t rpOrig = rp;
389 uint32_t rpTmp = rp;
390 uint32_t spTmp = sp;
391 uint32_t ilen = bam_cigar_oplen(cigar[i]);
392 for (std::size_t j = i + 1; j < rec->core.n_cigar; ++j) {
393 if ((bam_cigar_op(cigar[j]) == BAM_CMATCH) || (bam_cigar_op(cigar[j]) == BAM_CEQUAL) || (bam_cigar_op(cigar[j]) == BAM_CDIFF)) {
394 spTmp += bam_cigar_oplen(cigar[j]);
395 rpTmp += bam_cigar_oplen(cigar[j]);
396 if ((double) (rpTmp - rp) / (double) (ilen + (spTmp - sp)) > c.indelExtension) break;
397 } else if (bam_cigar_op(cigar[j]) == BAM_CDEL) {
398 if (bam_cigar_oplen(cigar[j]) > c.minRefSep) break; // No extension
399 rpTmp += bam_cigar_oplen(cigar[j]);
400 } else if (bam_cigar_op(cigar[j]) == BAM_CINS) {
401 spTmp += bam_cigar_oplen(cigar[j]);
402 if (bam_cigar_oplen(cigar[j]) > c.minRefSep) {
403 // Extend insertion
404 ilen += (spTmp - sp);
405 rp = rpTmp;
406 sp = spTmp;
407 i = j;
408 }
409 } else {
410 break; // No extension
411 }
412 }
413 _insertJunction(readBp, seed, rec, rpOrig, sp, true);
414 }
415 } else if (bam_cigar_op(cigar[i]) == BAM_CREF_SKIP) {
416 rp += bam_cigar_oplen(cigar[i]);
417 } else if ((bam_cigar_op(cigar[i]) == BAM_CSOFT_CLIP) || (bam_cigar_op(cigar[i]) == BAM_CHARD_CLIP)) {
418 int32_t finalsp = sp;
419 bool scleft = false;
420 if (sp == 0) {
421 finalsp += bam_cigar_oplen(cigar[i]); // Leading soft-clip / hard-clip
422 scleft = true;
423 }
424 sp += bam_cigar_oplen(cigar[i]);
425 //std::cerr << bam_get_qname(rec) << ',' << rp << ',' << finalsp << ',' << scleft << std::endl;
426 if (bam_cigar_oplen(cigar[i]) > c.minClip) _insertJunction(readBp, seed, rec, rp, finalsp, scleft);
427 } else {
428 std::cerr << "Unknown Cigar options" << std::endl;
429 }
430 }
431 }
432 bam_destroy1(rec);
433 hts_itr_destroy(iter);
434 }
435 }
436 }
437
438 // Sort junctions
439 for(typename TReadBp::iterator it = readBp.begin(); it != readBp.end(); ++it) std::sort(it->second.begin(), it->second.end());
440
441 // Clean-up
442 bam_hdr_destroy(hdr);
443 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
444 hts_idx_destroy(idx[file_c]);
445 sam_close(samfile[file_c]);
446 }
447 }
448
449
450 template<typename TConfig, typename TReadBp>
451 inline void
452 fetchSVs(TConfig const& c, TReadBp& readBp, std::vector<std::vector<SRBamRecord> >& br) {
453 // Extract BAM records
454 if ((c.svtset.empty()) || (c.svtset.find(2) != c.svtset.end())) selectDeletions(c, readBp, br);
455 if ((c.svtset.empty()) || (c.svtset.find(3) != c.svtset.end())) selectDuplications(c, readBp, br);
456 if ((c.svtset.empty()) || (c.svtset.find(0) != c.svtset.end()) || (c.svtset.find(1) != c.svtset.end())) selectInversions(c, readBp, br);
457 if ((c.svtset.empty()) || (c.svtset.find(4) != c.svtset.end())) {
458 selectInsertions(c, readBp, br);
459 bridgeInsertions(readBp, br);
460 }
461 if ((c.svtset.empty()) || (c.svtset.find(5) != c.svtset.end()) || (c.svtset.find(6) != c.svtset.end()) || (c.svtset.find(7) != c.svtset.end()) || (c.svtset.find(8) != c.svtset.end())) selectTranslocations(c, readBp, br);
462 }
463
464 template<typename TConfig, typename TValidRegions, typename TSvtSRBamRecord>
465 inline void
466 _findSRBreakpoints(TConfig const& c, TValidRegions const& validRegions, TSvtSRBamRecord& srBR, std::set<size_t>& validSR) {
467 // Breakpoints
468 typedef std::vector<Junction> TJunctionVector;
469 typedef boost::unordered_map<std::size_t, TJunctionVector> TReadBp;
470 TReadBp readBp;
471 findJunctions(c, validRegions, readBp, validSR);
472 fetchSVs(c, readBp, srBR);
473 }
474
475 template<typename TConfig, typename TValidRegions, typename TSvtSRBamRecord>
476 inline void
477 _findSRBreakpoints(TConfig const& c, TValidRegions const& validRegions, TSvtSRBamRecord& srBR) {
478 std::set<size_t> validSR;
479 _findSRBreakpoints(c, validRegions, srBR, validSR);
480 }
481
482 template<typename TConfig, typename TValidRegions, typename TSVs, typename TSRStore>
483 inline void
484 _clusterSRReads(TConfig const& c, TValidRegions const& validRegions, TSVs& svc, TSRStore& srStore) {
485 // Split-reads
486 typedef std::vector<SRBamRecord> TSRBamRecord;
487 typedef std::vector<TSRBamRecord> TSvtSRBamRecord;
488 TSvtSRBamRecord srBR(2 * DELLY_SVT_TRANS, TSRBamRecord());
489 _findSRBreakpoints(c, validRegions, srBR);
490
491 // Alternate alignments
492 if (c.hasAltFile) {
493
494 // Insert all split-reads
495 std::set<std::size_t> validSR;
496 for(uint32_t svt = 0; svt < srBR.size(); ++svt) {
497 for(uint32_t i = 0; i < srBR[svt].size(); ++i) validSR.insert(srBR[svt][i].id);
498 }
499
500 // Parse alternate alignments
501 std::vector<boost::filesystem::path> align;
502 std::vector<boost::filesystem::path> genome;
503 _alternateAlignments(c, align, genome);
504 for(uint32_t i = 0; i < align.size(); ++i) {
505 std::cerr << '[' << boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()) << "] " << "Parsing alternate alignment " << align[i] << std::endl;
506
507 TSvtSRBamRecord altSR(2 * DELLY_SVT_TRANS, TSRBamRecord());
508 TConfig altConfig(c);
509 altConfig.hasExcludeFile = false;
510 altConfig.exclude.clear();
511 altConfig.genome = genome[i];
512 altConfig.files.clear();
513 altConfig.files.push_back(align[i]);
514 if (isBamCram(align[i].string())) {
515 // Alternate alignment in BAM/CRAM format
516 samFile* samfile = sam_open(altConfig.files[0].string().c_str(), "r");
517 bam_hdr_t* hdr = sam_hdr_read(samfile);
518 TValidRegions vR;
519 _parseExcludeIntervals(altConfig, hdr, vR);
520 bam_hdr_destroy(hdr);
521 sam_close(samfile);
522 _findSRBreakpoints(altConfig, vR, altSR, validSR);
523
524 // Debug
525 //std::cerr << '[' << boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()) << "] " << "AltLinearAlign: " << align[i] << std::endl;
526 //outputSRBamRecords(altConfig, altSR, true);
527 } else {
528 Graph g;
529 parseGfa(altConfig, g);
530 altConfig.nchr = g.smap.size();
531
532 // Minigraph lacks alignment extension so larger BP separation expected?
533 altConfig.maxReadSep = 2000;
534
535 // Alternate alignment in GAF format
536 _findGraphSRBreakpoints(altConfig, g, altSR, validSR);
537
538 // Debug
539 //std::cerr << '[' << boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()) << "] " << "AltGraphAlign: " << align[i] << std::endl;
540 //outputGraphSRBamRecords(altConfig, g, altSR);
541 }
542
543 // Update valid SR set
544 std::set<std::size_t> newValidSR;
545 for(uint32_t svt = 0; svt < altSR.size(); ++svt) {
546 //std::cerr << '[' << boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()) << "] " << "SVT Size: " << svt << ',' << altSR[svt].size() << std::endl;
547 if (altSR[svt].empty()) continue;
548 for(uint32_t ik = 0; ik < altSR[svt].size(); ++ik) {
549 if (validSR.find(altSR[svt][ik].id) != validSR.end()) newValidSR.insert(altSR[svt][ik].id);
550 }
551 }
552 validSR = newValidSR;
553
554 // Debug
555 //std::cerr << '[' << boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()) << "] " << "SR size: " << validSR.size() << std::endl;
556 }
557
558 // Filter primary SR records
559 uint32_t origSRsize = 0;
560 uint32_t newSRsize = 0;
561 TSvtSRBamRecord copySR(2 * DELLY_SVT_TRANS, TSRBamRecord());
562 for(uint32_t svt = 0; svt < srBR.size(); ++svt) {
563 origSRsize += srBR[svt].size();
564 copySR[svt] = srBR[svt];
565 srBR[svt].clear();
566 for(uint32_t i = 0; i < copySR[svt].size(); ++i) {
567 if (validSR.find(copySR[svt][i].id) != validSR.end()) srBR[svt].push_back(copySR[svt][i]);
568 }
569 newSRsize += srBR[svt].size();
570 }
571 uint32_t filtSR = origSRsize - newSRsize;
572 double filtRatio = 0;
573 if (origSRsize) filtRatio = (double) filtSR / (double) origSRsize;
574 std::cerr << '[' << boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()) << "] " << "Filtered " << filtSR << " out of " << origSRsize << " split-read records (" << (filtRatio * 100) << "%)" << std::endl;
575 }
576
577
578 // Debug
579 //std::cerr << '[' << boost::posix_time::to_simple_string(boost::posix_time::second_clock::local_time()) << "] " << "MainAlign: " << std::endl;
580 //outputSRBamRecords(c, srBR, true);
581
582 // Cluster BAM records
583 for(uint32_t svt = 0; svt < srBR.size(); ++svt) {
584 if (srBR[svt].empty()) continue;
585
586 // Sort
587 std::sort(srBR[svt].begin(), srBR[svt].end());
588
589 // Cluster
590 cluster(c, srBR[svt], svc, svt);
591
592 // Debug
593 //outputStructuralVariants(c, svc, srBR, svt, true);
594 // Track split-reads
595 samFile* samfile = sam_open(c.files[0].string().c_str(), "r");
596 bam_hdr_t* hdr = sam_hdr_read(samfile);
597 for(uint32_t i = 0; i < srBR[svt].size(); ++i) {
598 // Read assigned?
599 if ((srBR[svt][i].svid != -1) && (srBR[svt][i].rstart != -1)) {
600 if (srBR[svt][i].rstart < (int32_t) hdr->target_len[srBR[svt][i].chr]) {
601 if (srStore[srBR[svt][i].chr].find(std::make_pair(srBR[svt][i].rstart, srBR[svt][i].id)) == srStore[srBR[svt][i].chr].end()) srStore[srBR[svt][i].chr].insert(std::make_pair(std::make_pair(srBR[svt][i].rstart, srBR[svt][i].id), std::vector<SeqSlice>()));
602 srStore[srBR[svt][i].chr][std::make_pair(srBR[svt][i].rstart, srBR[svt][i].id)].push_back(SeqSlice(srBR[svt][i].svid, srBR[svt][i].sstart, srBR[svt][i].inslen, srBR[svt][i].qual));
603 }
604 if (srBR[svt][i].chr != srBR[svt][i].chr2) {
605 // Unclear which chr was primary alignment so insert both if and only if rstart < reference length
606 if (srBR[svt][i].rstart < (int32_t) hdr->target_len[srBR[svt][i].chr2]) {
607 if (srStore[srBR[svt][i].chr2].find(std::make_pair(srBR[svt][i].rstart, srBR[svt][i].id)) == srStore[srBR[svt][i].chr2].end()) srStore[srBR[svt][i].chr2].insert(std::make_pair(std::make_pair(srBR[svt][i].rstart, srBR[svt][i].id), std::vector<SeqSlice>()));
608 srStore[srBR[svt][i].chr2][std::make_pair(srBR[svt][i].rstart, srBR[svt][i].id)].push_back(SeqSlice(srBR[svt][i].svid, srBR[svt][i].sstart, srBR[svt][i].inslen, srBR[svt][i].qual));
609 }
610 }
611 }
612 }
613 bam_hdr_destroy(hdr);
614 sam_close(samfile);
615 }
616 }
617
618
619 template<typename TConfig>
620 inline void
621 outputSRBamRecords(TConfig const& c, std::vector<std::vector<SRBamRecord> > const& br, bool const longread) {
622 // Header
623 std::cerr << "qname\tid\tchr1\tpos1\tchr2\tpos2\tsvtype\tct\tqual\tseqpos\tinslen" << std::endl;
624
625 // Hash reads
626 typedef boost::unordered_map<std::size_t, std::string> THashMap;
627 THashMap hm;
628 typedef std::vector<samFile*> TSamFile;
629 typedef std::vector<hts_idx_t*> TIndex;
630 TSamFile samfile(c.files.size());
631 TIndex idx(c.files.size());
632 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
633 samfile[file_c] = sam_open(c.files[file_c].string().c_str(), "r");
634 hts_set_fai_filename(samfile[file_c], c.genome.string().c_str());
635 idx[file_c] = sam_index_load(samfile[file_c], c.files[file_c].string().c_str());
636 }
637 bam_hdr_t* hdr = sam_hdr_read(samfile[0]);
638 for(int32_t refIndex = 0; refIndex < hdr->n_targets; ++refIndex) {
639 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
640 hts_itr_t* iter = sam_itr_queryi(idx[file_c], refIndex, 0, hdr->target_len[refIndex]);
641 bam1_t* rec = bam_init1();
642 while (sam_itr_next(samfile[file_c], iter, rec) >= 0) {
643 if (rec->core.flag & (BAM_FQCFAIL | BAM_FDUP | BAM_FUNMAP)) continue;
644 std::size_t seed;
645 if (longread) seed = hash_lr(rec);
646 else seed = hash_sr(rec);
647 std::string qname = bam_get_qname(rec);
648 if (hm.find(seed) == hm.end()) hm.insert(std::make_pair(seed, qname));
649 else {
650 if (hm[seed] != qname) {
651 std::cerr << "Warning: Hash collision! " << seed << ',' << hm[seed] << ',' << qname << std::endl;
652 }
653 }
654 }
655 bam_destroy1(rec);
656 hts_itr_destroy(iter);
657 }
658 }
659
660 // SVs
661 for(uint32_t svt = 0; svt < br.size(); ++svt) {
662 for(uint32_t i = 0; i < br[svt].size(); ++i) {
663 std::cerr << hm[br[svt][i].id] << '\t' << br[svt][i].id << '\t' << hdr->target_name[br[svt][i].chr] << '\t' << br[svt][i].pos << '\t' << hdr->target_name[br[svt][i].chr2] << '\t' << br[svt][i].pos2 << '\t' << _addID(svt) << '\t' << _addOrientation(svt) << '\t' << br[svt][i].qual << '\t' << br[svt][i].sstart << '\t' << br[svt][i].inslen << std::endl;
664 }
665 }
666
667 // Clean-up
668 bam_hdr_destroy(hdr);
669 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
670 hts_idx_destroy(idx[file_c]);
671 sam_close(samfile[file_c]);
672 }
673 }
674
675 template<typename TConfig, typename TSvtSRBamRecord>
676 inline void
677 outputStructuralVariants(TConfig const& c, std::vector<StructuralVariantRecord> const& svs, TSvtSRBamRecord const& srBR, int32_t const svt, bool const longread) {
678 // Header
679 std::cerr << "chr1\tpos1\tchr2\tpos2\tsvtype\tct\tinslen\tpeSupport\tsrSupport" << std::endl;
680
681 // Hash reads
682 typedef boost::unordered_map<std::size_t, std::string> THashMap;
683 THashMap hm;
684 typedef std::vector<samFile*> TSamFile;
685 typedef std::vector<hts_idx_t*> TIndex;
686 TSamFile samfile(c.files.size());
687 TIndex idx(c.files.size());
688 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
689 samfile[file_c] = sam_open(c.files[file_c].string().c_str(), "r");
690 hts_set_fai_filename(samfile[file_c], c.genome.string().c_str());
691 idx[file_c] = sam_index_load(samfile[file_c], c.files[file_c].string().c_str());
692 }
693 bam_hdr_t* hdr = sam_hdr_read(samfile[0]);
694 for(int32_t refIndex = 0; refIndex < hdr->n_targets; ++refIndex) {
695 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
696 hts_itr_t* iter = sam_itr_queryi(idx[file_c], refIndex, 0, hdr->target_len[refIndex]);
697 bam1_t* rec = bam_init1();
698 while (sam_itr_next(samfile[file_c], iter, rec) >= 0) {
699 if (rec->core.flag & (BAM_FQCFAIL | BAM_FDUP | BAM_FUNMAP)) continue;
700 std::size_t seed;
701 if (longread) seed = hash_lr(rec);
702 else seed = hash_sr(rec);
703 std::string qname = bam_get_qname(rec);
704 if (hm.find(seed) == hm.end()) hm.insert(std::make_pair(seed, qname));
705 else {
706 if (hm[seed] != qname) {
707 std::cerr << "Warning: Hash collision! " << seed << ',' << hm[seed] << ',' << qname << std::endl;
708 }
709 }
710 }
711 bam_destroy1(rec);
712 hts_itr_destroy(iter);
713 }
714 }
715
716 // Track split-reads
717 typedef std::vector<std::string> TReadNameVector;
718 typedef std::vector<TReadNameVector> TSVReadNames;
719 TSVReadNames svReadNames(svs.size(), TReadNameVector());
720 for(uint32_t i = 0; i < srBR[svt].size(); ++i) {
721 if (srBR[svt][i].svid != -1) {
722 svReadNames[srBR[svt][i].svid].push_back(hm[srBR[svt][i].id]);
723 }
724 }
725
726 // SVs
727 for(uint32_t i = 0; i < svs.size(); ++i) {
728 if (svs[i].svt != svt) continue;
729 std::cerr << hdr->target_name[svs[i].chr] << '\t' << svs[i].svStart << '\t' << hdr->target_name[svs[i].chr2] << '\t' << svs[i].svEnd << '\t' << _addID(svs[i].svt) << '\t' << _addOrientation(svs[i].svt) << '\t' << svs[i].insLen << '\t' << svs[i].peSupport << '\t' << svs[i].srSupport << '\t';
730 for(uint32_t k = 0; k < svReadNames[svs[i].id].size(); ++k) std::cerr << svReadNames[svs[i].id][k] << ',';
731 std::cerr << std::endl;
732 }
733
734 // Clean-up
735 bam_hdr_destroy(hdr);
736 for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {
737 hts_idx_destroy(idx[file_c]);
738 sam_close(samfile[file_c]);
739 }
740 }
741
742
743 }
744
745 #endif