Debian Codegraph @

src/gcbias.h

raw symbols SCIP
1 #ifndef GCBIAS_H
2 #define GCBIAS_H
3
4 #include <boost/unordered_map.hpp>
5 #include <boost/program_options/cmdline.hpp>
6 #include <boost/program_options/options_description.hpp>
7 #include <boost/program_options/parsers.hpp>
8 #include <boost/program_options/variables_map.hpp>
9 #include <boost/date_time/posix_time/posix_time.hpp>
10 #include <boost/date_time/gregorian/gregorian.hpp>
11 #include <boost/tuple/tuple.hpp>
12 #include <boost/filesystem.hpp>
13 #include <boost/dynamic_bitset.hpp>
14
15 #include <htslib/faidx.h>
16 #include <htslib/sam.h>
17 #include <htslib/vcf.h>
18
19 #include "scan.h"
20 #include "util.h"
21
22 namespace torali
23 {
24 struct GcBias {
25 int32_t sample;
26 int32_t reference;
27 double fractionSample;
28 double fractionReference;
29 double percentileSample;
30 double percentileReference;
31 double obsexp;
32 double coverage;
33
34 GcBias() : sample(0), reference(0), fractionSample(0), fractionReference(0), percentileSample(0), percentileReference(0), obsexp(0), coverage(0) {}
35 };
36
37 template<typename TConfig>
38 inline std::pair<uint32_t, uint32_t>
39 gcBound(TConfig const& c, std::vector<GcBias>& gcbias) {
40 uint32_t lowerBound = 0;
41 uint32_t upperBound = gcbias.size();
42 for(uint32_t i = 0; i < gcbias.size(); ++i) {
43 if ((gcbias[i].percentileSample < c.exclgc) || (gcbias[i].percentileReference < c.exclgc)) lowerBound = i;
44 if ((gcbias[i].percentileSample + c.exclgc > 1) || (gcbias[i].percentileReference + c.exclgc > 1)) {
45 if (i < upperBound) upperBound = i;
46 }
47 }
48 if (lowerBound >= upperBound) upperBound = lowerBound + 1;
49 /*
50 // Adjust total
51 uint64_t totalSampleCount = 0;
52 uint64_t totalReferenceCount = 0;
53 for(uint32_t i = lowerBound + 1; i < upperBound; ++i) {
54 totalSampleCount += gcbias[i].sample;
55 totalReferenceCount += gcbias[i].reference;
56 }
57 // Re-estimate observed/expected
58 for(uint32_t i = lowerBound + 1; i < upperBound; ++i) {
59 gcbias[i].fractionSample = (double) gcbias[i].sample / (double) totalSampleCount;
60 gcbias[i].fractionReference = (double) gcbias[i].reference / (double) totalReferenceCount;
61 gcbias[i].obsexp = 1;
62 if (gcbias[i].fractionReference > 0) gcbias[i].obsexp = gcbias[i].fractionSample / gcbias[i].fractionReference;
63 }
64 */
65
66 return std::make_pair(lowerBound, upperBound);
67 }
68
69
70 template<typename TConfig, typename TGCBound>
71 inline void
72 gcBias(TConfig const& c, std::vector< std::vector<ScanWindow> > const& scanCounts, LibraryInfo const& li, std::vector<GcBias>& gcbias, TGCBound& gcbound) {
73 // Load bam file
74 samFile* samfile = sam_open(c.bamFile.string().c_str(), "r");
75 hts_set_fai_filename(samfile, c.genome.string().c_str());
76 hts_idx_t* idx = sam_index_load(samfile, c.bamFile.string().c_str());
77 bam_hdr_t* hdr = sam_hdr_read(samfile);
78
79 // Parse bam (contig by contig)
80 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
81 std::cerr << '[' << boost::posix_time::to_simple_string(now) << "] " << "Estimate GC bias" << std::endl;
82
83 faidx_t* faiMap = fai_load(c.mapFile.string().c_str());
84 faidx_t* faiRef = fai_load(c.genome.string().c_str());
85 for (int refIndex = 0; refIndex < hdr->n_targets; ++refIndex) {
86 if (scanCounts[refIndex].empty()) continue;
87
88 // Bin map
89 std::vector<uint16_t> binMap;
90 if (c.hasScanFile) {
91 // Fill bin map
92 binMap.resize(hdr->target_len[refIndex], LAST_BIN);
93 for(uint32_t bin = 0;((bin < scanCounts[refIndex].size()) && (bin < LAST_BIN)); ++bin) {
94 for(int32_t k = scanCounts[refIndex][bin].start; k < scanCounts[refIndex][bin].end; ++k) binMap[k] = bin;
95 }
96 }
97
98 // Check presence in mappability map
99 std::string tname(hdr->target_name[refIndex]);
100 int32_t seqlen = faidx_seq_len(faiMap, tname.c_str());
101 if (seqlen == - 1) continue;
102 else seqlen = -1;
103 char* seq = faidx_fetch_seq(faiMap, tname.c_str(), 0, faidx_seq_len(faiMap, tname.c_str()), &seqlen);
104
105 // Check presence in reference
106 seqlen = faidx_seq_len(faiRef, tname.c_str());
107 if (seqlen == - 1) continue;
108 else seqlen = -1;
109 char* ref = faidx_fetch_seq(faiRef, tname.c_str(), 0, faidx_seq_len(faiRef, tname.c_str()), &seqlen);
110
111 // Get GC and Mappability
112 std::vector<uint16_t> uniqContent(hdr->target_len[refIndex], 0);
113 std::vector<uint16_t> gcContent(hdr->target_len[refIndex], 0);
114 {
115 // Mappability map
116 typedef boost::dynamic_bitset<> TBitSet;
117 TBitSet uniq(hdr->target_len[refIndex], false);
118 for(uint32_t i = 0; i < hdr->target_len[refIndex]; ++i) {
119 if (seq[i] == 'C') uniq[i] = true;
120 }
121
122 // GC map
123 typedef boost::dynamic_bitset<> TBitSet;
124 TBitSet gcref(hdr->target_len[refIndex], false);
125 for(uint32_t i = 0; i < hdr->target_len[refIndex]; ++i) {
126 if ((ref[i] == 'c') || (ref[i] == 'C') || (ref[i] == 'g') || (ref[i] == 'G')) gcref[i] = 1;
127 }
128
129 // Sum across fragments
130 int32_t halfwin = (int32_t) (c.meanisize / 2);
131 int32_t usum = 0;
132 int32_t gcsum = 0;
133 for(int32_t pos = halfwin; pos < (int32_t) hdr->target_len[refIndex] - halfwin; ++pos) {
134 if (pos == halfwin) {
135 for(int32_t i = pos - halfwin; i<=pos+halfwin; ++i) {
136 usum += uniq[i];
137 gcsum += gcref[i];
138 }
139 } else {
140 usum -= uniq[pos - halfwin - 1];
141 gcsum -= gcref[pos - halfwin - 1];
142 usum += uniq[pos + halfwin];
143 gcsum += gcref[pos + halfwin];
144 }
145 gcContent[pos] = gcsum;
146 uniqContent[pos] = usum;
147 }
148 }
149
150 // Coverage track
151 typedef uint16_t TCount;
152 uint32_t maxCoverage = std::numeric_limits<TCount>::max();
153 typedef std::vector<TCount> TCoverage;
154 TCoverage cov(hdr->target_len[refIndex], 0);
155
156 // Mate map
157 typedef boost::unordered_map<std::size_t, bool> TMateMap;
158 TMateMap mateMap;
159
160 // Parse BAM
161 hts_itr_t* iter = sam_itr_queryi(idx, refIndex, 0, hdr->target_len[refIndex]);
162 bam1_t* rec = bam_init1();
163 int32_t lastAlignedPos = 0;
164 std::set<std::size_t> lastAlignedPosReads;
165 while (sam_itr_next(samfile, iter, rec) >= 0) {
166 if (rec->core.flag & (BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP | BAM_FSUPPLEMENTARY | BAM_FUNMAP)) continue;
167 if ((rec->core.flag & BAM_FPAIRED) && ((rec->core.flag & BAM_FMUNMAP) || (rec->core.tid != rec->core.mtid))) continue;
168 if (rec->core.qual < c.minQual) continue;
169
170 int32_t midPoint = rec->core.pos + halfAlignmentLength(rec);
171 if (rec->core.flag & BAM_FPAIRED) {
172 // Clean-up the read store for identical alignment positions
173 if (rec->core.pos > lastAlignedPos) {
174 lastAlignedPosReads.clear();
175 lastAlignedPos = rec->core.pos;
176 }
177
178 // Process pair
179 if ((rec->core.pos < rec->core.mpos) || ((rec->core.pos == rec->core.mpos) && (lastAlignedPosReads.find(hash_string(bam_get_qname(rec))) == lastAlignedPosReads.end()))) {
180 // First read
181 lastAlignedPosReads.insert(hash_string(bam_get_qname(rec)));
182 std::size_t hv = hash_pair(rec);
183 mateMap[hv]= true;
184 continue;
185 } else {
186 // Second read
187 std::size_t hv = hash_pair_mate(rec);
188 if ((mateMap.find(hv) == mateMap.end()) || (!mateMap[hv])) continue; // Mate discarded
189 mateMap[hv] = false;
190 }
191
192 // Insert size filter
193 int32_t isize = (rec->core.pos + alignmentLength(rec)) - rec->core.mpos;
194 if ((li.minNormalISize < isize) && (isize < li.maxNormalISize)) {
195 midPoint = rec->core.mpos + (int32_t) (isize/2);
196 } else {
197 if (rec->core.flag & BAM_FREVERSE) midPoint = rec->core.pos + alignmentLength(rec) - (c.meanisize / 2);
198 else midPoint = rec->core.pos + (c.meanisize / 2);
199 }
200 }
201
202 // Count fragment
203 if ((midPoint >= 0) && (midPoint < (int32_t) hdr->target_len[refIndex]) && (cov[midPoint] < maxCoverage - 1)) ++cov[midPoint];
204 }
205 bam_destroy1(rec);
206 hts_itr_destroy(iter);
207 if (seq != NULL) free(seq);
208 if (ref != NULL) free(ref);
209
210 // Summarize GC coverage for this chromosome
211 for(uint32_t i = 0; i < hdr->target_len[refIndex]; ++i) {
212 if (uniqContent[i] >= c.fragmentUnique * c.meanisize) {
213 // Valid bin?
214 int32_t bin = _findScanWindow(c, hdr->target_len[refIndex], binMap, i);
215 if ((bin >= 0) && (scanCounts[refIndex][bin].select)) {
216 ++gcbias[gcContent[i]].reference;
217 gcbias[gcContent[i]].sample += cov[i];
218 gcbias[gcContent[i]].coverage += cov[i];
219 }
220 }
221 }
222 }
223
224 // Normalize GC coverage
225 for(uint32_t i = 0; i < gcbias.size(); ++i) {
226 if (gcbias[i].reference) gcbias[i].coverage /= (double) gcbias[i].reference;
227 else gcbias[i].coverage = 0;
228 }
229
230 // Determine percentiles
231 uint64_t totalSampleCount = 0;
232 uint64_t totalReferenceCount = 0;
233 for(uint32_t i = 0; i < gcbias.size(); ++i) {
234 totalSampleCount += gcbias[i].sample;
235 totalReferenceCount += gcbias[i].reference;
236 }
237 uint64_t cumSample = 0;
238 uint64_t cumReference = 0;
239 for(uint32_t i = 0; i < gcbias.size(); ++i) {
240 cumSample += gcbias[i].sample;
241 cumReference += gcbias[i].reference;
242 gcbias[i].fractionSample = (double) gcbias[i].sample / (double) totalSampleCount;
243 gcbias[i].fractionReference = (double) gcbias[i].reference / (double) totalReferenceCount;
244 gcbias[i].percentileSample = (double) cumSample / (double) totalSampleCount;
245 gcbias[i].percentileReference = (double) cumReference / (double) totalReferenceCount;
246 gcbias[i].obsexp = 1;
247 if (gcbias[i].fractionReference > 0) gcbias[i].obsexp = gcbias[i].fractionSample / gcbias[i].fractionReference;
248 }
249
250 // Estimate correctable GC range
251 gcbound = gcBound(c, gcbias);
252
253 // Adjust correction to the callable range
254 totalSampleCount = 0;
255 totalReferenceCount = 0;
256 for(uint32_t i = gcbound.first + 1; i < gcbound.second; ++i) {
257 totalSampleCount += gcbias[i].sample;
258 totalReferenceCount += gcbias[i].reference;
259 }
260 cumSample = 0;
261 cumReference = 0;
262 // Re-initialize
263 for(uint32_t i = 0; i < gcbias.size(); ++i) {
264 gcbias[i].fractionSample = 0;
265 gcbias[i].fractionReference = 0;
266 gcbias[i].percentileSample = 0;
267 gcbias[i].percentileReference = 0;
268 gcbias[i].obsexp = 1;
269 }
270 for(uint32_t i = gcbound.first + 1; i < gcbound.second; ++i) {
271 cumSample += gcbias[i].sample;
272 cumReference += gcbias[i].reference;
273 gcbias[i].fractionSample = (double) gcbias[i].sample / (double) totalSampleCount;
274 gcbias[i].fractionReference = (double) gcbias[i].reference / (double) totalReferenceCount;
275 gcbias[i].percentileSample = (double) cumSample / (double) totalSampleCount;
276 gcbias[i].percentileReference = (double) cumReference / (double) totalReferenceCount;
277 gcbias[i].obsexp = 1;
278 if (gcbias[i].fractionReference > 0) gcbias[i].obsexp = gcbias[i].fractionSample / gcbias[i].fractionReference;
279 }
280
281 fai_destroy(faiRef);
282 fai_destroy(faiMap);
283 hts_idx_destroy(idx);
284 sam_close(samfile);
285 bam_hdr_destroy(hdr);
286 }
287
288 }
289
290 #endif