std::string fractal_info::to_str() const { std::string s; s += "Type: "; switch (type) { case MANDELBROT: s += "Mandelbrot"; break; case JULIA: s += "Julia"; break; }; s += "\n"; s += strf( "XMin: %s\n" "XMax: %s\n" "YMax: %s\n", dbl2str(xmin).c_str(), dbl2str(xmax).c_str(), dbl2str(ymax).c_str()); // FIXME: add Julia-specific info here return s; }
/** * Log statistics. */ void StatCalc::log(int generation) { if(generation == -1) generation = statNo; ECF_LOG(state_, 3, "Evaluations: " + uint2str(evaluations_[generation]) + "\nStats: fitness\n\tmax: " + dbl2str(max_[generation]) + "\n\tmin: " + dbl2str(min_[generation]) + "\n\tavg: " + dbl2str(average_[generation]) + "\n\tstdev: " + dbl2str(stdDev_[generation]) + "\n"); }
vector_t Plink::glmAssoc(bool print_results, Perm & perm) { // The model.cpp functions require a SNP-major structure, if SNP // data are being used. There are some exceptions to this however, // listed below if ( par::SNP_major && ! ( par::epi_genebased || par::set_score || par::set_step || par::proxy_glm || par::dosage_assoc || par::cnv_enrichment_test || par::cnv_glm || par::score_test || par::rare_test || par::gvar ) ) SNP2Ind(); // Test all SNPs 1 at a time automatically, or is this // a tailored single test? int ntests = par::assoc_glm_without_main_snp ? 1 : nl_all; vector<double> results(ntests); if ( print_results && par::qt && par::multtest ) tcnt.resize(ntests); ofstream ASC; if (print_results) { string f = par::output_file_name; if ( par::bt) { f += ".assoc.logistic"; printLOG("Writing logistic model association results to [ " + f + " ] \n"); } else { f += ".assoc.linear"; printLOG("Writing linear model association results to [ " + f + " ] \n"); } ASC.open(f.c_str(),ios::out); ASC << setw(4) << "CHR" << " " << setw(par::pp_maxsnp) << "SNP" << " " << setw(10) << "BP" << " " << setw(4) << "A1" << " " << setw(10) << "TEST" << " " << setw(8) << "NMISS" << " "; if ( par::bt && ! par::return_beta ) ASC << setw(10) << "OR" << " "; else ASC << setw(10) << "BETA" << " "; if (par::display_ci) ASC << setw(8) << "SE" << " " << setw(8) << string("L"+dbl2str(par::ci_level*100)) << " " << setw(8) << string("U"+dbl2str(par::ci_level*100)) << " "; ASC << setw(12) << "STAT" << " " << setw(12) << "P" << " " << "\n"; ASC.precision(4); } ///////////////////////////// // Determine sex distribution int nmales = 0, nfemales = 0; for (int i=0; i<n; i++) if ( ! sample[i]->missing ) { if ( sample[i]->sex ) nmales++; else nfemales++; } bool variationInSex = nmales > 0 && nfemales > 0; ////////////////////////////////////////// // Iterate over each locus, or just once for (int l=0; l<ntests; l++) { // Skip possibly (in all-locus mode) if ( par::adaptive_perm && ( ! par::assoc_glm_without_main_snp ) && ( ! perm.snp_test[l]) ) continue; ////////////////////////////////////////////////////////// // X-chromosome, haploid? // xchr_model 0: skip non-autosomal SNPs bool X=false; bool automaticSex=false; if ( ! par::assoc_glm_without_main_snp ) { if ( par::xchr_model == 0 ) { if ( par::chr_sex[locus[l]->chr] || par::chr_haploid[locus[l]->chr] ) continue; } else if (par::chr_sex[locus[l]->chr]) X=true; } ////////////////////////////////////////////////////////// // A new GLM Model * lm; ////////////////////////////////////////////////////////// // Linear or logistic? if (par::bt) { LogisticModel * m = new LogisticModel(this); lm = m; } else { LinearModel * m = new LinearModel(this); lm = m; } ////////////////////////////////////////////////////////// // A temporary fix if ( par::dosage_assoc || par::cnv_enrichment_test || par::cnv_glm || par::score_test || par::set_score || par::proxy_glm || par::gvar || par::rare_test ) lm->hasSNPs(false); ////////////////////////////////////////////////////////// // Set missing data lm->setMissing(); ////////////////////////////////////////////////////////// // Set genetic model if ( par::glm_dominant ) lm->setDominant(); else if ( par::glm_recessive || par::twoDFmodel_hethom ) lm->setRecessive(); string mainEffect = ""; bool genotypic = false; ///////////////////////////////////////////////// // Main SNP if ( ! par::assoc_glm_without_main_snp ) { genotypic = par::chr_haploid[locus[l]->chr] ? false : par::twoDFmodel ; // Models // AA AB BB // Additive 0 1 2 // Dominant 0 1 1 // Recessive 0 0 1 // Genotypic(1) // Additive 0 1 2 // Dom Dev. 0 1 0 // Genotypic(2) // Homozygote 0 0 1 // Heterozygote 0 1 0 //////////////////////////////////////////////////////////// // An additive effect? (or single coded effect) of main SNP if ( par::glm_recessive ) mainEffect = "REC"; else if ( par::glm_dominant ) mainEffect = "DOM"; else if ( par::twoDFmodel_hethom ) mainEffect = "HOM"; else mainEffect = "ADD"; lm->addAdditiveSNP(l); lm->label.push_back(mainEffect); ////////////////////////////////////////////////////////// // Or a 2-df additive + dominance model? if ( genotypic ) { lm->addDominanceSNP(l); if ( par::twoDFmodel_hethom ) lm->label.push_back("HET"); else lm->label.push_back("DOMDEV"); } } ////////////////////////////////////////////////////////// // Haplotypes: WHAP test (grouped?) if ( par::chap_test ) { // Use whap->group (a list of sets) to specify these, from // the current model (either alternate or null) // Start from second category (i.e. first is reference) for (int h=1; h < whap->current->group.size(); h++) { lm->addHaplotypeDosage( whap->current->group[h] ); lm->label.push_back( "WHAP"+int2str(h+1) ); } } ////////////////////////////////////////////////////////// // Haplotypes: proxy test if ( par::proxy_glm ) { // Unlike WHAP tests, we now will only ever have two // categories; and a single tested coefficient set<int> t1 = haplo->makeSetFromMap(haplo->testSet); lm->addHaplotypeDosage( t1 ); lm->label.push_back( "PROXY" ); } if ( par::test_hap_GLM ) { // Assume model specified in haplotype sets // Either 1 versus all others, or H-1 versus // terms for omnibus set<int>::iterator i = haplo->sets.begin(); while ( i != haplo->sets.end() ) { set<int> t; t.insert(*i); lm->addHaplotypeDosage( t ); lm->label.push_back( haplo->haplotypeName( *i ) ); ++i; } } ////////////////////////////////////////////////////////// // Conditioning SNPs? // (might be X or autosomal, dealth with automatically) if (par::conditioning_snps) { if ( par::chap_test ) { for (int c=0; c<conditioner.size(); c++) { if ( whap->current->masked_conditioning_snps[c] ) { lm->addAdditiveSNP(conditioner[c]); lm->label.push_back(locus[conditioner[c]]->name); } } } else { for (int c=0; c<conditioner.size(); c++) { lm->addAdditiveSNP(conditioner[c]); lm->label.push_back(locus[conditioner[c]]->name); } } } ////////////////////////////////////////////////////////// // Sex-covariate (necessary for X chromosome models, unless // explicitly told otherwise) if ( ( par::glm_sex_effect || ( X && !par::glm_no_auto_sex_effect ) ) && variationInSex ) { automaticSex = true; lm->addSexEffect(); lm->label.push_back("SEX"); } ////////////////////////////////////////////////////////// // Covariates? if (par::clist) { for (int c=0; c<par::clist_number; c++) { lm->addCovariate(c); lm->label.push_back(clistname[c]); } } ////////////////////////////////////////////////////////// // Interactions // addInteraction() takes parameter numbers // i.e. not covariate codes // 0 intercept // 1 {A} // {D} // {conditioning SNPs} // {sex efffect} // {covariates} // Allow for interactions between conditioning SNPs, sex, covariates, etc //////////////////////////////////////// // Basic SNP x covariate interaction? // Currently -- do not allow interactions if no main effect // SNP -- i.e. we need a recoding of things here. if ( par::simple_interaction && ! par::assoc_glm_without_main_snp ) { // A, D and haplotypes by conditioning SNPs, sex, covariates int cindex = 2; if ( genotypic ) cindex = 3; for (int c=0; c<conditioner.size(); c++) { lm->addInteraction(1,cindex); lm->label.push_back(mainEffect+"xCSNP"+int2str(c+1)); if ( genotypic ) { lm->addInteraction(2,cindex); if ( par::twoDFmodel_hethom ) lm->label.push_back("HETxCSNP"+int2str(c+1)); else lm->label.push_back("DOMDEVxCSNP"+int2str(c+1)); } cindex++; } if ( automaticSex ) { lm->addInteraction(1,cindex); lm->label.push_back(mainEffect+"xSEX"); if ( genotypic ) { lm->addInteraction(2,cindex); if ( par::twoDFmodel_hethom ) lm->label.push_back("HETxSEX"); else lm->label.push_back("DOMDEVxSEX"); } cindex++; } for (int c=0; c<par::clist_number; c++) { lm->addInteraction(1,cindex); lm->label.push_back(mainEffect+"x"+clistname[c]); if ( genotypic ) { lm->addInteraction(2,cindex); if ( par::twoDFmodel_hethom ) lm->label.push_back("HETx"+clistname[c]); else lm->label.push_back("DOMDEVx"+clistname[c]); } cindex++; } } ////////////////////////////// // Fancy X chromosome models if ( X && automaticSex && par::xchr_model > 2 ) { // Interaction between allelic term and sex (i.e. // allow scale of male effect to vary) int sindex = 2; if ( genotypic ) sindex++; sindex += conditioner.size(); lm->addInteraction(2,sindex); lm->label.push_back("XxSEX"); // xchr model 3 : test ADD + XxSEX // xchr model 4 : test ADD + DOM + XxSEX } ////////////////////////////// // Build design matrix lm->buildDesignMatrix(); ////////////////////////////// // Clusters specified? if ( par::include_cluster ) { lm->setCluster(); } ////////////////////////////////////////////////// // Fit linear or logistic model (Newton-Raphson) lm->fitLM(); //////////////////////////////////////// // Check for multi-collinearity lm->validParameters(); //////////////////////////////////////// // Obtain estimates and statistic if (print_results) lm->displayResults(ASC,locus[l]); //cout << setw(25) << lm->getVar()[1] << " " << lm->isValid() << " " << realnum(lm->getVar()[1]) << endl; //for test purpose only //////////////////////////////////////////////// // Test linear hypothesis (multiple parameters) // Perform if: // automatic 2df genotypic test ( --genotypic ) // OR // sex-tests ( --xchr-model ) // OR // test of everything ( --test-all ) // OR // user has specified user-defined test ( --tests ) if ( ( genotypic && ! par::glm_user_parameters ) || par::glm_user_test || par::test_full_model ) { vector_t h; // dim = number of fixes (to =0) matrix_t H; // row = number of fixes; cols = np int df; string testname; //////////////////////////////////////////////// // Joint test of all parameters if (par::test_full_model) { df = lm->getNP() - 1; h.resize(df,0); testname = "FULL_"+int2str(df)+"DF"; sizeMatrix(H,df,lm->getNP()); for (int i=0; i<df; i++) H[i][i+1] = 1; } //////////////////////////////////////////////// // Joint test of user-specified parameters else if (par::glm_user_test) { df = par::test_list.size(); h.resize(df,0); testname = "USER_"+int2str(df)+"DF"; sizeMatrix(H,df,lm->getNP()); for (int i=0; i<df; i++) if ( par::test_list[i]<lm->getNP() ) H[i][par::test_list[i]] = 1; } //////////////////////////////////////////////// // Joint test of additive and dominant models else if ( genotypic ) { testname = "GENO_2DF"; df = 2; h.resize(2,0); sizeMatrix(H,2,lm->getNP()); H[0][1] = H[1][2] = 1; } else if ( X && par::xchr_model == 3 ) { testname = "XMOD_2DF"; } //////////////////////////////////////////////// // Joint test of all parameters double chisq = lm->isValid() ? lm->linearHypothesis(H,h) : 0; double pvalue = chiprobP(chisq,df); // If filtering p-values if ( (!par::pfilter) || pvalue <= par::pfvalue ) { ASC << setw(4) << locus[l]->chr << " " << setw(par::pp_maxsnp) << locus[l]->name << " " << setw(10) << locus[l]->bp << " " << setw(4) << locus[l]->allele1 << " " << setw(10) << testname << " " << setw(8) << lm->Ysize() << " " << setw(10) << "NA" << " "; if (par::display_ci) ASC << setw(8) << "NA" << " " << setw(8) << "NA" << " " << setw(8) << "NA" << " "; if (lm->isValid() && realnum(chisq) ) ASC << setw(12) << chisq << " " << setw(12) << pvalue << "\n"; else ASC << setw(12) << "NA" << " " << setw(12) << "NA" << "\n"; } } //////////////////////////////////////// // Store statistic (1 df chisq), and p-value // if need be ( based on value of testParameter ) if ( ! par::assoc_glm_without_main_snp ) results[l] = lm->getStatistic(); if ( par::qt && print_results && par::multtest ) tcnt[l] = lm->Ysize() - lm->getNP(); ////////////////////////////////////////////// // Clear up linear model, if no longer needed if ( par::chap_test || par::test_hap_GLM || par::set_step || par::set_score || par::proxy_glm || par::dosage_assoc || par::cnv_enrichment_test || par::cnv_glm || par::score_test || par::gvar || par::rare_test ) { // Responsibility to clear up in parent routine model = lm; } else { delete lm; } // Flush output buffer ASC.flush(); // Next SNP } if (print_results) ASC.close(); return results; }
/** * \brief Initialize all mutation operators of all active genotypes */ bool Mutation::initialize(StateP state) { state_ = state; protectedGenotypes_.clear(); protectedGenotypes_.insert(protectedGenotypes_.begin(), operators.size(), false); opProb.clear(); voidP sptr = state->getRegistry()->getEntry("mutation.indprob"); indMutProb_ = *((double*)sptr.get()); sptr = state->getRegistry()->getEntry("mutation.geneprob"); // geneMutProb_ = *((double*)sptr.get()); // if(state->getRegistry()->isModified("mutation.geneprob") == false) // geneMutProb_ = 0; sptr = state->getRegistry()->getEntry("mutation.genotypes"); std::string mutGen = *((std::string*)sptr.get()); mutateGenotypes_ = RANDOM_GENOTYPE; if(mutGen == "random") mutateGenotypes_ = RANDOM_GENOTYPE; else if(mutGen == "all") mutateGenotypes_ = ALL_GENOTYPES; else ECF_LOG_ERROR(state, "Warning: invalid parameter value (key: mutation.genotypes)"); // read protected genotypes std::stringstream ss; sptr = state->getRegistry()->getEntry("mutation.protected"); ss << *((std::string*) sptr.get()); uint genId; while(ss >> genId) { // read all the data from string if(genId >= protectedGenotypes_.size()) { ECF_LOG_ERROR(state, "Error: invalid genotype index (key: mutation.protected)!"); throw(""); } protectedGenotypes_[genId] = true; } // initialize operators for all genotypes for(uint gen = 0; gen < operators.size(); gen++) { uint nOps = (uint) operators[gen].size(); // if the genotype doesn't define mutation operators if(nOps == 0) { protectedGenotypes_[gen] = true; std::vector<double> empty; opProb.push_back(empty); break; } for(uint i = 0; i < nOps; i++) { operators[gen][i]->state_ = state; operators[gen][i]->initialize(state); } // calculate cumulative operator probabilities std::vector<double> probs(nOps); probs[0] = operators[gen][0]->probability_; for(uint i = 1; i < nOps; i++) { probs[i] = probs[i - 1] + operators[gen][i]->probability_; } if(probs[nOps - 1] == 0) { std::vector<double> none(1); none[0] = -1; opProb.push_back(none); } else { if(probs[nOps - 1] != 1) { double normal = probs[nOps - 1]; ECF_LOG_ERROR(state, "Warning: " + operators[gen][0]->myGenotype_->getName() + " mutation operators: cumulative probability not equal to 1 (sum = " + dbl2str(normal) + ")"); for(uint i = 0; i < probs.size(); i++) probs[i] /= normal; } opProb.push_back(probs); } } return true; }
static void query_chat_location(PurpleConnection *gc) { whatsapp_connection *wconn = purple_connection_get_protocol_data(gc); char *who, *prev, *author; int size; double lat, lng; unsigned long timestamp; if (waAPI_querychatlocation(wconn->waAPI, &who, &prev, &size, &lat, &lng, &author, ×tamp)) { purple_debug_info(WHATSAPP_ID, "Got geomessage from: %s Coordinates (%f %f)\n", who, (float)lat, (float)lng); char *msg = g_strdup_printf("<a href=\"http://openstreetmap.org/?lat=%s&lon=%s&zoom=20\">http://openstreetmap.org/?lat=%s&lon=%s&zoom=20</a>", dbl2str(lat), dbl2str(lng), dbl2str(lat), dbl2str(lng)); conv_add_message(gc, who, msg, author, timestamp); g_free(msg); } }
vector<double> Plink::calcMantelHaenszel_2x2xK(Perm & perm, bool original) { // Should we perform BD test (K>1) if (nk<2) par::breslowday = false; ofstream MHOUT; if ( original ) { ////////////////////////////////// // Any individual not assigned to a cluster, making missing // phenotype (only need to do this once, for original) vector<Individual*>::iterator person = sample.begin(); while ( person != sample.end() ) { if ( (*person)->sol < 0 ) (*person)->missing = true; person++; } string f = par::output_file_name + ".cmh"; MHOUT.open(f.c_str(),ios::out); MHOUT << setw(4) << "CHR" << " " << setw(par::pp_maxsnp) << "SNP" << " " << setw(10) << "BP" << " " << setw(4) << "A1" << " " << setw(8) << "MAF" << " " << setw(4) << "A2" << " " << setw(10) << "CHISQ" << " " << setw(10) << "P" << " " << setw(10) << "OR" << " " << setw(10) << "SE" << " " << setw(10) << string("L"+dbl2str(par::ci_level*100)) << " " << setw(10) << string("U"+dbl2str(par::ci_level*100)) << " "; if (par::breslowday) MHOUT << setw(10) << "CHISQ_BD" << " " << setw(10) << "P_BD" << " "; MHOUT << "\n"; MHOUT.precision(4); printLOG("Cochran-Mantel-Haenszel 2x2xK test, K = " + int2str( nk) + "\n"); if (par::breslowday) printLOG("Performing Breslow-Day test of homogeneous odds ratios\n"); printLOG("Writing results to [ " + f + " ]\n"); // Warnings, if (par::breslowday && nk>10) printLOG("** Warning ** Breslow-Day statistics require large N per cluster ** \n"); } double zt = ltqnorm( 1 - (1 - par::ci_level) / 2 ) ; // Cochran-Mantel-Haenszel 2x2xK test vector<double> results(nl_all); vector<CSNP*>::iterator s = SNP.begin(); int l=0; while ( s != SNP.end() ) { // Skip possibly if (par::adaptive_perm && !perm.snp_test[l]) { s++; l++; continue; } // Disease X allele X strata // Calculate mean of 11 cell for each strata vector<double> mean_11(nk,0); vector<double> var_11(nk,0); // Calculate statistic vector<double> n_11(nk,0); vector<double> n_12(nk,0); vector<double> n_21(nk,0); vector<double> n_22(nk,0); // Disease marginals vector<double> n_1X(nk,0); // disease vector<double> n_2X(nk,0); // no disease vector<double> n_X1(nk,0); // F allele vector<double> n_X2(nk,0); // T allele vector<double> n_TT(nk,0); // Total allele count ///////////////////////// // Autosomal or haploid? bool X=false, haploid=false; if (par::chr_sex[locus[l]->chr]) X=true; else if (par::chr_haploid[locus[l]->chr]) haploid=true; //////////////////////// // Consider each person vector<bool>::iterator i1 = (*s)->one.begin(); vector<bool>::iterator i2 = (*s)->two.begin(); vector<Individual*>::iterator gperson = sample.begin(); while ( gperson != sample.end() ) { Individual * pperson = (*gperson)->pperson; bool s1 = *i1; bool s2 = *i2; // Affected individuals if ( pperson->aff && !pperson->missing ) { // Haploid? if ( haploid || ( X && (*gperson)->sex ) ) { // Allelic marginal if ( ! s1 ) { // FF hom n_11[ pperson->sol ] ++ ; n_X1[ pperson->sol ] ++ ; } else { if ( ! s2 ) // FT { gperson++; i1++; i2++; continue; // skip missing genotypes } else // TT { n_12[ pperson->sol ] ++ ; n_X2[ pperson->sol ] ++ ; } } // Disease marginal n_1X[ pperson->sol ] ++; n_TT[ pperson->sol ] ++; } else // autosomal { // Allelic marginal if ( ! s1 ) { if ( ! s2 ) // FF hom { n_11[ pperson->sol ] +=2 ; n_X1[ pperson->sol ] +=2 ; } else { n_11[ pperson->sol ]++ ; // FT het n_12[ pperson->sol ]++ ; n_X1[ pperson->sol ]++ ; n_X2[ pperson->sol ]++ ; } } else { if ( ! s2 ) // FT { gperson++; i1++; i2++; continue; // skip missing genotypes } else // TT { n_12[ pperson->sol ] +=2 ; n_X2[ pperson->sol ] +=2 ; } } // Disease marginal n_1X[ pperson->sol ] += 2; n_TT[ pperson->sol ] += 2; } // end autosomal } else if ( ! pperson->missing ) // Unaffecteds { // Haploid? if ( haploid || ( X && (*gperson)->sex ) ) { // Allelic marginal if ( ! s1 ) { // FF hom n_21[ pperson->sol ] ++ ; n_X1[ pperson->sol ] ++ ; } else { if ( ! s2 ) // FT { gperson++; i1++; i2++; continue; // skip missing genotypes } else // TT { n_22[ pperson->sol ] ++ ; n_X2[ pperson->sol ] ++ ; } } // Disease marginal n_2X[ pperson->sol ] ++; n_TT[ pperson->sol ] ++; } else // autosomal { // Allelic marginal if ( ! s1 ) { if ( ! s2 ) // FF { n_X1[ pperson->sol ] +=2 ; n_21[ pperson->sol ] +=2 ; } else { n_X1[ pperson->sol ] ++ ; n_X2[ pperson->sol ] ++ ; n_21[ pperson->sol ] ++ ; n_22[ pperson->sol ] ++ ; } } else { if ( ! s2 ) // FT { gperson++; i1++; i2++; continue; // skip missing genotypes } else // TT { n_X2[ pperson->sol ] +=2 ; n_22[ pperson->sol ] +=2 ; } } // disease marginal n_2X[ pperson->sol ] += 2; n_TT[ pperson->sol ] += 2; } // end autosomal } // end unaffected gperson++; i1++; i2++; } // count next individual // Finished iterating over individuals: cluster needs at least 2 // nonmissing individuals vector<bool> validK(nk,false); for (int k=0; k<nk; k++) if (n_TT[k]>=2) validK[k]=true; for (int k=0; k<nk; k++) { if (validK[k]) { mean_11[k] = ( n_X1[k] * n_1X[k] ) / n_TT[k] ; var_11[k] = ( n_X1[k] * n_X2[k] * n_1X[k] * n_2X[k] ) / ( n_TT[k]*n_TT[k]*(n_TT[k]-1) ); // cout << k << " " // << n_11[k] << " " // << n_12[k] << " " // << n_21[k] << " " // << n_22[k] << "\n"; } } double CMH = 0; double denom = 0; for (int k=0; k<nk; k++) { if (validK[k]) { CMH += n_11[k] - mean_11[k]; denom += var_11[k]; } } CMH *= CMH; CMH /= denom; // MH Odds ratio & CI double R = 0; double S = 0; vector<double> r2(nk); vector<double> s2(nk); for (int k=0; k<nk; k++) { if (validK[k]) { r2[k] = (n_11[k]*n_22[k]) / n_TT[k]; s2[k] = (n_12[k]*n_21[k]) / n_TT[k]; R += r2[k]; S += s2[k]; } } double OR = R / S ; double v1 = 0, v2 = 0, v3 = 0; for (int k=0; k<nk; k++) { if (validK[k]) { v1 += (1/n_TT[k]) * ( n_11[k] + n_22[k] ) * r2[k] ; v2 += (1/n_TT[k]) * ( n_12[k] + n_21[k] ) * s2[k] ; v3 += (1/n_TT[k]) * ( ( n_11[k] + n_22[k] ) * s2[k] + ( n_12[k] + n_21[k] ) * r2[k] ); } } double SE = ( 1/(2*R*R) ) * v1 + (1/(2*S*S)) * v2 + (1/(2*R*S)) * v3 ; SE = sqrt(SE); double OR_lower = exp( log(OR) - zt * SE ); double OR_upper = exp( log(OR) + zt * SE ); if ( original ) { double pvalue = chiprobP(CMH,1); // Skip?, if filtering p-values if ( par::pfilter && ( pvalue > par::pfvalue || pvalue < 0 ) ) goto skip_p_cmh; MHOUT << setw(4) << locus[l]->chr << " " << setw(par::pp_maxsnp) << locus[l]->name << " " << setw(10) << locus[l]->bp << " " << setw(4) << locus[l]->allele1 << " " << setw(8) << locus[l]->freq << " " << setw(4) << locus[l]->allele2 << " "; if (realnum(CMH)) MHOUT << setw(10) << CMH << " " << setw(10) << chiprobP(CMH,1) << " "; else MHOUT << setw(10) << "NA" << " " << setw(10) << "NA" << " "; if (realnum(OR)) MHOUT << setw(10) << OR << " "; else MHOUT << setw(10) << "NA" << " "; if (realnum(SE)) MHOUT << setw(10) << SE << " "; else MHOUT << setw(10) << "NA" << " "; if (realnum(OR_lower)) MHOUT << setw(10) << OR_lower << " "; else MHOUT << setw(10) << "NA" << " "; if (realnum(OR_upper)) MHOUT << setw(10) << OR_upper << " "; else MHOUT << setw(10) << "NA" << " "; // Optional Breslow-Day test of homogeneity of odds ratios if (par::breslowday) { double amax; double bb; double determ; double as_plus; double as_minus; double Astar; double Bstar; double Cstar; double Dstar; double Var; double BDX2 = 0; int df = 0; for (int k=0; k<nk; k++) { if (validK[k]) { df++; amax = (n_1X[k] < n_X1[k]) ? n_1X[k] : n_X1[k]; bb = n_2X[k] + n_1X[k] * OR - n_X1[k] * (1-OR); determ = sqrt(bb*bb + 4*(1-OR) * OR * n_1X[k] * n_X1[k]); as_plus = ( -bb + determ ) / ( 2 - 2 * OR ); as_minus = ( -bb - determ ) / ( 2 - 2 * OR ); Astar = as_minus <= amax && as_minus >= 0 ? as_minus : as_plus ; Bstar = n_1X[k] - Astar; Cstar = n_X1[k] - Astar; Dstar = n_2X[k] - n_X1[k] + Astar; Var = 1/(1/Astar + 1/Bstar + 1/Cstar + 1/Dstar); BDX2 += ( (n_11[k] - Astar) * ( n_11[k] - Astar ) ) / Var ; } } double BDp = chiprobP( BDX2 , df-1 ); if ( BDp > -1 ) MHOUT << setw(10) << BDX2 << " " << setw(10) << BDp << " "; else MHOUT << setw(10) << "NA" << " " << setw(10) << "NA" << " "; } MHOUT << "\n"; } skip_p_cmh: // Store for permutation procedure, based 2x2xK CMH result results[l] = CMH; // Next SNP s++; l++; } if (original) MHOUT.close(); return results; }
static void waprpl_process_incoming_events(PurpleConnection * gc) { whatsapp_connection *wconn = purple_connection_get_protocol_data(gc); PurpleAccount *acc = purple_connection_get_account(gc); int err; do { char * reason; err = waAPI_geterror(wconn->waAPI, &reason); if (err != 0) { PurpleConnectionError errcode = PURPLE_CONNECTION_ERROR_OTHER_ERROR; if (err == 1) errcode = PURPLE_CONNECTION_ERROR_AUTHENTICATION_FAILED; purple_connection_error_reason(gc, errcode, reason); g_free(reason); } } while (err != 0); switch (waAPI_loginstatus(wconn->waAPI)) { case 0: purple_connection_update_progress(gc, "Connecting", 0, 4); break; case 1: purple_connection_update_progress(gc, "Sending authorization", 1, 4); break; case 2: purple_connection_update_progress(gc, "Awaiting response", 2, 4); break; case 3: if (!wconn->connected) { purple_connection_update_progress(gc, "Connection established", 3, 4); purple_connection_set_state(gc, PURPLE_CONNECTED); PurpleAccount *account = purple_connection_get_account(gc); PurpleStatus *status = purple_account_get_active_status(account); waprpl_insert_contacts(gc); waprpl_set_status(account, status); wconn->connected = 1; } break; default: break; }; /* Groups update */ if (waAPI_getgroupsupdated(wconn->waAPI)) { purple_debug_info(WHATSAPP_ID, "Receiving update information from my groups\n"); /* Delete/update the chats that are in our list */ PurpleBlistNode *node; for (node = purple_blist_get_root(); node; node = purple_blist_node_next(node, FALSE)) { if (!PURPLE_BLIST_NODE_IS_CHAT(node)) continue; PurpleChat *ch = PURPLE_CHAT(node); if (purple_chat_get_account(ch) != acc) continue; GHashTable *hasht = purple_chat_get_components(ch); char *grid = g_hash_table_lookup(hasht, "id"); char *glist = waAPI_getgroups(wconn->waAPI); gchar **gplist = g_strsplit(glist, ",", 0); if (str_array_find(gplist, grid) >= 0) { /* The group is in the system, update the fields */ char *sub, *own; waAPI_getgroupinfo(wconn->waAPI, grid, &sub, &own, 0); g_hash_table_replace(hasht, g_strdup("subject"), sub); g_hash_table_replace(hasht, g_strdup("owner"), own); purple_blist_alias_chat(ch, sub); } else { /* The group was deleted */ PurpleChat *del = (PurpleChat *) node; node = purple_blist_node_next(node, FALSE); purple_blist_remove_chat(del); } g_strfreev(gplist); g_free(glist); } /* Add new groups */ char *glist = waAPI_getgroups(wconn->waAPI); gchar **gplist = g_strsplit(glist, ",", 0); gchar **p; for (p = gplist; *p; p++) { gchar *gpid = *p; PurpleChat *ch = blist_find_chat_by_id(gc, gpid); if (!ch) ch = create_chat_group(gpid, wconn, acc); /* Now update the open conversation that may exist */ char *id = g_hash_table_lookup(purple_chat_get_components(ch), "id"); int prplid = chatid_to_convo(id); PurpleConversation *conv = purple_find_chat(gc, prplid); char *subject, *owner, *part; if (conv && waAPI_getgroupinfo(wconn->waAPI, id, &subject, &owner, &part)) { conv_add_participants(conv, part, owner); } } g_strfreev(gplist); g_free(glist); } t_message m; while (waAPI_querymsg(wconn->waAPI, &m)) { switch (m.type) { case 0: purple_debug_info(WHATSAPP_ID, "Got chat message from %s: %s\n", m.who, m.message); conv_add_message(gc, m.who, m.message, m.author, m.t); break; case 1: { purple_debug_info(WHATSAPP_ID, "Got image from %s: %s\n", m.who, m.message); int imgid = purple_imgstore_add_with_id(g_memdup(m.image, m.imagelen), m.imagelen, NULL); char *msg = g_strdup_printf("<a href=\"%s\"><img id=\"%u\"></a><br/><a href=\"%s\">%s</a>", m.url, imgid, m.url, m.url); conv_add_message(gc, m.who, msg, m.author, m.t); g_free(msg); } break; case 2: { purple_debug_info(WHATSAPP_ID, "Got geomessage from: %s Coordinates (%f %f)\n", m.who, (float)m.lat, (float)m.lng); char * lat = dbl2str(m.lat); char * lng = dbl2str(m.lng); char *msg = g_strdup_printf("<a href=\"http://openstreetmap.org/?lat=%s&lon=%s&zoom=20\">" "http://openstreetmap.org/?lat=%s&lon=%s&zoom=20</a>", lat, lng, lat, lng); conv_add_message(gc, m.who, msg, m.author, m.t); g_free(msg); g_free(lng); g_free(lat); } break; case 3: { purple_debug_info(WHATSAPP_ID, "Got chat sound from %s: %s\n", m.who, m.url); char *msg = g_strdup_printf("<a href=\"%s\">%s</a>", m.url, m.url); conv_add_message(gc, m.who, msg, m.author, m.t); g_free(msg); } break; case 4: { purple_debug_info(WHATSAPP_ID, "Got chat video from %s: %s\n", m.who, m.url); char *msg = g_strdup_printf("<a href=\"%s\">%s</a>", m.url, m.url); conv_add_message(gc, m.who, msg, m.author, m.t); g_free(msg); } break; case 5: { purple_debug_info(WHATSAPP_ID, "Got phone call from %s\n", m.who); conv_add_message(gc, m.who, "[Trying to voice-call you]", m.author, m.t); } break; default: purple_debug_info(WHATSAPP_ID, "Got an unrecognized message!\n"); break; }; g_free(m.who); g_free(m.author); g_free(m.message); } while (1) { int typer; char msgid[128]; if (!waAPI_queryreceivedmsg(wconn->waAPI, msgid, &typer)) break; purple_debug_info(WHATSAPP_ID, "Received message %s type: %d\n", msgid, typer); purple_signal_emit(purple_connection_get_prpl(gc), "whatsapp-message-received", gc, msgid, typer); } /* Status changes, typing notices and profile pictures. */ query_status(gc); query_typing(gc); query_icon(gc); }
void Plink::displayGeneReport() { // Simply read in any generic results file and list of SNPs by // ranges (which may be subsetted). // if ( false ) // readMapFile(par::mapfile,include,include_pos,nl_actual); ofstream GREP; GREP.open( (par::output_file_name + ".range.report").c_str() , ios::out); map<string, set<Range> > ranges; // Read list of ranges ranges = readRange( par::greport_gene_list ); // Filter ranges if ( par::greport_subset ) ranges = filterRanges( ranges, par::greport_subset_file ); // Open a single results file ifstream RESIN; RESIN.open( par::greport_results.c_str() , ios::in ); // Read first (header) row char cline[par::MAX_LINE_LENGTH]; RESIN.getline(cline,par::MAX_LINE_LENGTH,'\n'); string sline = cline; if (sline=="") error("Problem reading [ " + par::greport_results + " ]\n"); string buf; stringstream ss(sline); vector<string> tokens; while (ss >> buf) tokens.push_back(buf); int chr_column = -1; int bp_column = -1; int pval_column = -1; int snp_column = -1; for (int i=0; i<tokens.size(); i++) { if ( tokens[i] == "CHR" ) chr_column = i; if ( tokens[i] == "BP" ) bp_column = i; if ( tokens[i] == "SNP" ) snp_column = i; if ( tokens[i] == "P" ) pval_column = i; } // Do we have a list of SNPs to specifically extract? set<string> extractSNP; if ( par::extract_set ) { if ( snp_column == -1 ) error("Did not find a SNP field, so cannot use --extract"); checkFileExists( par::extract_file ); PP->printLOG("Only extracting SNPs listed in [ " + par::extract_file + " ]\n"); ifstream IN(par::extract_file.c_str(), ios::in); while ( ! IN.eof() ) { string snpname; IN >> snpname; if ( snpname=="" ) continue; extractSNP.insert(snpname); } IN.close(); PP->printLOG("Read " + int2str( extractSNP.size() ) + " SNPs to extract\n"); } if ( chr_column < 0 || bp_column < 0 ) error("Could not find CHR and BP fields in results file"); map<Range*,vector<string> > annotatedResults; string headerline = sline; int cnt = 0; while ( ! RESIN.eof() ) { // if ( ! par::silent ) // cout << "Processing results line " << ++cnt << " \r"; // vector<string> tokens = tokenizeLine( RESIN ); char cline[par::MAX_LINE_LENGTH]; RESIN.getline(cline,par::MAX_LINE_LENGTH,'\n'); string sline = cline; if (sline=="") continue; string buf; stringstream ss(sline); vector<string> tokens; while (ss >> buf) tokens.push_back(buf); if ( tokens.size() <= chr_column || tokens.size() <= bp_column ) continue; // Using a p-value-filtering field? double pvalue = 0; if ( pval_column != -1 ) { if ( tokens.size() <= pval_column ) continue; if ( ! from_string<double>( pvalue, tokens[pval_column] , std::dec)) continue; if ( par::pfilter && pvalue > par::pfvalue ) continue; } if ( par::extract_set ) { if ( tokens.size() <= snp_column ) continue; if ( extractSNP.find( tokens[snp_column] ) == extractSNP.end() ) continue; } int thisChr = -1; int thisBP = -1; if ( ! from_string<int>( thisChr, tokens[chr_column] , std::dec)) continue; if ( ! from_string<int>( thisBP, tokens[bp_column] , std::dec)) continue; // Do we need to store this? i.e. what ranges is it actually in? // This information is in snp2range Range r1(thisChr,thisBP,thisBP,"dummy"); set<Range*> implicated = rangeIntersect(r1,ranges); set<Range*>::iterator ri = implicated.begin(); while ( ri != implicated.end() ) { string distance = dbl2str(( thisBP - ((*ri)->start + par::make_set_border)) /1000.00 , 4 ) + "kb" ; if ( annotatedResults.find( *ri ) == annotatedResults.end() ) { vector<string> t(2); t[0] = distance; t[1] = sline; annotatedResults.insert(make_pair( (Range *)(*ri) , t ) ); } else { vector<string> & v = annotatedResults.find( *ri )->second; v.push_back(distance); v.push_back(sline); } ++ri; } // Read next line of results } // Iterate through these -- they will be in genomic order, hopefully map<string, set<Range> >::iterator ri = ranges.begin(); while ( ri != ranges.end() ) { set<Range>::iterator si = ri->second.begin(); while ( si != ri->second.end() ) { bool displayed = false; map<Range*,vector<string> >::iterator ari; ari = annotatedResults.find( (Range *)&(*si) ); if ( ari != annotatedResults.end() ) { for (int l=0; l< ari->second.size(); l+=2) { if ( ! displayed ) { GREP << ri->first << " -- chr" << chromosomeName( si->chr ) << ":" << si->start << ".." << si->stop << " ( " << (si->stop - si->start ) / 1000.00 << "kb ) "; if ( par::make_set_border > 0 ) GREP << " including " << par::make_set_border/1000.00 << "kb border "; GREP << "\n\n" << setw(12) << "DIST" << " " << headerline << "\n"; displayed = true; } GREP << setw(12) << ari->second[l] << " " << ari->second[l+1] << "\n"; } } if ( ! displayed ) { if ( par::greport_display_empty ) { GREP << ri->first << " -- chr" << chromosomeName( si->chr ) << ":" << si->start << ".." << si->stop << " ( " << (si->stop - si->start ) / 1000.00 << "kb ) "; if ( par::make_set_border > 0 ) GREP << " including " << par::make_set_border/1000.00 << "kb border "; GREP << " { nothing to report }\n\n"; } } else GREP << "\n\n"; ++si; } ++ri; } RESIN.close(); GREP.close(); if ( ! par::silent ) cout << "\n"; printLOG("Writing per-range report to [ " + par::output_file_name + ".range.report ]\n"); shutdown(); }
/* * StripConfig_write * */ int StripConfig_write (StripConfig *scfg, FILE *f, StripConfigMask mask) { StripConfigMaskElement elem; int i, j = 0; char cbuf[BUFSIZE], fbuf[BUFSIZE], num_buf[BUFSIZE]; char *p; cColor *pcolor; fprintf (f, "%-*s%d.%d\n", LEFT_COLUMNWIDTH, STRIPCONFIG_HEADER_STR, STRIPCONFIG_MAJOR_VERSION, STRIPCONFIG_MINOR_VERSION); for (i = 0; i < SCFGMASK_NUM_ELEMENTS; i++) { elem = SCFGMASK_FIRST_ELEMENT + i; if (StripConfigMask_stat (&mask, elem)) { p = cbuf; sprintf (p, "%s", SCFTokenStr[STRIP]); p += strlen (p); /* Time */ if (StripConfigMask_stat (&SCFGMASK_TIME, elem)) { sprintf (p, "%s%s%s%s", SCFTokenStr[SEPARATOR], SCFTokenStr[TIME], SCFTokenStr[SEPARATOR], SCFTokenStr[i]); sprintf (fbuf, "%-*s", LEFT_COLUMNWIDTH, cbuf); switch (elem) { case SCFGMASK_TIME_TIMESPAN: fprintf (f, "%s%u\n", fbuf, scfg->Time.timespan); break; case SCFGMASK_TIME_NUM_SAMPLES: fprintf (f, "%s%d\n", fbuf, scfg->Time.num_samples); break; case SCFGMASK_TIME_SAMPLE_INTERVAL: fprintf (f, "%s%f\n", fbuf, scfg->Time.sample_interval); break; case SCFGMASK_TIME_REFRESH_INTERVAL: fprintf (f, "%s%f\n", fbuf, scfg->Time.refresh_interval); break; } } /* Color */ else if (StripConfigMask_stat (&SCFGMASK_COLOR, elem)) { sprintf (p, "%s%s%s%s", SCFTokenStr[SEPARATOR], SCFTokenStr[COLOR], SCFTokenStr[SEPARATOR], SCFTokenStr[i]); sprintf (fbuf, "%-*s", LEFT_COLUMNWIDTH, cbuf); /* remember that n = (1 << i), that i is a SFCToken, * and that we have a mapping from token -> attribute */ StripConfig_getattr (scfg, (StripConfigAttribute)i+1, &pcolor, 0); fprintf (f, "%s%-*hu%-*hu%-*hu\n", fbuf, NUMERIC_COLUMNWIDTH, pcolor->xcolor.red, NUMERIC_COLUMNWIDTH, pcolor->xcolor.green, NUMERIC_COLUMNWIDTH, pcolor->xcolor.blue); } /* Option */ else if (StripConfigMask_stat (&SCFGMASK_OPTION, elem)) { sprintf (p, "%s%s%s%s", SCFTokenStr[SEPARATOR], SCFTokenStr[OPTION], SCFTokenStr[SEPARATOR], SCFTokenStr[i]); sprintf (fbuf, "%-*s", LEFT_COLUMNWIDTH, cbuf); switch (elem) { case SCFGMASK_OPTION_GRID_XON: j = scfg->Option.grid_xon; break; case SCFGMASK_OPTION_GRID_YON: j = scfg->Option.grid_yon; break; case SCFGMASK_OPTION_AXIS_YCOLORSTAT: j = scfg->Option.axis_ycolorstat; break; case SCFGMASK_OPTION_GRAPH_LINEWIDTH: j = scfg->Option.graph_linewidth; break; } fprintf (f, "%s%d\n", fbuf, j); } /* Curves */ else if (StripConfigMask_stat (&SCFGMASK_CURVE, elem)) { sprintf (p, "%s%s", SCFTokenStr[SEPARATOR], SCFTokenStr[CURVE]); for (j = 0; j < STRIP_MAX_CURVES; j++) { if (scfg->Curves.Detail[j].id == NULL) continue; sprintf (fbuf, "%s%s%d%s%s", cbuf, SCFTokenStr[SEPARATOR], j, SCFTokenStr[SEPARATOR], SCFTokenStr[i]); switch (elem) { case SCFGMASK_CURVE_NAME: fprintf (f, "%-*s%s\n", LEFT_COLUMNWIDTH, fbuf, scfg->Curves.Detail[j].name); break; case SCFGMASK_CURVE_EGU: if (StripConfigMask_stat (&scfg->Curves.Detail[j].set_mask, SCFGMASK_CURVE_EGU)) fprintf (f, "%-*s%s\n", LEFT_COLUMNWIDTH, fbuf, scfg->Curves.Detail[j].egu); break; case SCFGMASK_CURVE_COMMENT: if (StripConfigMask_stat (&scfg->Curves.Detail[j].set_mask, SCFGMASK_CURVE_COMMENT)) fprintf (f, "%-*s%s\n", LEFT_COLUMNWIDTH, fbuf, scfg->Curves.Detail[j].comment); break; case SCFGMASK_CURVE_PRECISION: if (StripConfigMask_stat (&scfg->Curves.Detail[j].set_mask, SCFGMASK_CURVE_PRECISION)) fprintf (f, "%-*s%d\n", LEFT_COLUMNWIDTH, fbuf, scfg->Curves.Detail[j].precision); break; case SCFGMASK_CURVE_MIN: if (StripConfigMask_stat (&scfg->Curves.Detail[j].set_mask, SCFGMASK_CURVE_MIN)) { dbl2str (scfg->Curves.Detail[j].min, scfg->Curves.Detail[j].precision, num_buf, 31); fprintf (f, "%-*s%s\n", LEFT_COLUMNWIDTH, fbuf, num_buf); } break; case SCFGMASK_CURVE_MAX: if (StripConfigMask_stat (&scfg->Curves.Detail[j].set_mask, SCFGMASK_CURVE_MAX)) { dbl2str (scfg->Curves.Detail[j].max, scfg->Curves.Detail[j].precision, num_buf, 31); fprintf (f, "%-*s%s\n", LEFT_COLUMNWIDTH, fbuf, num_buf); break; } case SCFGMASK_CURVE_SCALE: fprintf (f, "%-*s%d\n", LEFT_COLUMNWIDTH, fbuf, scfg->Curves.Detail[j].scale); break; case SCFGMASK_CURVE_PLOTSTAT: fprintf (f, "%-*s%d\n", LEFT_COLUMNWIDTH, fbuf, scfg->Curves.Detail[j].plotstat); break; } } } } } return 1; }