Debian Codegraph @

src/ResultData.cpp

raw
1 #include "ResultData.h"
2 #include "TryCatch.h"
3
4 using namespace std;
5
6
7
8 vcflib::Variant& Results::vcf(
9 vcflib::Variant& var, // variant to update
10 BigFloat pHom,
11 long double bestComboOddsRatio,
12 //long double alleleSamplingProb,
13 Samples& samples,
14 string refbase,
15 vector<Allele>& altAllelesIncludingNulls,
16 map<string, int> repeats,
17 int genotypingIterations,
18 vector<string>& sampleNames,
19 int coverage,
20 GenotypeCombo& genotypeCombo,
21 map<string, vector<Allele*> >& alleleGroups,
22 map<string, vector<Allele*> >& partialObservationGroups,
23 map<Allele*, set<Allele*> >& partialObservationSupport,
24 map<int, vector<Genotype> >& genotypesByPloidy,
25 vector<string>& sequencingTechnologies,
26 AlleleParser* parser) {
27
28 Parameters& parameters = parser->parameters;
29
30 GenotypeComboMap comboMap;
31 genotypeCombo2Map(genotypeCombo, comboMap);
32
33 // set up the reported reference allele
34 long int referencePosition = (long int) parser->currentPosition; // 0-based
35
36 // remove NULL alt alleles
37 vector<Allele> altAlleles;
38 for (vector<Allele>::iterator aa = altAllelesIncludingNulls.begin(); aa != altAllelesIncludingNulls.end(); ++aa) {
39 if (!aa->isNull()) {
40 altAlleles.push_back(*aa);
41 }
42 }
43
44 map<string, string> adjustedCigar;
45 vector<Allele>& adjustedAltAlleles = altAlleles; // just an alias
46 for (vector<Allele>::iterator aa = altAlleles.begin(); aa != altAlleles.end(); ++aa) {
47 adjustedCigar[aa->base()] = aa->cigar;
48 var.alt.push_back(aa->alternateSequence);
49 }
50
51 var.ref = refbase;
52 assert(!var.ref.empty());
53
54 // get the required size of the reference sequence
55 // strip identical bases from start and/or end of alleles
56 // if bases have been stripped from the beginning,
57
58 // set up VCF record-wide variables
59
60 var.sequenceName = parser->currentSequenceName;
61 var.position = referencePosition + 1;
62 var.id = ".";
63 var.filter = ".";
64
65 // note that we set QUAL to 0 at loci with no data
66 var.quality = max((long double) 0, nan2zero(big2phred(pHom)));
67 if (coverage == 0) {
68 var.quality = 0;
69 }
70
71
72 // set up format string
73
74 var.format.clear();
75 var.format.push_back("GT");
76 if (parameters.calculateMarginals) var.format.push_back("GQ");
77 // XXX
78 var.format.push_back("DP");
79 var.format.push_back("AD");
80 var.format.push_back("RO");
81 var.format.push_back("QR");
82 var.format.push_back("AO");
83 var.format.push_back("QA");
84 // add GL/GLE later, when we know if we need to use one or the other
85
86 unsigned int refBasesLeft = 0;
87 unsigned int refBasesRight = 0;
88 unsigned int refReadsLeft = 0;
89 unsigned int refReadsRight = 0;
90 unsigned int refEndLeft = 0;
91 unsigned int refEndRight = 0;
92 unsigned int refmqsum = 0;
93 unsigned int refProperPairs = 0;
94 long double refReadMismatchSum = 0;
95 long double refReadSNPSum = 0;
96 long double refReadIndelSum = 0;
97 long double refReadSoftClipSum = 0;
98 unsigned int refObsCount = 0;
99 map<string, int> refObsBySequencingTechnology;
100
101 map<string, vector<Allele*> >::iterator f = alleleGroups.find(refbase);
102 if (f != alleleGroups.end()) {
103 vector<Allele*>& referenceAlleles = alleleGroups.at(refbase);
104 refObsCount = referenceAlleles.size();
105 for (vector<Allele*>::iterator app = referenceAlleles.begin(); app != referenceAlleles.end(); ++app) {
106 Allele& allele = **app;
107 refReadMismatchSum += allele.readMismatchRate;
108 refReadSNPSum += allele.readSNPRate;
109 refReadIndelSum += allele.readIndelRate;
110 if (allele.isProperPair) {
111 ++refProperPairs;
112 }
113 if (!allele.sequencingTechnology.empty()) {
114 ++refObsBySequencingTechnology[allele.sequencingTechnology];
115 }
116 refBasesLeft += allele.basesLeft;
117 refBasesRight += allele.basesRight;
118 if (allele.basesLeft >= allele.basesRight) {
119 refReadsLeft += 1;
120 if (allele.strand == STRAND_FORWARD) {
121 refEndLeft += 1;
122 } else {
123 refEndRight += 1;
124 }
125 } else {
126 refReadsRight += 1;
127 if (allele.strand == STRAND_FORWARD) {
128 refEndRight += 1;
129 } else {
130 refEndLeft += 1;
131 }
132 }
133 refmqsum += allele.mapQuality;
134 }
135 }
136
137 long double refReadMismatchRate = (refObsCount == 0 ? 0 : refReadMismatchSum / (long double) refObsCount);
138 long double refReadSNPRate = (refObsCount == 0 ? 0 : refReadSNPSum / (long double) refObsCount);
139 long double refReadIndelRate = (refObsCount == 0 ? 0 : refReadIndelSum / (long double) refObsCount);
140
141 //var.info["XRM"].push_back(convert(refReadMismatchRate));
142 //var.info["XRS"].push_back(convert(refReadSNPRate));
143 //var.info["XRI"].push_back(convert(refReadIndelRate));
144
145 var.info["MQMR"].push_back(convert((refObsCount == 0) ? 0 : (double) refmqsum / (double) refObsCount));
146 var.info["RPPR"].push_back(convert((refObsCount == 0) ? 0 : nan2zero(ln2phred(hoeffdingln(refReadsLeft, refReadsRight + refReadsLeft, 0.5)))));
147 var.info["EPPR"].push_back(convert((refBasesLeft + refBasesRight == 0) ? 0 : nan2zero(ln2phred(hoeffdingln(refEndLeft, refEndLeft + refEndRight, 0.5)))));
148 var.info["PAIREDR"].push_back(convert((refObsCount == 0) ? 0 : (double) refProperPairs / (double) refObsCount));
149
150 //var.info["HWE"].push_back(convert(nan2zero(ln2phred(genotypeCombo.hweComboProb()))));
151 var.info["GTI"].push_back(convert(genotypingIterations));
152
153 // loop over all alternate alleles
154 for (vector<Allele>::iterator aa = altAlleles.begin(); aa != altAlleles.end(); ++aa) {
155
156 Allele& altAllele = *aa;
157 string altbase = altAllele.base();
158
159 // count alternate alleles in the best genotyping
160 unsigned int alternateCount = 0;
161 unsigned int alleleCount = 0;
162 double alternateQualitySum = 0;
163 double partialObservationCount = 0;
164 double partialObservationQualitySum;
165 // reference / alternate base counts by strand
166 //map<string, unsigned int> altCountBySample;
167 //map<string, unsigned int> altQualBySample;
168 // het counts
169 unsigned int hetReferenceObsCount = 0;
170 unsigned int hetOtherObsCount = 0;
171 unsigned int hetAlternateObsCount = 0;
172 unsigned int hetAltSamples = 0;
173 unsigned int homAltSamples = 0;
174 unsigned int homRefSamples = 0;
175 unsigned int refSampleObsCount = 0; // depth in hom-ref samples
176 unsigned int altSampleObsCount = 0; // depth in samples with called alternates
177 // unique alternate alleles / all alternate alleles in alt-associated samples
178 unsigned int uniqueAllelesInAltSamples = 0;
179 //unsigned int hetAllObsCount = hetOtherObsCount + hetAlternateObsCount + hetReferenceObsCount;
180 unsigned int hetAllObsCount = 0;
181
182 StrandBaseCounts baseCountsTotal;
183 map<string, StrandBaseCounts> baseCountsBySample;
184 for (vector<string>::iterator sampleName = sampleNames.begin(); sampleName != sampleNames.end(); ++sampleName) {
185 GenotypeComboMap::iterator gc = comboMap.find(*sampleName);
186 //cerr << "alternate count for " << altbase << " and " << *genotype << " is " << genotype->alleleCount(altbase) << endl;
187 if (gc != comboMap.end()) {
188 Genotype* genotype = gc->second->genotype;
189
190 Sample& sample = *gc->second->sample;
191
192 // check that we actually have observations for this sample
193 unsigned int observationCount = sample.observationCount();
194 if (observationCount == 0) {
195 continue;
196 }
197
198 alternateCount += genotype->alleleCount(altbase);
199 alleleCount += genotype->ploidy;
200
201 unsigned int altCount = sample.observationCount(altbase);
202 unsigned int refCount = sample.observationCount(refbase);
203
204 if (!genotype->homozygous) {
205 // het case
206 if (altCount > 0) {
207 ++hetAltSamples;
208 hetAllObsCount += observationCount;
209 hetReferenceObsCount += refCount;
210 hetOtherObsCount += observationCount - altCount;
211 hetAlternateObsCount += altCount;
212 altSampleObsCount += observationCount;
213 uniqueAllelesInAltSamples += sample.size();
214 if (refCount > 0) {
215 --uniqueAllelesInAltSamples; // ignore reference allele
216 }
217 }
218 } else {
219 if (altCount > 0) {
220 ++homAltSamples;
221 altSampleObsCount += observationCount;
222 uniqueAllelesInAltSamples += sample.size();
223 if (refCount > 0) {
224 --uniqueAllelesInAltSamples; // ignore reference allele
225 }
226 } else {
227 ++homRefSamples;
228 refSampleObsCount += observationCount;
229 }
230 }
231 //altCountBySample[*sampleName] = altCount;
232
233 //altQualBySample[*sampleName] = sample.qualSum(altbase);
234
235 StrandBaseCounts baseCounts = sample.strandBaseCount(refbase, altbase);
236 baseCountsBySample[*sampleName] = baseCounts;
237 baseCountsTotal.forwardRef += baseCounts.forwardRef;
238 baseCountsTotal.forwardAlt += baseCounts.forwardAlt;
239 baseCountsTotal.reverseRef += baseCounts.reverseRef;
240 baseCountsTotal.reverseAlt += baseCounts.reverseAlt;
241 }
242 }
243
244 unsigned int altBasesLeft = 0;
245 unsigned int altBasesRight = 0;
246 unsigned int altReadsLeft = 0;
247 unsigned int altReadsRight = 0;
248 unsigned int altEndLeft = 0;
249 unsigned int altEndRight = 0;
250 unsigned int altmqsum = 0;
251 unsigned int altproperPairs = 0;
252 long double altReadMismatchSum = 0;
253 long double altReadSNPSum = 0;
254 long double altReadIndelSum = 0;
255 unsigned int altObsCount = 0;
256 map<string, int> altObsBySequencingTechnology;
257
258 // TODO we need a partial obs structure to annotate partial obs
259 map<string, vector<Allele*> >::iterator f = alleleGroups.find(altbase);
260 if (f != alleleGroups.end()) {
261 vector<Allele*>& alternateAlleles = alleleGroups.at(altbase);
262 // TODO XXX XXX adjust to use partial observations
263 altObsCount = alternateAlleles.size();
264 for (vector<Allele*>::iterator app = alternateAlleles.begin(); app != alternateAlleles.end(); ++app) {
265 Allele& allele = **app;
266 altReadMismatchSum += allele.readMismatchRate;
267 altReadSNPSum += allele.readSNPRate;
268 altReadIndelSum += allele.readIndelRate;
269 // TODO: add altReadSoftClipRate (avg)
270 if (allele.isProperPair) {
271 ++altproperPairs;
272 }
273 if (!allele.sequencingTechnology.empty()) {
274 ++altObsBySequencingTechnology[allele.sequencingTechnology];
275 }
276 altBasesLeft += allele.basesLeft;
277 altBasesRight += allele.basesRight;
278 if (allele.basesLeft >= allele.basesRight) {
279 altReadsLeft += 1;
280 if (allele.strand == STRAND_FORWARD) {
281 altEndLeft += 1;
282 } else {
283 altEndRight += 1;
284 }
285 } else {
286 altReadsRight += 1;
287 if (allele.strand == STRAND_FORWARD) {
288 altEndRight += 1;
289 } else {
290 altEndLeft += 1;
291 }
292 }
293 altmqsum += allele.mapQuality;
294 }
295 }
296
297 long double altReadMismatchRate = (altObsCount == 0 ? 0 : altReadMismatchSum / altObsCount);
298 long double altReadSNPRate = (altObsCount == 0 ? 0 : altReadSNPSum / altObsCount);
299 long double altReadIndelRate = (altObsCount == 0 ? 0 : altReadIndelSum / altObsCount);
300
301 //var.info["XAM"].push_back(convert(altReadMismatchRate));
302 //var.info["XAS"].push_back(convert(altReadSNPRate));
303 //var.info["XAI"].push_back(convert(altReadIndelRate));
304
305 // alt/ref ratios
306 //var.info["ARM"].push_back(convert(refReadMismatchRate == 0 ? 0 : altReadMismatchRate / refReadMismatchRate));
307 //var.info["ARS"].push_back(convert(refReadSNPRate == 0 ? 0 : altReadSNPRate / refReadSNPRate));
308 //var.info["ARI"].push_back(convert(refReadIndelRate == 0 ? 0 : altReadIndelRate / refReadIndelRate));
309
310 //string refbase = parser->currentReferenceBase();
311 // positional information
312 // CHROM POS ID REF ALT QUAL FILTER INFO FORMAT
313 //out.setf(ios::fixed,ios::floatfield);
314 //out.precision(5);
315
316 var.info["AC"].push_back(convert(alternateCount));
317 var.info["AN"].clear(); var.info["AN"].push_back(convert(alleleCount)); // XXX hack...
318 var.info["AF"].push_back(convert((alleleCount == 0) ? 0 : (double) alternateCount / (double) alleleCount));
319 var.info["AO"].push_back(convert(altObsCount));
320 var.info["PAO"].push_back(convert(samples.partialObservationCount(altbase)));
321 var.info["QA"].push_back(convert(samples.qualSum(altbase)));
322 var.info["PQA"].push_back(convert(samples.partialQualSum(altbase)));
323 if (homRefSamples > 0 && hetAltSamples + homAltSamples > 0) {
324 double altSampleAverageDepth = (double) altSampleObsCount
325 / ( (double) hetAltSamples + (double) homAltSamples );
326 double refSampleAverageDepth = (double) refSampleObsCount / (double) homRefSamples;
327 var.info["DPRA"].push_back(convert(altSampleAverageDepth / refSampleAverageDepth));
328 } else {
329 var.info["DPRA"].push_back(convert(0));
330 }
331
332 var.info["SRP"].clear(); // XXX hack
333 var.info["SRF"].clear();
334 var.info["SRR"].clear();
335 var.info["SRF"].push_back(convert(baseCountsTotal.forwardRef));
336 var.info["SRR"].push_back(convert(baseCountsTotal.reverseRef));
337 var.info["SRP"].push_back(convert((refObsCount == 0) ? 0 : nan2zero(ln2phred(hoeffdingln(baseCountsTotal.forwardRef, refObsCount, 0.5)))));
338 var.info["SAF"].push_back(convert(baseCountsTotal.forwardAlt));
339 var.info["SAR"].push_back(convert(baseCountsTotal.reverseAlt));
340 var.info["SAP"].push_back(convert((altObsCount == 0) ? 0 : nan2zero(ln2phred(hoeffdingln(baseCountsTotal.forwardAlt, altObsCount, 0.5)))));
341 var.info["AB"].push_back(convert((hetAllObsCount == 0) ? 0 : nan2zero((double) hetAlternateObsCount / (double) hetAllObsCount )));
342 var.info["ABP"].push_back(convert((hetAllObsCount == 0) ? 0 : nan2zero(ln2phred(hoeffdingln(hetAlternateObsCount, hetAllObsCount, 0.5)))));
343 var.info["RUN"].push_back(convert(parser->homopolymerRunLeft(altbase) + 1 + parser->homopolymerRunRight(altbase)));
344 var.info["MQM"].push_back(convert((altObsCount == 0) ? 0 : nan2zero((double) altmqsum / (double) altObsCount)));
345 var.info["RPP"].push_back(convert((altObsCount == 0) ? 0 : nan2zero(ln2phred(hoeffdingln(altReadsLeft, altReadsRight + altReadsLeft, 0.5)))));
346 var.info["RPR"].push_back(convert(altReadsRight));
347 var.info["RPL"].push_back(convert(altReadsLeft));
348 var.info["EPP"].push_back(convert((altBasesLeft + altBasesRight == 0) ? 0 : nan2zero(ln2phred(hoeffdingln(altEndLeft, altEndLeft + altEndRight, 0.5)))));
349 var.info["PAIRED"].push_back(convert((altObsCount == 0) ? 0 : nan2zero((double) altproperPairs / (double) altObsCount)));
350 var.info["CIGAR"].push_back(adjustedCigar[altAllele.base()]);
351 var.info["MEANALT"].push_back(convert((hetAltSamples + homAltSamples == 0) ? 0 : nan2zero((double) uniqueAllelesInAltSamples / (double) (hetAltSamples + homAltSamples))));
352
353 for (vector<string>::iterator st = sequencingTechnologies.begin();
354 st != sequencingTechnologies.end(); ++st) { string& tech = *st;
355 var.info["technology." + tech].push_back(convert((altObsCount == 0) ? 0
356 : nan2zero((double) altObsBySequencingTechnology[tech] / (double) altObsCount )));
357 }
358
359 // allele class
360 if (altAllele.type == ALLELE_DELETION) {
361 var.info["TYPE"].push_back("del");
362 // what is the class of deletion
363 // microsatellite repeat?
364 // "novel"?
365 // how large is the repeat, if there is one?
366 } else if (altAllele.type == ALLELE_INSERTION) {
367 var.info["TYPE"].push_back("ins");
368 } else if (altAllele.type == ALLELE_COMPLEX) {
369 var.info["TYPE"].push_back("complex");
370 } else if (altAllele.type == ALLELE_SNP) {
371 var.info["TYPE"].push_back("snp");
372
373 /*
374 // CpG
375 if (parser->isCpG(altbase)) {
376 var.infoFlags["CpG"] = true;
377 }
378 */
379 } else if (altAllele.type == ALLELE_MNP) {
380 var.info["TYPE"].push_back("mnp");
381 } else {
382 /*
383 cerr << "What is this?"
384 << "type: " << altAllele.type << " "
385 << "allele: " << altAllele << endl;
386 */
387 }
388 var.info["LEN"].push_back(convert(altAllele.length));
389
390 }
391
392
393 // set up site-wide INFO tags, non-multiple
394
395 // info variables
396
397 // site-wide coverage
398 int samplesWithData = 0;
399 int refAlleleObservations = 0;
400 for (vector<string>::iterator sampleName = sampleNames.begin(); sampleName != sampleNames.end(); ++sampleName) {
401 GenotypeComboMap::iterator gc = comboMap.find(*sampleName);
402 //cerr << "alternate count for " << altbase << " and " << *genotype << " is " << genotype->alleleCount(altbase) << endl;
403 if (gc != comboMap.end()) {
404 Genotype* genotype = gc->second->genotype;
405
406 Sample& sample = *gc->second->sample;
407 //refAlleleObservations += sample.observationCount(refbase);
408 refAlleleObservations += sample.observationCount(refbase);
409
410 ++samplesWithData;
411 }
412 }
413
414 var.info["NS"].push_back(convert(samplesWithData));
415 var.info["DP"].push_back(convert(coverage));
416 var.info["RO"].push_back(convert(refAlleleObservations));
417 var.info["PRO"].push_back(convert(samples.partialObservationCount(refbase)));
418 var.info["QR"].push_back(convert(samples.qualSum(refbase)));
419 var.info["PQR"].push_back(convert(samples.partialQualSum(refbase)));
420
421 // tally partial observations to get a mean coverage per bp of reference
422 int haplotypeLength = refbase.size();
423 int basesInObservations = 0;
424
425 for (map<string, vector<Allele*> >::iterator g = alleleGroups.begin(); g != alleleGroups.end(); ++g) {
426 for (vector<Allele*>::iterator a = g->second.begin(); a != g->second.end(); ++a) {
427 basesInObservations += (*a)->alternateSequence.size();
428 }
429 }
430
431 for (map<Allele*, set<Allele*> >::iterator p = partialObservationSupport.begin(); p != partialObservationSupport.end(); ++p) {
432 basesInObservations += p->first->alternateSequence.size();
433 }
434
435 double depthPerBase = (double) basesInObservations / (double) haplotypeLength;
436 var.info["DPB"].push_back(convert(depthPerBase));
437
438 // number of alternate alleles
439 var.info["NUMALT"].push_back(convert(altAlleles.size()));
440
441 if (parameters.showReferenceRepeats && !repeats.empty()) {
442 stringstream repeatsstr;
443 for (map<string, int>::iterator c = repeats.begin(); c != repeats.end(); ++c) {
444 repeatsstr << c->first << ":" << c->second << "|";
445 }
446 string repeatstr = repeatsstr.str();
447 TRY { repeatstr = repeatstr.substr(0, repeatstr.size() - 1); } CATCH;
448 var.info["REPEAT"].clear();
449 var.info["REPEAT"].push_back(repeatstr);
450 }
451
452 var.info["ODDS"].push_back(convert(bestComboOddsRatio));
453
454 // samples
455
456 bool outputExplicitGenotypeLikelihoods = false;
457 bool outputAnyGenotypeLikelihoods = true;
458
459 // for ordering GLs
460 // ordering is F(j/k) = (k*(k+1)/2)+j.
461 map<int, map<string, int> > vcfGenotypeOrder;
462 for (map<int, vector<Genotype> >::iterator gtg = genotypesByPloidy.begin(); gtg != genotypesByPloidy.end(); ++gtg) {
463
464 int groupPloidy = gtg->first;
465 vector<Genotype>& genotypes = gtg->second;
466 for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) {
467 Genotype* genotypePtr = &*g;
468 Genotype& genotype = *g;
469 string genotypeStr = genotype.str();
470 // only provide output for genotypes for which we have data
471 bool fullySpecified = true;
472 vector<int> gtspec;
473 genotype.relativeGenotype(gtspec, refbase, altAlleles);
474 // null allele case handled by the fact that we don't have any null alternate alleles
475 for (vector<int>::iterator n = gtspec.begin(); n != gtspec.end(); ++n) {
476 if (*n < 0) {
477 fullySpecified = false;
478 break;
479 }
480 }
481 if (fullySpecified) {
482 if (groupPloidy == 2) {
483 int j = gtspec.front();
484 int k = gtspec.back();
485 vcfGenotypeOrder[groupPloidy][genotypeStr] = (k * (k + 1) / 2) + j;
486 } else if (groupPloidy == 1) {
487 vcfGenotypeOrder[groupPloidy][genotypeStr] = gtspec.front();
488 } else {
489 outputAnyGenotypeLikelihoods = false; // XXX prevents output of GLs for polyploid data
490 outputExplicitGenotypeLikelihoods = true;
491 }
492 }
493 }
494 }
495
496 // get the best genotypes from the combos, and set the output GTs and GQs using them
497 for (vector<string>::iterator sn = sampleNames.begin(); sn != sampleNames.end(); ++sn) {
498 string& sampleName = *sn;
499 GenotypeComboMap::iterator gc = comboMap.find(sampleName);
500 Results::iterator s = find(sampleName);
501 map<string, vector<string> >& sampleOutput = var.samples[sampleName];
502 if (gc != comboMap.end() && s != end()) {
503
504 Sample& sample = *gc->second->sample;
505 Result& sampleLikelihoods = s->second;
506 Genotype* genotype = gc->second->genotype;
507 if (sample.observationCount() == 0) {
508 continue;
509 }
510
511 sampleOutput["GT"].push_back(genotype->relativeGenotype(refbase, altAlleles));
512
513 if (parameters.calculateMarginals) {
514 double val = nan2zero(big2phred((BigFloat)1 - big_exp(sampleLikelihoods.front().marginal)));
515 if (parameters.strictVCF)
516 sampleOutput["GQ"].push_back(convert(int(round(val))));
517 else
518 sampleOutput["GQ"].push_back(convert(val));
519 }
520
521 sampleOutput["DP"].push_back(convert(sample.observationCount()));
522 sampleOutput["AD"].push_back(convert(sample.observationCount(refbase)));
523 sampleOutput["RO"].push_back(convert(sample.observationCount(refbase)));
524 sampleOutput["QR"].push_back(convert(sample.qualSum(refbase)));
525
526 for (vector<Allele>::iterator aa = altAlleles.begin(); aa != altAlleles.end(); ++aa) {
527 Allele& altAllele = *aa;
528 string altbase = altAllele.base();
529 sampleOutput["AO"].push_back(convert(sample.observationCount(altbase)));
530 sampleOutput["AD"].push_back(convert(sample.observationCount(altbase)));
531 sampleOutput["QA"].push_back(convert(sample.qualSum(altbase)));
532 }
533
534 if (outputAnyGenotypeLikelihoods && !parameters.excludeUnobservedGenotypes && !parameters.excludePartiallyObservedGenotypes) {
535
536 // get data likelihoods for present genotypes, none if we have excluded genotypes from data likelihood calculations
537 if (outputExplicitGenotypeLikelihoods) {
538
539 if (var.format.back() != "GLE") {
540 var.format.push_back("GLE");
541 }
542
543 map<string, string> genotypeLikelihoodsExplicit;
544
545 for (Result::iterator g = sampleLikelihoods.begin(); g != sampleLikelihoods.end(); ++g) {
546 if (g->genotype->hasNullAllele()) {
547 // if the genotype has null (unspecified) alleles, find
548 // the fully specified genotypes it can match with.
549 vector<Genotype*> nullmatchgts = g->genotype->nullMatchingGenotypes(genotypesByPloidy[g->genotype->ploidy]);
550 // the gls for these will be the same, so the gl for
551 // this genotype can be used for all of them. these
552 // are the genotypes which the sample does not have,
553 // but for which one allele or no alleles match
554 for (vector<Genotype*>::iterator n = nullmatchgts.begin(); n != nullmatchgts.end(); ++n) {
555 genotypeLikelihoodsExplicit[(*n)->relativeGenotype(refbase, altAlleles)] = convert(ln2log10(g->prob));
556 }
557 } else {
558 // otherwise, we are well-specified, and only one
559 // genotype should match
560 genotypeLikelihoodsExplicit[g->genotype->relativeGenotype(refbase, altAlleles)] = convert(ln2log10(g->prob));
561 }
562 }
563
564 vector<string> datalikelihoods;
565 for (map<string, string>::iterator gle = genotypeLikelihoodsExplicit.begin(); gle != genotypeLikelihoodsExplicit.end(); ++gle) {
566 datalikelihoods.push_back(gle->first + "^" + gle->second);
567 }
568 sampleOutput["GLE"].push_back(join(datalikelihoods, "|"));
569
570 } else {
571
572 if (var.format.back() != "GL") {
573 var.format.push_back("GL");
574 }
575
576 map<int, double> genotypeLikelihoods;
577 map<int, string> genotypeLikelihoodsOutput;
578
579 for (Result::iterator g = sampleLikelihoods.begin(); g != sampleLikelihoods.end(); ++g) {
580 if (g->genotype->hasNullAllele()) {
581 // if the genotype has null (unspecified) alleles, find
582 // the fully specified genotypes it can match with.
583 vector<Genotype*> nullmatchgts = g->genotype->nullMatchingGenotypes(genotypesByPloidy[g->genotype->ploidy]);
584 // the gls for these will be the same, so the gl for
585 // this genotype can be used for all of them. these
586 // are the genotypes which the sample does not have,
587 // but for which one allele or no alleles match
588 for (vector<Genotype*>::iterator n = nullmatchgts.begin(); n != nullmatchgts.end(); ++n) {
589 map<string, int>::iterator o = vcfGenotypeOrder[(*n)->ploidy].find((*n)->str());
590 if (o != vcfGenotypeOrder[(*n)->ploidy].end()) {
591 genotypeLikelihoods[o->second] = ln2log10(g->prob);
592 }
593 }
594 } else {
595 // otherwise, we are well-specified, and only one
596 // genotype should match
597 map<string, int>::iterator o = vcfGenotypeOrder[g->genotype->ploidy].find(g->genotype->str());
598 if (o != vcfGenotypeOrder[g->genotype->ploidy].end()) {
599 genotypeLikelihoods[o->second] = ln2log10(g->prob);
600 }
601 }
602 }
603
604 // normalize GLs to 0 max using division by max
605 long double minGL = 0;
606 for (map<int, double>::iterator g = genotypeLikelihoods.begin(); g != genotypeLikelihoods.end(); ++g) {
607 if (g->second < minGL) minGL = g->second;
608 }
609 long double maxGL = minGL;
610 for (map<int, double>::iterator g = genotypeLikelihoods.begin(); g != genotypeLikelihoods.end(); ++g) {
611 if (g->second > maxGL) maxGL = g->second;
612 }
613
614 if (parameters.limitGL == 0) {
615 for (map<int, double>::iterator g = genotypeLikelihoods.begin(); g != genotypeLikelihoods.end(); ++g) {
616 genotypeLikelihoodsOutput[g->first] = convert(g->second-maxGL);
617 }
618 } else {
619 for (map<int, double>::iterator g = genotypeLikelihoods.begin(); g != genotypeLikelihoods.end(); ++g) {
620 genotypeLikelihoodsOutput[g->first] = convert( max((long double) + parameters.limitGL, (g->second-maxGL)) );
621 }
622 }
623
624 vector<string>& datalikelihoods = sampleOutput["GL"];
625 // output is sorted by map
626 for (map<int, string>::iterator gl = genotypeLikelihoodsOutput.begin(); gl != genotypeLikelihoodsOutput.end(); ++gl) {
627 datalikelihoods.push_back(gl->second);
628 }
629
630 }
631 }
632 }
633 }
634
635 return var;
636
637 }
638
639
640 vcflib::Variant& Results::gvcf(
641 vcflib::Variant& var,
642 NonCalls& nonCalls,
643 AlleleParser* parser) {
644
645 // what is the first position in the nonCalls?
646 pair<string, long> start = nonCalls.firstPos();
647 const string& startChrom = start.first;
648 long startPos = start.second;
649 // startPos and endPos are zero-based, half-open -- [startPos,endPos)
650
651 // what is the current position? nb: can't be on a different chrom
652 long endPos;
653 if (startChrom != parser->currentSequenceName) {
654 endPos = parser->reference.sequenceLength(startChrom);
655 } else {
656 endPos = parser->currentPosition;
657 }
658 long numSites = endPos - startPos;
659 if(numSites <= 0){
660 std::cerr << "Hit end of chr, but still attempted to call location !!! \n Breaking\n";
661 exit(1);
662 };
663
664 // set up site call
665 var.ref = parser->referenceSubstr(startPos, 1);
666 var.alt.push_back("<*>");
667 var.sequenceName = parser->currentSequenceName;
668 var.position = startPos + 1; // output text field is one-based
669 var.id = ".";
670 var.filter = ".";
671 // TODO change to actual quality
672 var.quality = 0;
673 // set up format string
674 var.format.clear();
675 var.format.push_back("GQ");
676 var.format.push_back("DP");
677 var.format.push_back("MIN_DP");
678 var.format.push_back("QR");
679 var.format.push_back("RO");
680 var.format.push_back("QA");
681 var.format.push_back("AO");
682
683 NonCall total = nonCalls.aggregateAll();
684
685 /* This resets min depth to zero if nonCalls is less than numSites. */
686
687 int minDepth = (numSites != total.nCount) ? 0 : total.minDepth;
688
689 var.info["DP"].push_back(convert((total.refCount+total.altCount) / numSites));
690 var.info["MIN_DP"].push_back(convert(minDepth));
691 // The text END field is one-based, inclusive. We proudly conflate this
692 // with our zero-based, exclusive endPos.
693 var.info["END"].push_back(convert(endPos));
694
695 // genotype quality is 1- p(polymorphic)
696
697 map<string, NonCall> perSample;
698 nonCalls.aggregatePerSample(perSample);
699
700 // iterate through the samples and aggregate information about them
701 for (vector<string>::const_iterator s = parser->sampleList.begin();
702 s != parser->sampleList.end(); ++s) {
703 const string& sampleName = *s;
704 const NonCall& nc = perSample[sampleName];
705 map<string, vector<string> >& sampleOutput = var.samples[sampleName];
706 long double qual = nc.reflnQ - nc.altlnQ;
707 sampleOutput["GQ"].push_back(convert(ln2phred(qual)));
708
709
710 /* This resets min depth to zero if nonCalls is less than numSites. */
711
712 int minDepth = (numSites != nc.nCount) ? 0 : nc.minDepth;
713
714
715 sampleOutput["DP"].push_back(convert((nc.refCount+nc.altCount) / numSites));
716 sampleOutput["MIN_DP"].push_back(convert(minDepth));
717 sampleOutput["QR"].push_back(convert(llrintl(ln2phred(nc.reflnQ))));
718 sampleOutput["RO"].push_back(convert((nc.refCount/numSites)));
719 sampleOutput["QA"].push_back(convert(llrintl(ln2phred(nc.altlnQ))));
720 sampleOutput["AO"].push_back(convert((nc.altCount/numSites)));
721 }
722
723 return var;
724 }