int main(void) { // #ifdef T_addBigInt string num1("123"); string num2("4567"); string sum = addBigInt(num1, num2); if (sum == "") { cerr << "error in addBigInt" << endl; return -1; } cout << num1 << " + " << num2 << " = " << sum << endl; #endif #ifdef T_mulOneBit BigFloat bigNum; cout << "enter a big float: "; cin >> bigNum; cout << "digits = " << bigNum.digits << endl; cout << "exp = " << bigNum.exp << endl; string resu(bigNum.mulOneBit('0')); if ("" == resu) { cerr << "mulOneBit error" << endl; return -1; } cout << "result is " << resu << endl; #endif #ifdef T_opMul BigFloat num1(100); BigFloat num2; cout << "Enter a number : "; cin >> num2; BigFloat prdt = num1 * num2; cout << "result is : \n" << prdt << endl; #endif return 0; }
int BigFloat::ucmp(const BigFloat &x) const{ // Compare function that ignores the sign. // This is needed to determine which direction subtractions will go. // Magnitude int64_t magA = exp + L; int64_t magB = x.exp + x.L; if (magA > magB) return 1; if (magA < magB) return -1; // Compare int64_t mag = magA; while (mag >= exp || mag >= x.exp){ uint32_t wordA = word_at(mag); uint32_t wordB = x.word_at(mag); if (wordA < wordB) return -1; if (wordA > wordB) return 1; mag--; } return 0; }
BigFloat BigFloat::usub(const BigFloat &x,size_t p) const{ // Perform subtraction ignoring the sign of the two operands. // "this" must be greater than or equal to x. Otherwise, the behavior // is undefined. // Magnitude int64_t magA = exp + L; int64_t magB = x.exp + x.L; int64_t top = std::max(magA,magB); int64_t bot = std::min(exp,x.exp); // Truncate precision int64_t TL = top - bot; if (p == 0){ // Default value. No trunction. p = (size_t)TL; }else{ // Increase precision p += YCL_BIGFLOAT_EXTRA_PRECISION; } if (TL > (int64_t)p){ bot = top - p; TL = p; } // Compute basic fields. BigFloat z; z.sign = sign; z.exp = bot; z.L = (uint32_t)TL; // Allocate mantissa z.T = std::unique_ptr<uint32_t[]>(new uint32_t[z.L]); // Subtract int32_t carry = 0; for (size_t c = 0; bot < top; bot++, c++){ int32_t word = (int32_t)word_at(bot) - (int32_t)x.word_at(bot) - carry; carry = 0; if (word < 0){ word += 1000000000; carry = 1; } z.T[c] = word; } // Strip leading zeros while (z.L > 0 && z.T[z.L - 1] == 0) z.L--; if (z.L == 0){ z.exp = 0; z.sign = true; z.T.reset(); } return z; }
inline BigFloat Epsilon<BigFloat>( const BigFloat& alpha ) { // NOTE: This 'precision' is the number of bits in the mantissa auto p = alpha.Precision(); // epsilon = b^{-(p-1)} / 2 = 2^{-p} BigFloat one(1,p); return one >> p; }
inline BigFloat SafeMin( const BigFloat& alpha ) { // TODO: Decide how to only recompute this when the precision changes const BigFloat one = BigFloat(1,alpha.Precision()); const BigFloat eps = Epsilon(alpha); const BigFloat minVal = Min(alpha); const BigFloat invMax = one/Max(alpha); return ( invMax>minVal ? invMax*(one+eps) : minVal ); }
BigFloat invsqrt(uint32_t x,size_t p,int tds){ // Compute inverse square root using Newton's Method. // ( r0^2 * x - 1 ) // r1 = r0 - (----------------) * r0 // ( 2 ) if (x == 0) throw "Divide by Zero"; // End of recursion. Generate starting point. if (p == 0){ double val = 1. / sqrt((double)x); int64_t exponent = 0; // Scale while (val < 1000000000.){ val *= 1000000000.; exponent--; } // Rebuild a BigFloat. uint64_t val64 = (uint64_t)val; BigFloat out; out.sign = true; out.T = std::unique_ptr<uint32_t[]>(new uint32_t[2]); out.T[0] = (uint32_t)(val64 % 1000000000); out.T[1] = (uint32_t)(val64 / 1000000000); out.L = 2; out.exp = exponent; return out; } // Half the precision size_t s = p / 2 + 1; if (p == 1) s = 0; if (p == 2) s = 1; // Recurse at half the precision BigFloat T = invsqrt(x,s,tds); BigFloat temp = T.mul(T,p); // r0^2 temp = temp.mul(x,p,tds); // r0^2 * x temp = temp.sub(BigFloat(1),p); // r0^2 * x - 1 temp = temp.mul(500000000); // (r0^2 * x - 1) / 2 temp.exp--; temp = temp.mul(T,p,tds); // (r0^2 * x - 1) / 2 * r0 return T.sub(temp,p); // r0 - (r0^2 * x - 1) / 2 * r0 }
BigFloat BigFloat::sub(const BigFloat &x,size_t p) const{ // Subtraction // The target precision is p. // If (p = 0), then no truncation is done. The entire operation is done // at maximum precision with no data loss. // Different sign. Add. if (sign != x.sign) return uadd(x,p); // this > x if (ucmp(x) > 0) return usub(x,p); // this < x BigFloat z = x.usub(*this,p); z.negate(); return z; }
int main() { BigFloat *sum; sum = new BigFloat(0.0); for ( int i = 1; i <= 100 ; i ++) { BigFloat index(1.0); BigFloat temp((double)i); if ( 0 == index.divide(&index, &temp)) sum->add(sum,&index); else { printf("error"); exit(1); } } sum->printAll(); sum->print_fraction_portion_in_decimal(1000,NULL); }
BigFloat BigFloat::uadd(const BigFloat &x,size_t p) const{ // Perform addition ignoring the sign of the two operands. // Magnitude int64_t magA = exp + L; int64_t magB = x.exp + x.L; int64_t top = std::max(magA,magB); int64_t bot = std::min(exp,x.exp); // Target length int64_t TL = top - bot; if (p == 0){ // Default value. No trunction. p = (size_t)TL; }else{ // Increase precision p += YCL_BIGFLOAT_EXTRA_PRECISION; } // Perform precision truncation. if (TL > (int64_t)p){ bot = top - p; TL = p; } // Compute basic fields. BigFloat z; z.sign = sign; z.exp = bot; z.L = (uint32_t)TL; // Allocate mantissa z.T = std::unique_ptr<uint32_t[]>(new uint32_t[z.L + 1]); // Add uint32_t carry = 0; for (size_t c = 0; bot < top; bot++, c++){ uint32_t word = word_at(bot) + x.word_at(bot) + carry; carry = 0; if (word >= 1000000000){ word -= 1000000000; carry = 1; } z.T[c] = word; } // Carry out if (carry != 0){ z.T[z.L++] = 1; } return z; }
//////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Pi void Pi_BSR(BigFloat &P,BigFloat &Q,BigFloat &R,uint32_t a,uint32_t b,size_t p){ // Binary Splitting recursion for the Chudnovsky Formula. if (b - a == 1){ // P = (13591409 + 545140134 b)(2b-1)(6b-5)(6b-1) (-1)^b P = BigFloat(b).mul(545140134); P = P.add(BigFloat(13591409)); P = P.mul(2*b - 1); P = P.mul(6*b - 5); P = P.mul(6*b - 1); if (b % 2 == 1) P.negate(); // Q = 10939058860032000 * b^3 Q = BigFloat(b); Q = Q.mul(Q).mul(Q).mul(26726400).mul(409297880); // R = (2b-1)(6b-5)(6b-1) R = BigFloat(2*b - 1); R = R.mul(6*b - 5); R = R.mul(6*b - 1); return; } uint32_t m = (a + b) / 2; BigFloat P0,Q0,R0,P1,Q1,R1; Pi_BSR(P0,Q0,R0,a,m,p); Pi_BSR(P1,Q1,R1,m,b,p); P = P0.mul(Q1,p).add(P1.mul(R0,p),p); Q = Q0.mul(Q1,p); R = R0.mul(R1,p); }
bool GaussElimination::changeValuesInRowByBigFloat(vector<vector<BigFloat>>& matrix, int indexRow) { if( matrix[indexRow][indexRow].compare( &BigFloat(0.0) ) != 0 ) return true; // wenn i.zeile zahl in spalte i = 0, tausche mit zeile darunter!!, wo zahl in i.spalte != 0 -> falls nicht da, gs nicht lösbar for(unsigned int rowCounter = indexRow+1; rowCounter < row; ++rowCounter) { BigFloat value = matrix[rowCounter][indexRow]; if(value.compare( &BigFloat(0.0) ) != 0 ) { // tausche reihen for(unsigned int i = 0; i <= col; ++i) //zusätzliche spalte angefügt durch vector { BigFloat currowValue = matrix[indexRow][i]; BigFloat changeValue = matrix[rowCounter][i]; matrix[indexRow][i] = changeValue; matrix[rowCounter][i] = currowValue; } return true; } } return false; }
// Zoom vers la cible du clic static void clicGauche(SDL_Event& event, Affichage* disp) { // Calcul de la position du clic dans le plan complexe float x = disp->center.x + disp->scale*(((float)event.motion.x) / WIDTH - 0.5f); float y = disp->center.y + disp->scale*(((float)event.motion.y) / HEIGHT - 0.5f); // MAJ de la position du nouveau centre dans le plan complexe if (INTERACTIVE) { disp->center.x = x + (disp->center.x - x) * ZOOM_FACTOR; disp->center.y = y + (disp->center.y - y) * ZOOM_FACTOR; updateBigCenter(event, true); } // MAJ de l'echelle disp->scale *= ZOOM_FACTOR; //BigFloat zoomFactor(true, 0, 0x80000000, 0, 0); BigFloat temp, temp2; BigFloat::mult(ZOOM_FACTOR, *bigScale, temp); bigScale->reset(); temp2.copy(*bigScale); BigFloat::add(temp, temp2, *bigScale); //Nouveau calcul de la fractale avec chrono disp->start = chrono::system_clock::now(); if (GPU && BIG_FLOAT_SIZE == 0) affichageGPU(disp); else if (GPU) computeBigMandelGPU(disp, xCenter->pos, xCenter->decimals, yCenter->pos, yCenter->decimals, bigScale->decimals); else if (BIG_FLOAT_SIZE == 0) computeMandel(disp->pixels, disp->center, disp->scale); else { computeBigMandel(disp->pixels, *xCenter, *yCenter, *bigScale); } disp->end = chrono::system_clock::now(); disp->duration = disp->end - disp->start; cout << "Frame computing time : " << disp->duration.count() << endl; //cout << "Frame computing scale : " << disp->scale << endl; // Affichage de la fractale disp->dessin(); }
//////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Pi void Pi_BSR(BigFloat &P,BigFloat &Q,BigFloat &R,uint32_t a,uint32_t b,size_t p,int tds = 1){ // Binary Splitting recursion for the Chudnovsky Formula. if (b - a == 1){ // P = (13591409 + 545140134 b)(2b-1)(6b-5)(6b-1) (-1)^b P = BigFloat(b).mul(545140134); P = P.add(BigFloat(13591409)); P = P.mul(2*b - 1); P = P.mul(6*b - 5); P = P.mul(6*b - 1); if (b % 2 == 1) P.negate(); // Q = 10939058860032000 * b^3 Q = BigFloat(b); Q = Q.mul(Q).mul(Q).mul(26726400).mul(409297880); // R = (2b-1)(6b-5)(6b-1) R = BigFloat(2*b - 1); R = R.mul(6*b - 5); R = R.mul(6*b - 1); return; } uint32_t m = (a + b) / 2; BigFloat P0,Q0,R0,P1,Q1,R1; if (b - a < 1000 || tds < 2){ // No more threads. Pi_BSR(P0,Q0,R0,a,m,p); Pi_BSR(P1,Q1,R1,m,b,p); }else{ // Run sub-recursions in parallel. int tds0 = tds / 2; int tds1 = tds - tds0; #pragma omp parallel num_threads(2) { int tid = omp_get_thread_num(); if (tid == 0){ Pi_BSR(P0,Q0,R0,a,m,p,tds0); } if (tid != 0 || omp_get_num_threads() < 2){ Pi_BSR(P1,Q1,R1,m,b,p,tds1); } } } P = P0.mul(Q1,p,tds).add(P1.mul(R0,p,tds),p); Q = Q0.mul(Q1,p,tds); R = R0.mul(R1,p,tds); }
BigFloat BigFloat::add(const BigFloat &x,size_t p) const{ // Addition // The target precision is p. // If (p = 0), then no truncation is done. The entire operation is done // at maximum precision with no data loss. // Same sign. Add. if (sign == x.sign) return uadd(x,p); // this > x if (ucmp(x) > 0) return usub(x,p); // this < x return x.usub(*this,p); }
void ComputeFloatSession<wtype>::write_digits(const BigFloat<wtype>& x, const std::string& name, const std::string& algorithm){ std::string dec_name, hex_name; if (algorithm.empty()){ dec_name = name + " - Dec.txt"; hex_name = name + " - Hex.txt"; }else{ dec_name = name + " - Dec - " + algorithm + ".txt"; hex_name = name + " - Hex - " + algorithm + ".txt"; } // Special Case: If the number is close to one, don't count the digits in // front of the decimal place. This keeps the behavior consistent with // y-cruncher and other Pi programs that start counting digits after the // decimal place. upL_t dec_digits = m_dec; upL_t hex_digits = m_hex; if (x.get_mag() == 1){ wtype top_word = x[0]; dec_digits += std::to_string(top_word).size(); while (top_word != 0){ top_word >>= 4; hex_digits++; } }
BigFloat BigFloat::rcp(size_t p,int tds) const{ // Compute reciprocal using Newton's Method. // r1 = r0 - (r0 * x - 1) * r0 if (L == 0) throw "Divide by Zero"; // Collect operand int64_t Aexp = exp; size_t AL = L; uint32_t *AT = T.get(); // End of recursion. Generate starting point. if (p == 0){ // Truncate precision to 3. p = 3; if (AL > p){ size_t chop = AL - p; AL = p; Aexp += chop; AT += chop; } // Convert number to floating-point. double val = AT[0]; if (AL >= 2) val += AT[1] * 1000000000.; if (AL >= 3) val += AT[2] * 1000000000000000000.; // Compute reciprocal. val = 1. / val; Aexp = -Aexp; // Scale while (val < 1000000000.){ val *= 1000000000.; Aexp--; } // Rebuild a BigFloat. uint64_t val64 = (uint64_t)val; BigFloat out; out.sign = sign; out.T = std::unique_ptr<uint32_t[]>(new uint32_t[2]); out.T[0] = (uint32_t)(val64 % 1000000000); out.T[1] = (uint32_t)(val64 / 1000000000); out.L = 2; out.exp = Aexp; return out; } // Half the precision size_t s = p / 2 + 1; if (p == 1) s = 0; if (p == 2) s = 1; // Recurse at half the precision BigFloat T = rcp(s,tds); // r1 = r0 - (r0 * x - 1) * r0 return T.sub(this->mul(T,p,tds).sub(BigFloat(1),p).mul(T,p,tds),p); }
inline Int NumMantissaBits<BigFloat>( const BigFloat& alpha ) { return alpha.Precision(); }
inline bool IsFinite( const BigFloat& alpha ) { return mpfr_number_p( alpha.LockedPointer() ) != 0; }
inline BigFloat Infinity<BigFloat>( const BigFloat& alpha ) { BigFloat inf(0,alpha.Precision()); mpfr_set_inf( inf.Pointer(), 1 ); return inf; }
// freebayes main int main (int argc, char *argv[]) { // install segfault handler signal(SIGSEGV, segfaultHandler); AlleleParser* parser = new AlleleParser(argc, argv); Parameters& parameters = parser->parameters; list<Allele*> alleles; Samples samples; ostream& out = *(parser->output); Bias observationBias; if (!parameters.alleleObservationBiasFile.empty()) { observationBias.open(parameters.alleleObservationBiasFile); } Contamination contaminationEstimates(0.5+parameters.probContamination, parameters.probContamination); if (!parameters.contaminationEstimateFile.empty()) { contaminationEstimates.open(parameters.contaminationEstimateFile); } // this can be uncommented to force operation on a specific set of genotypes vector<Allele> allGenotypeAlleles; allGenotypeAlleles.push_back(genotypeAllele(ALLELE_GENOTYPE, "A", 1)); allGenotypeAlleles.push_back(genotypeAllele(ALLELE_GENOTYPE, "T", 1)); allGenotypeAlleles.push_back(genotypeAllele(ALLELE_GENOTYPE, "G", 1)); allGenotypeAlleles.push_back(genotypeAllele(ALLELE_GENOTYPE, "C", 1)); int allowedAlleleTypes = ALLELE_REFERENCE; if (parameters.allowSNPs) { allowedAlleleTypes |= ALLELE_SNP; } if (parameters.allowIndels) { allowedAlleleTypes |= ALLELE_INSERTION; allowedAlleleTypes |= ALLELE_DELETION; } if (parameters.allowMNPs) { allowedAlleleTypes |= ALLELE_MNP; } if (parameters.allowComplex) { allowedAlleleTypes |= ALLELE_COMPLEX; } // output VCF header if (parameters.output == "vcf") { out << parser->variantCallFile.header << endl; } Allele nullAllele = genotypeAllele(ALLELE_NULL, "N", 1, "1N"); unsigned long total_sites = 0; unsigned long processed_sites = 0; while (parser->getNextAlleles(samples, allowedAlleleTypes)) { ++total_sites; DEBUG2("at start of main loop"); // don't process non-ATGC's in the reference string cb = parser->currentReferenceBaseString(); if (cb != "A" && cb != "T" && cb != "C" && cb != "G") { DEBUG2("current reference base is N"); continue; } if (parameters.trace) { for (Samples::iterator s = samples.begin(); s != samples.end(); ++s) { const string& name = s->first; for (Sample::iterator g = s->second.begin(); g != s->second.end(); ++g) { vector<Allele*>& group = g->second; for (vector<Allele*>::iterator a = group.begin(); a != group.end(); ++a) { Allele& allele = **a; parser->traceFile << parser->currentSequenceName << "," << (long unsigned int) parser->currentPosition + 1 << ",allele," << name << "," << allele.readID << "," << allele.base() << "," << allele.currentQuality() << "," << allele.mapQuality << endl; } } } DEBUG2("after trace generation"); } if (!parser->inTarget()) { DEBUG("position: " << parser->currentSequenceName << ":" << (long unsigned int) parser->currentPosition + 1 << " is not inside any targets, skipping"); continue; } int coverage = countAlleles(samples); DEBUG("position: " << parser->currentSequenceName << ":" << (long unsigned int) parser->currentPosition + 1 << " coverage: " << coverage); if (!parser->hasInputVariantAllelesAtCurrentPosition()) { // skips 0-coverage regions if (coverage == 0) { DEBUG("no alleles left at this site after filtering"); continue; } else if (coverage < parameters.minCoverage) { DEBUG("post-filtering coverage of " << coverage << " is less than --min-coverage of " << parameters.minCoverage); continue; } else if (parameters.onlyUseInputAlleles) { DEBUG("no input alleles, but using only input alleles for analysis, skipping position"); continue; } DEBUG2("coverage " << parser->currentSequenceName << ":" << parser->currentPosition << " == " << coverage); // establish a set of possible alternate alleles to evaluate at this location if (!parameters.reportMonomorphic && !sufficientAlternateObservations(samples, parameters.minAltCount, parameters.minAltFraction)) { DEBUG("insufficient alternate observations"); continue; } if (parameters.reportMonomorphic) { DEBUG("calling at site even though there are no alternate observations"); } } else { /* cerr << "has input variants at " << parser->currentSequenceName << ":" << parser->currentPosition << endl; vector<Allele>& inputs = parser->inputVariantAlleles[parser->currentPosition]; for (vector<Allele>::iterator a = inputs.begin(); a != inputs.end(); ++a) { cerr << *a << endl; } */ } // to ensure proper ordering of output stream vector<string> sampleListPlusRef; for (vector<string>::iterator s = parser->sampleList.begin(); s != parser->sampleList.end(); ++s) { sampleListPlusRef.push_back(*s); } if (parameters.useRefAllele) { sampleListPlusRef.push_back(parser->currentSequenceName); } // establish genotype alleles using input filters map<string, vector<Allele*> > alleleGroups; groupAlleles(samples, alleleGroups); DEBUG2("grouped alleles by equivalence"); vector<Allele> genotypeAlleles = parser->genotypeAlleles(alleleGroups, samples, parameters.onlyUseInputAlleles); // always include the reference allele as a possible genotype, even when we don't include it by default if (!parameters.useRefAllele) { vector<Allele> refAlleleVector; refAlleleVector.push_back(genotypeAllele(ALLELE_REFERENCE, string(1, parser->currentReferenceBase), 1, "1M")); genotypeAlleles = alleleUnion(genotypeAlleles, refAlleleVector); } map<string, vector<Allele*> > partialObservationGroups; map<Allele*, set<Allele*> > partialObservationSupport; // build haplotype alleles matching the current longest allele (often will do nothing) // this will adjust genotypeAlleles if changes are made DEBUG("building haplotype alleles, currently there are " << genotypeAlleles.size() << " genotype alleles"); DEBUG(genotypeAlleles); parser->buildHaplotypeAlleles(genotypeAlleles, samples, alleleGroups, partialObservationGroups, partialObservationSupport, allowedAlleleTypes); DEBUG("built haplotype alleles, now there are " << genotypeAlleles.size() << " genotype alleles"); DEBUG(genotypeAlleles); string referenceBase = parser->currentReferenceHaplotype(); /* for debugging for (Samples::iterator s = samples.begin(); s != samples.end(); ++s) { string sampleName = s->first; Sample& sample = s->second; cerr << sampleName << ": " << sample << endl; } */ // re-calculate coverage, as this could change now that we've built haplotype alleles coverage = countAlleles(samples); // estimate theta using the haplotype length long double theta = parameters.TH * parser->lastHaplotypeLength; // if we have only one viable allele, we don't have evidence for variation at this site if (!parser->hasInputVariantAllelesAtCurrentPosition() && !parameters.reportMonomorphic && genotypeAlleles.size() <= 1 && genotypeAlleles.front().isReference()) { DEBUG("no alternate genotype alleles passed filters at " << parser->currentSequenceName << ":" << parser->currentPosition); continue; } DEBUG("genotype alleles: " << genotypeAlleles); // add the null genotype bool usingNull = false; if (parameters.excludeUnobservedGenotypes && genotypeAlleles.size() > 2) { genotypeAlleles.push_back(nullAllele); usingNull = true; } ++processed_sites; // generate possible genotypes // for each possible ploidy in the dataset, generate all possible genotypes vector<int> ploidies = parser->currentPloidies(samples); map<int, vector<Genotype> > genotypesByPloidy = getGenotypesByPloidy(ploidies, genotypeAlleles); int numCopiesOfLocus = parser->copiesOfLocus(samples); DEBUG2("generated all possible genotypes:"); if (parameters.debug2) { for (map<int, vector<Genotype> >::iterator s = genotypesByPloidy.begin(); s != genotypesByPloidy.end(); ++s) { vector<Genotype>& genotypes = s->second; for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) { DEBUG2(*g); } } } // get estimated allele frequencies using sum of estimated qualities map<string, double> estimatedAlleleFrequencies = samples.estimatedAlleleFrequencies(); double estimatedMaxAlleleFrequency = 0; double estimatedMaxAlleleCount = 0; double estimatedMajorFrequency = estimatedAlleleFrequencies[referenceBase]; if (estimatedMajorFrequency < 0.5) estimatedMajorFrequency = 1-estimatedMajorFrequency; double estimatedMinorFrequency = 1-estimatedMajorFrequency; //cerr << "num copies of locus " << numCopiesOfLocus << endl; int estimatedMinorAllelesAtLocus = max(1, (int) ceil((double) numCopiesOfLocus * estimatedMinorFrequency)); //cerr << "estimated minor frequency " << estimatedMinorFrequency << endl; //cerr << "estimated minor count " << estimatedMinorAllelesAtLocus << endl; Results results; map<string, vector<vector<SampleDataLikelihood> > > sampleDataLikelihoodsByPopulation; map<string, vector<vector<SampleDataLikelihood> > > variantSampleDataLikelihoodsByPopulation; map<string, vector<vector<SampleDataLikelihood> > > invariantSampleDataLikelihoodsByPopulation; map<string, int> inputAlleleCounts; int inputLikelihoodCount = 0; DEBUG2("calculating data likelihoods"); // calculate data likelihoods //for (Samples::iterator s = samples.begin(); s != samples.end(); ++s) { for (vector<string>::iterator n = parser->sampleList.begin(); n != parser->sampleList.end(); ++n) { //string sampleName = s->first; string& sampleName = *n; //DEBUG2("sample: " << sampleName); //Sample& sample = s->second; if (samples.find(sampleName) == samples.end() && !(parser->hasInputVariantAllelesAtCurrentPosition() || parameters.reportMonomorphic)) { continue; } Sample& sample = samples[sampleName]; vector<Genotype>& genotypes = genotypesByPloidy[parser->currentSamplePloidy(sampleName)]; vector<Genotype*> genotypesWithObs; for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) { if (parameters.excludePartiallyObservedGenotypes) { if (g->sampleHasSupportingObservationsForAllAlleles(sample)) { genotypesWithObs.push_back(&*g); } } else if (parameters.excludeUnobservedGenotypes && usingNull) { if (g->sampleHasSupportingObservations(sample)) { //cerr << sampleName << " has suppporting obs for " << *g << endl; genotypesWithObs.push_back(&*g); } else if (g->hasNullAllele() && g->homozygous) { // this genotype will never be added if we are running in observed-only mode, but // we still need it for consistency genotypesWithObs.push_back(&*g); } } else { genotypesWithObs.push_back(&*g); } } // skip this sample if we have no observations supporting any of the genotypes we are going to evaluate if (genotypesWithObs.empty()) { continue; } vector<pair<Genotype*, long double> > probs = probObservedAllelesGivenGenotypes(sample, genotypesWithObs, parameters.RDF, parameters.useMappingQuality, observationBias, parameters.standardGLs, genotypeAlleles, contaminationEstimates, estimatedAlleleFrequencies); #ifdef VERBOSE_DEBUG if (parameters.debug2) { for (vector<pair<Genotype*, long double> >::iterator p = probs.begin(); p != probs.end(); ++p) { cerr << parser->currentSequenceName << "," << (long unsigned int) parser->currentPosition + 1 << "," << sampleName << ",likelihood," << *(p->first) << "," << p->second << endl; } } #endif Result& sampleData = results[sampleName]; sampleData.name = sampleName; sampleData.observations = &sample; for (vector<pair<Genotype*, long double> >::iterator p = probs.begin(); p != probs.end(); ++p) { sampleData.push_back(SampleDataLikelihood(sampleName, &sample, p->first, p->second, 0)); } sortSampleDataLikelihoods(sampleData); string& population = parser->samplePopulation[sampleName]; vector<vector<SampleDataLikelihood> >& sampleDataLikelihoods = sampleDataLikelihoodsByPopulation[population]; vector<vector<SampleDataLikelihood> >& variantSampleDataLikelihoods = variantSampleDataLikelihoodsByPopulation[population]; vector<vector<SampleDataLikelihood> >& invariantSampleDataLikelihoods = invariantSampleDataLikelihoodsByPopulation[population]; if (parameters.genotypeVariantThreshold != 0) { if (sampleData.size() > 1 && abs(sampleData.at(1).prob - sampleData.front().prob) < parameters.genotypeVariantThreshold) { variantSampleDataLikelihoods.push_back(sampleData); } else { invariantSampleDataLikelihoods.push_back(sampleData); } } else { variantSampleDataLikelihoods.push_back(sampleData); } sampleDataLikelihoods.push_back(sampleData); DEBUG2("obtaining genotype likelihoods input from VCF"); int prevcount = sampleDataLikelihoods.size(); parser->addCurrentGenotypeLikelihoods(genotypesByPloidy, sampleDataLikelihoods); // add these sample data likelihoods to 'invariant' likelihoods inputLikelihoodCount += sampleDataLikelihoods.size() - prevcount; parser->addCurrentGenotypeLikelihoods(genotypesByPloidy, invariantSampleDataLikelihoods); } // if there are not any input GLs, attempt to use the input ACs if (inputLikelihoodCount == 0) { parser->getInputAlleleCounts(genotypeAlleles, inputAlleleCounts); } DEBUG2("finished calculating data likelihoods"); // this section is a hack to make output of trace identical to BamBayes trace // and also outputs the list of samples vector<bool> samplesWithData; if (parameters.trace) { parser->traceFile << parser->currentSequenceName << "," << (long unsigned int) parser->currentPosition + 1 << ",samples,"; for (vector<string>::iterator s = sampleListPlusRef.begin(); s != sampleListPlusRef.end(); ++s) { if (parameters.trace) parser->traceFile << *s << ":"; Results::iterator r = results.find(*s); if (r != results.end()) { samplesWithData.push_back(true); } else { samplesWithData.push_back(false); } } parser->traceFile << endl; } // if somehow we get here without any possible sample genotype likelihoods, bail out bool hasSampleLikelihoods = false; for (map<string, vector<vector<SampleDataLikelihood> > >::iterator s = sampleDataLikelihoodsByPopulation.begin(); s != sampleDataLikelihoodsByPopulation.end(); ++s) { if (!s->second.empty()) { hasSampleLikelihoods = true; break; } } if (!hasSampleLikelihoods) { continue; } DEBUG2("calulating combo posteriors over " << parser->populationSamples.size() << " populations"); // XXX // TODO skip these steps in the case that there is only one population? // we provide p(var|data), or the probability that the location has // variation between individuals relative to the probability that it // has no variation // // in other words: // p(var|d) = 1 - p(AA|d) - p(TT|d) - P(GG|d) - P(CC|d) // // the approach is go through all the homozygous combos // and then subtract this from 1... resolving p(var|d) BigFloat pVar = 1.0; BigFloat pHom = 0.0; long double bestComboOddsRatio = 0; GenotypeCombo bestCombo; // = NULL; // what a hack... /* if (parameters.trace) { for (list<GenotypeCombo>::iterator gc = genotypeCombos.begin(); gc != genotypeCombos.end(); ++gc) { vector<Genotype*> comboGenotypes; for (GenotypeCombo::iterator g = gc->begin(); g != gc->end(); ++g) comboGenotypes.push_back((*g)->genotype); long double posteriorProb = gc->posteriorProb; long double dataLikelihoodln = gc->probObsGivenGenotypes; long double priorln = gc->posteriorProb; long double priorlnG_Af = gc->priorProbG_Af; long double priorlnAf = gc->priorProbAf; long double priorlnBin = gc->priorProbObservations; parser->traceFile << parser->currentSequenceName << "," << (long unsigned int) parser->currentPosition + 1 << ",genotypecombo,"; int j = 0; GenotypeCombo::iterator i = gc->begin(); for (vector<bool>::iterator d = samplesWithData.begin(); d != samplesWithData.end(); ++d) { if (*d) { parser->traceFile << IUPAC(*(*i)->genotype); ++i; } else { parser->traceFile << "?"; } } // TODO cleanup this and above parser->traceFile << "," << dataLikelihoodln << "," << priorln << "," << priorlnG_Af << "," << priorlnAf << "," << priorlnBin << "," << posteriorProb << "," << safe_exp(posteriorProb - posteriorNormalizer) << endl; } } */ // the second clause guards against float underflow causing us not to output a position // practically, parameters.PVL == 0 means "report all genotypes which pass our input filters" GenotypeCombo bestGenotypeComboByMarginals; vector<vector<SampleDataLikelihood> > allSampleDataLikelihoods; DEBUG("searching genotype space"); // resample the posterior, this time without bounds on the // samples we vary, ensuring that we can generate marginals for // all sample/genotype combinations //SampleDataLikelihoods marginalLikelihoods = sampleDataLikelihoods; // heavyweight copy... map<string, list<GenotypeCombo> > genotypeCombosByPopulation; int genotypingTotalIterations = 0; // tally total iterations required to reach convergence map<string, list<GenotypeCombo> > glMaxCombos; for (map<string, SampleDataLikelihoods>::iterator p = sampleDataLikelihoodsByPopulation.begin(); p != sampleDataLikelihoodsByPopulation.end(); ++p) { const string& population = p->first; SampleDataLikelihoods& sampleDataLikelihoods = p->second; list<GenotypeCombo>& populationGenotypeCombos = genotypeCombosByPopulation[population]; DEBUG2("genqerating banded genotype combinations from " << sampleDataLikelihoods.size() << " sample genotypes in population " << population); // cap the number of iterations at 2 x the number of alternate alleles // max it at parameters.genotypingMaxIterations iterations, min at 10 int itermax = min(max(10, 2 * estimatedMinorAllelesAtLocus), parameters.genotypingMaxIterations); //int itermax = parameters.genotypingMaxIterations; // XXX HACK // passing 0 for bandwidth and banddepth means "exhaustive local search" // this produces properly normalized GQ's at polyallelic sites int adjustedBandwidth = 0; int adjustedBanddepth = 0; // however, this can lead to huge performance problems at complex sites, // so we implement this hack... if (parameters.genotypingMaxBandDepth > 0 && genotypeAlleles.size() > parameters.genotypingMaxBandDepth) { adjustedBandwidth = 1; adjustedBanddepth = parameters.genotypingMaxBandDepth; } GenotypeCombo nullCombo; SampleDataLikelihoods nullSampleDataLikelihoods; // this is the genotype-likelihood maximum if (parameters.reportGenotypeLikelihoodMax) { GenotypeCombo comboKing; vector<int> initialPosition; initialPosition.assign(sampleDataLikelihoods.size(), 0); SampleDataLikelihoods nullDataLikelihoods; // dummy variable makeComboByDatalLikelihoodRank(comboKing, initialPosition, sampleDataLikelihoods, nullDataLikelihoods, inputAlleleCounts, theta, parameters.pooledDiscrete, parameters.ewensPriors, parameters.permute, parameters.hwePriors, parameters.obsBinomialPriors, parameters.alleleBalancePriors, parameters.diffusionPriorScalar); glMaxCombos[population].push_back(comboKing); } // search much longer for convergence convergentGenotypeComboSearch( populationGenotypeCombos, nullCombo, sampleDataLikelihoods, // vary everything sampleDataLikelihoods, nullSampleDataLikelihoods, samples, genotypeAlleles, inputAlleleCounts, adjustedBandwidth, adjustedBanddepth, theta, parameters.pooledDiscrete, parameters.ewensPriors, parameters.permute, parameters.hwePriors, parameters.obsBinomialPriors, parameters.alleleBalancePriors, parameters.diffusionPriorScalar, itermax, genotypingTotalIterations, true); // add homozygous combos // ^^ combo results are sorted by default } // generate the GL max combo GenotypeCombo glMax; if (parameters.reportGenotypeLikelihoodMax) { list<GenotypeCombo> glMaxGenotypeCombos; combinePopulationCombos(glMaxGenotypeCombos, glMaxCombos); glMax = glMaxGenotypeCombos.front(); } // accumulate combos from independently-calculated populations into the list of combos list<GenotypeCombo> genotypeCombos; // build new combos into this list combinePopulationCombos(genotypeCombos, genotypeCombosByPopulation); // TODO factor out the following blocks as they are repeated from above // re-get posterior normalizer vector<long double> comboProbs; for (list<GenotypeCombo>::iterator gc = genotypeCombos.begin(); gc != genotypeCombos.end(); ++gc) { comboProbs.push_back(gc->posteriorProb); } long double posteriorNormalizer = logsumexp_probs(comboProbs); // recalculate posterior normalizer pVar = 1.0; pHom = 0.0; // calculates pvar and gets the best het combo for (list<GenotypeCombo>::iterator gc = genotypeCombos.begin(); gc != genotypeCombos.end(); ++gc) { if (gc->isHomozygous() && (parameters.useRefAllele || !parameters.useRefAllele && gc->alleles().front() == referenceBase)) { pVar -= big_exp(gc->posteriorProb - posteriorNormalizer); pHom += big_exp(gc->posteriorProb - posteriorNormalizer); } } // report the maximum a posteriori estimate // unless we're reporting the GL maximum if (!parameters.reportGenotypeLikelihoodMax) { bestCombo = genotypeCombos.front(); } else { bestCombo = glMax; } DEBUG2("best combo: " << bestCombo); // odds ratio between the first and second-best combinations if (genotypeCombos.size() > 1) { bestComboOddsRatio = genotypeCombos.front().posteriorProb - (++genotypeCombos.begin())->posteriorProb; } if (parameters.calculateMarginals) { // make a combined, all-populations sample data likelihoods vector to accumulate marginals SampleDataLikelihoods allSampleDataLikelihoods; for (map<string, SampleDataLikelihoods>::iterator p = sampleDataLikelihoodsByPopulation.begin(); p != sampleDataLikelihoodsByPopulation.end(); ++p) { SampleDataLikelihoods& sdls = p->second; allSampleDataLikelihoods.reserve(allSampleDataLikelihoods.size() + distance(sdls.begin(), sdls.end())); allSampleDataLikelihoods.insert(allSampleDataLikelihoods.end(), sdls.begin(), sdls.end()); } // calculate the marginal likelihoods for this population marginalGenotypeLikelihoods(genotypeCombos, allSampleDataLikelihoods); // store the marginal data likelihoods in the results, for easy parsing // like a vector -> map conversion... results.update(allSampleDataLikelihoods); } map<string, int> repeats; if (parameters.showReferenceRepeats) { repeats = parser->repeatCounts(parser->currentSequencePosition(), parser->currentSequence, 12); } vector<Allele> alts; if (parameters.onlyUseInputAlleles || parameters.reportAllHaplotypeAlleles || parameters.pooledContinuous) { //alts = genotypeAlleles; for (vector<Allele>::iterator a = genotypeAlleles.begin(); a != genotypeAlleles.end(); ++a) { if (!a->isReference()) { alts.push_back(*a); } } } else { // get the unique alternate alleles in this combo, sorted by frequency in the combo vector<pair<Allele, int> > alternates = alternateAlleles(bestCombo, referenceBase); for (vector<pair<Allele, int> >::iterator a = alternates.begin(); a != alternates.end(); ++a) { Allele& alt = a->first; if (!alt.isNull() && !alt.isReference()) alts.push_back(alt); } // if there are no alternate alleles in the best combo, use the genotype alleles // XXX ... if (alts.empty()) { for (vector<Allele>::iterator a = genotypeAlleles.begin(); a != genotypeAlleles.end(); ++a) { if (!a->isReference()) { alts.push_back(*a); } } } } //if (alts.empty()) alts = genotypeAlleles; if (!alts.empty() && (1 - pHom.ToDouble()) >= parameters.PVL || parameters.PVL == 0) { vcf::Variant var(parser->variantCallFile); out << results.vcf( var, pHom, bestComboOddsRatio, samples, referenceBase, alts, repeats, genotypingTotalIterations, parser->sampleList, coverage, bestCombo, alleleGroups, partialObservationGroups, partialObservationSupport, genotypesByPloidy, parser->sequencingTechnologies, parser) << endl; } else if (!parameters.failedFile.empty()) { // get the unique alternate alleles in this combo, sorted by frequency in the combo long unsigned int position = parser->currentPosition; for (vector<Allele>::iterator ga = genotypeAlleles.begin(); ga != genotypeAlleles.end(); ++ga) { if (ga->type == ALLELE_REFERENCE) continue; parser->failedFile << parser->currentSequenceName << "\t" << position << "\t" << position + ga->length << "\t" << *ga << endl; } // BED format } DEBUG2("finished position"); } DEBUG("total sites: " << total_sites << endl << "processed sites: " << processed_sites << endl << "ratio: " << (float) processed_sites / (float) total_sites); delete parser; return 0; }
inline BigFloat Min<BigFloat>( const BigFloat& alpha ) { BigFloat one(1,alpha.Precision()); return one << (MinExponent<BigFloat>()-1); }
inline BigFloat Max<BigFloat>( const BigFloat& alpha ) { BigFloat one(1,alpha.Precision()); return (one-Epsilon(one)) << MaxExponent<BigFloat>(); }
NxI32 CommandCallback(NxI32 token,NxI32 count,const char **arglist) { NxI32 ret = 0; saveMenuState(); switch ( token ) { case MC_MEMORY_REPORT: break; case MC_FLOATING_POINT_RESOLUTION: if ( count == 2 ) { MultiFloatType type = MFT_MEDIUM; if ( stricmp(arglist[1],"SMALL") == 0 ) type = MFT_SMALL; else if ( stricmp(arglist[1],"MEDIUM") == 0 ) type = MFT_MEDIUM; else if ( stricmp(arglist[1],"BIGFLOAT") == 0 ) type = MFT_BIG; else if ( stricmp(arglist[1],"FIXED32") == 0 ) type = MFT_FIXED32; tf_setFloatingPointResolution(gTfrac,type); gLog->Display("Setting Floating Point Resolution to: %s\r\n", arglist[1] ); } break; case MC_SHOW_NORMALS: if ( count == 2 ) { setShowNormals( getBool(arglist[1]) ); } break; case MC_ENVIRONMENT_TEXTURE: if ( count == 2 ) { const char *t = arglist[1]; if ( gFileSystem ) t = gFileSystem->FileOpenString(t,true); gPd3d->setEnvironmentTexture(t); } break; case MC_ROTATION_SPEED: if ( count == 2 ) { NxF32 rspeed = (NxF32)atof( arglist[1] ); setRotationSpeed(rspeed); } break; case MC_OPTIMIZE_MESH: if ( !mStartup ) { tf_state(gTfrac,TS_OPTIMIZE_MESH); } break; case MC_FILTER_FRACTAL: if ( !mStartup ) { tf_state(gTfrac,TS_FILTER_FRACTAL); } break; case MC_DEFAULT_MANDELBROT: if ( !mStartup ) { BigFloat xleft; BigFloat xright; BigFloat ytop; xleft.FromDouble(-2.5); xright.FromDouble(0.75); ytop.FromDouble(-1.5); tf_setFractalCoordinates(gTfrac,xleft,xright,ytop); tf_action(gTfrac,FA_MOUSE_CENTER,false,1024/2,768/2); } break; case MC_CLAMP_LOW: if ( count == 2 && gTfrac ) { NxF32 c = (NxF32) atof( arglist[1] ); tf_state(gTfrac,TS_CLAMP_LOW,false,0,c); } break; case MC_CLAMP_HIGH: if ( count == 2 && gTfrac ) { NxF32 c = (NxF32) atof( arglist[1] ); tf_state(gTfrac,TS_CLAMP_HIGH,false,0,c); } break; case MC_CLAMP_SCALE: if ( count == 2 && gTfrac ) { NxF32 c = (NxF32) atof( arglist[1] ); tf_state(gTfrac,TS_CLAMP_SCALE,false,0,c); } break; case MC_WIREFRAME_OVERLAY: if ( count == 2 && gTfrac ) { bool state = getBool(arglist[1]); tf_state(gTfrac,TS_WIREFAME_OVERLAY,state); } break; case MC_VIEW3D: if ( count == 2 ) { gView3d = getBool(arglist[1]); if ( gView3d ) { NxF32 eye[3]; NxF32 look[3]; look[0] = 0; look[1] = 0; look[2] = 0; eye[0] = 200; eye[1] = 250; eye[2] = 200; lookAt(eye,look); } } break; case MC_FRACTAL_COORDINATES: if ( count == 4 && gTfrac ) { BigFloat xleft = arglist[1]; BigFloat xright = arglist[2]; BigFloat ytop = arglist[3]; tf_setFractalCoordinates(gTfrac,xleft,xright,ytop); } break; case MC_COLOR_PALETTE: if ( count == 2 && gTfrac ) { tf_setPal(gTfrac,arglist[1]); } break; case MC_ITERATION_COUNT: if ( count == 2 && gTfrac ) { NxU32 icount = (NxU32)atoi(arglist[1]); tf_state(gTfrac,TS_ITERATION_COUNT,false,icount); } break; case MC_CLOCK_CYCLES: if ( count == 2 && gTfrac ) { NxU32 icount = (NxU32)atoi(arglist[1]); tf_state(gTfrac,TS_CLOCK_CYCLES,false,icount); } break; case MC_USE_THREADING: if ( count == 2 && gTfrac ) { bool state = getBool(arglist[1]); tf_state(gTfrac,TS_THREADING,state); } break; case MC_SMOOTH_COLOR: if ( count == 2 && gTfrac ) { NxI32 cscale = atoi(arglist[1]); tf_state(gTfrac,TS_SMOOTH_COLOR,false,cscale); } break; case MC_PREVIEW_ONLY: if ( count == 2 && gTfrac ) { bool state = getBool(arglist[1]); tf_state(gTfrac,TS_PREVIEW_ONLY,state); } break; case MC_RECTANGLE_SUBDIVISION: if ( count == 2 && gTfrac ) { bool state = getBool(arglist[1]); tf_state(gTfrac,TS_RECTANGLE_SUBDIVISION,state); } break; case MC_PSLOOKAT: // 0 1 2 3 4 5 6 // Usage: PsLookAt <eyex> <eyey> <eyez> <lookx> <looky> <lookz> if ( count == 7 ) { NxF32 eye[3]; NxF32 look[3]; eye[0] = (NxF32) atof( arglist[1] ); eye[1] = (NxF32) atof( arglist[2] ); eye[2] = (NxF32) atof( arglist[3] ); look[0] = (NxF32) atof(arglist[4] ); look[1] = (NxF32) atof(arglist[5] ); look[2] = (NxF32) atof(arglist[6] ); lookAt(eye,look); } break; case MC_PSSCRIPT: { const char *fname = 0; if ( count >= 2 ) { fname = arglist[1]; } #if TODO SoftFileInterface *sfi = gSoftBodySystem->getSoftFileInterface(); if ( sfi ) { fname = sfi->getLoadFileName(".psc", "Select a demo script to run."); } if ( fname ) { CPARSER.Parse("Run \"%s\"",fname); } #endif } break; } return ret; }
vector<double> GaussElimination::solveLinearEquationByBigFloat(vector<vector<double>> matrix, vector<double> v) { row = matrix.size(); col = matrix[0].size(); if( row != col ) { cout << "It has to be a linear equation (row != col)." << endl; return vector<double>(0); } if( row == 0 ) { cout << "There are no member in equation (row = col = 0)." << endl; return vector<double>(0); } if( row != v.size() ) { cout << "Length of vector matched not matrix size." << endl; return vector<double>(0); } // umwandlung in bigfloats und anhängen des vectors vector<vector<BigFloat>> matrixBF(row); unsigned int newcol = col + 1; for(unsigned int r = 0; r < row; ++r) { vector<BigFloat> vBF(newcol); matrixBF[r] = vBF; for(unsigned c = 0; c < newcol; ++c) { BigFloat bf; // letzte spalte kommt vom vector if( c == col ) bf.set_with_double( v[r] ); else bf.set_with_double( matrix[r][c] ); matrixBF[r][c] = bf; } } //writeMatrix(matrixBF); // für alle reihen for(unsigned int indexDiagonal = 0; indexDiagonal < row; ++indexDiagonal) { bool success = handleEliminatingValuesInRowByBigFloat(matrixBF, indexDiagonal); if(!success) { cout << "Current row has problems. Row: " << indexDiagonal << endl; return vector<double>(0); } } vector<double> coefficients(row); // letzte spalte = coefficients -> return letzte spalte als vector for(unsigned int i = 0; i < row; ++i) coefficients[i] = matrixBF[i][col].getdouble(); return coefficients; }
BigFloat BigFloat::div(const BigFloat &x,size_t p) const{ // Division return this->mul(x.rcp(p),p); }
BigFloat BigFloat::div(const BigFloat &x,size_t p,int tds) const{ // Division return this->mul(x.rcp(p,tds),p,tds); }