Example #1
0
int main(int argc, char * argv [])
{

	int next_option;
	const char * const short_options = "p:i:d:m:n:c:o:s:t:g:a:erlh:b:vu";
//b - interaction parameter

	const struct option long_options [] =
	{
		{"pheno",  1, NULL, 'p'},
		{"info",   1, NULL, 'i'},
		{"dose",   1, NULL, 'd'},
		{"map",	   1, NULL, 'm'},
		{"nids",   1, NULL, 'n'},
		{"chrom",  1, NULL, 'c'},
		{"out",    1, NULL, 'o'},
		{"skipd",  1, NULL, 's'},
		{"ntraits",1, NULL, 't'},
		{"ngpreds",1, NULL, 'g'},
		{"separat",1, NULL, 'a'},
		{"score",  0, NULL, 'r'},
		{"no-head",0, NULL, 'e'},
		{"allcov", 0, NULL, 'l'},
		{"help",   0, NULL, 'h'},
		{"interaction",   1, NULL, 'b'},
		{"interaction_only",   1, NULL, 'k'},
		{"mmscore",   1, NULL, 'v'},
		{"robust",   0, NULL, 'u'},
		{NULL  ,   0, NULL, 0  }
	};
	char * program_name = argv[0];

	char *phefilename = NULL;
	char *mlinfofilename = NULL;
	char *genfilename = NULL;
	char *mapfilename = NULL;
	char *outfilename = NULL;
	char *inverse_filename = NULL;
	string sep = " ";
	int nohead=0;
	int score=0;
	int npeople=-1;
	int ngpreds=1;
	int interaction=0;
	int interaction_excluded=0;
	int robust = 0;
	string chrom = "-1";
	int neco[] = {0,0,0};
	bool iscox=false;
#if COXPH
	int noutcomes = 2;
	iscox=true;
#else
	int noutcomes = 1;
#endif
	int skipd = 2;
	int allcov = 0;
	do
	{
		next_option = getopt_long(argc,argv,short_options,long_options,NULL);
		switch (next_option)
		{
			case 'h': print_help(program_name,0);
			case 'p': 
				  phefilename = optarg; 
				  neco[0]=1; 
				  break;
			case 'i': 
				  mlinfofilename = optarg; 
				  neco[1]=1; 
				  break;
			case 'd': 
				  genfilename = optarg; 
				  neco[2]=1; 
				  break;
			case 'm': 
				  mapfilename = optarg; 
				  break;
			case 'n': 
				  npeople = atoi(optarg); 
				  break;
			case 'c': 
				  chrom = optarg; 
				  break;
			case 'o': 
				  outfilename = optarg; 
				  break;
			case 's':
				  skipd = atoi(optarg); 
				  break;
			case 't':
				  noutcomes = atoi(optarg); 
				  break;
			case 'g':
				  ngpreds = atoi(optarg); 
				  break;
			case 'a':
				  sep = optarg; 
				  break;
			case 'e':
				 nohead=1; 
				 break;
			case 'r':
				 score=1; 
				 break;
			case 'l':
				 allcov=1; 
				 break;
			case 'b':
				 interaction=atoi(optarg); 
				 break;
			case 'k':
				 interaction_excluded=atoi(optarg); 
				 break;
			case 'v':
				 inverse_filename=optarg; 
				 break;
			case 'u':
				 robust=1;
				 break;


			case '?': print_usage(program_name,1);
			case -1 : break;
			default: abort();
		}
	}
	while (next_option != -1);


	fprintf(stdout, 
		"ProbABEL v. %s (%s) (C) Yurii Aulchenko, Maksim Struchalin, EMCR, and others\n\n", 
		VERSION, DATE);
	if (neco[0]!=1 || neco[1]!=1 || neco[2]!=1)
	{
		print_usage(program_name,1);
	}
	
	fprintf(stdout,"Options in effect:\n");
	fprintf(stdout,"\t --pheno   = %s\n",phefilename);
	fprintf(stdout,"\t --info    = %s\n",mlinfofilename);
	fprintf(stdout,"\t --dose    = %s\n",genfilename);
	fprintf(stdout,"\t --ntraits = %d\n",noutcomes);
	fprintf(stdout,"\t --ngpreds = %d\n",ngpreds);
	fprintf(stdout,"\t --interaction = %d\n",interaction);
	fprintf(stdout,"\t --interaction_only = %d\n",interaction_excluded);
	
	if (inverse_filename != NULL) fprintf(stdout,"\t --mmscore = %s\n",inverse_filename);
	else fprintf(stdout,"\t --mmscore     = not in output\n");
//	fprintf(stdout,"\t --mmscore = %s\n",inverse_filename);
	
	if (mapfilename != NULL) fprintf(stdout,"\t --map     = %s\n",mapfilename);
	else fprintf(stdout,"\t --map     = not in output\n");
	if (npeople>0) fprintf(stdout,"\t --nids    = %d\n",npeople);
	else fprintf(stdout,"\t --nids    = estimated from data\n");
	if (chrom != "-1") cout << "\t --chrom   = " << chrom << "\n";
	else cout << "\t --chrom   = not in output\n";
	if (outfilename != NULL ) fprintf(stdout,"\t --out     = %s\n",outfilename);
	else fprintf(stdout,"\t --out     = regression.out.txt\n");
	fprintf(stdout,"\t --skipd   = %d\n",skipd);
	cout << "\t --separat = \"" << sep << "\"\n";
	if (score)
		fprintf(stdout,"\t --score   = ON\n");
	else
		fprintf(stdout,"\t --score   = OFF\n");
	if (nohead)
		fprintf(stdout,"\t --nohead  = ON\n");
	else
		fprintf(stdout,"\t --nohead  = OFF\n");
	if (allcov)
		fprintf(stdout,"\t --allcov  = ON\n");
	else
		fprintf(stdout,"\t --allcov  = OFF\n");
	if (robust)
		fprintf(stdout,"\t --robust  = ON\n");
	else
		fprintf(stdout,"\t --robust  = OFF\n");

	if (ngpreds!=1 && ngpreds!=2) 
	{
		fprintf(stderr,"\n\n--ngpreds should be 1 for MLDOSE or 2 for MLPROB\n");
		exit(1);
	}
	
	if(interaction_excluded != 0)
		{
		interaction = interaction_excluded; //ups
		is_interaction_excluded = true;
		}

#if COXPH
	if (score) 
	{
		fprintf(stderr,"\n\nOption --score is implemented for linear and logistic models only\n");
		exit(1);
	}
#endif
//	if (allcov && ngpreds>1)
//	{
//		fprintf(stdout,"\n\nWARNING: --allcov allowed only for 1 predictor (MLDOSE)\n");
//		allcov = 0;
//	}

	mlinfo mli(mlinfofilename,mapfilename);
	int nsnps = mli.nsnps;
	phedata phd(phefilename,noutcomes,npeople, interaction, iscox);
	
  int interaction_cox = interaction;
#if COXPH
	interaction_cox--;
#endif
	if(interaction < 0 || interaction > phd.ncov || interaction_cox > phd.ncov)
		{
		std::cerr << "error: Interaction parameter is out of range (ineraction="<<interaction<<") \n";
		exit(1);
		}

	//interaction--;

//	if(inverse_filename != NULL && phd.ncov > 1)
//		{
//		std::cerr<<"Error: In mmscore you can not use any covariates. You phenotype file must conatin id column and trait (residuals) only\n";
//		exit(1);
//		}

//	if(inverse_filename != NULL && (allcov == 1 || score == 1 || interaction != 0 || ngpreds==2))
//		{
//		std::cerr<<"Error: In mmscore you can use additive model without any inetractions only\n";		
//		exit(1);
//		}




	 mematrix<double> invvarmatrix;

#if LOGISTIC		
	if(inverse_filename != NULL) {std::cerr<<"ERROR: mmscore is forbidden for logistic regression\n";exit(1);}
#endif

#if COXPH
	if(inverse_filename != NULL) {std::cerr<<"ERROR: mmscore is forbidden for cox regression\n";exit(1);}
	if (robust) {
	  //std::cerr<<"ERROR: robust standard errors not implemented for Cox regression (drop us e-mail if you really need that)\n";exit(1);
	  cout << "Robust standard errors implemented for Cox regression\n";
	}
#endif


	if(inverse_filename != NULL)
		{
		std::cout<<"you are runing mmscore...\n";
		}

	std::cout << "Reading data ...";



	if(inverse_filename != NULL)
		{
		InvSigma inv(inverse_filename, &phd);
		invvarmatrix = inv.get_matrix();
		double par=1.; //var(phd.Y)*phd.nids/(phd.nids-phd.ncov-1);
		invvarmatrix = invvarmatrix*par;
	//	matrix.print();
		}

		
	

	std::cout.flush();
	gendata gtd(genfilename,nsnps,ngpreds,phd.nids_all,phd.nids,phd.allmeasured,skipd,phd.idnames);

// estimate null model
	double null_loglik=0.;
#if COXPH
	coxph_data nrgd(phd,gtd,-1);
#else 
	regdata nrgd(phd,gtd,-1);
#endif
#if LOGISTIC
	logistic_reg nrd(nrgd);
	nrd.estimate(nrgd,0,MAXITER,EPS,CHOLTOL,0, interaction, ngpreds, invvarmatrix, robust, 1);
#elif LINEAR
	linear_reg nrd(nrgd);
	nrd.estimate(nrgd,0,CHOLTOL,0, interaction, ngpreds, invvarmatrix, robust, 1);
#elif COXPH
	coxph_reg nrd(nrgd);
	nrd.estimate(nrgd,0,MAXITER,EPS,CHOLTOL,0, interaction, ngpreds, 1, robust);
#endif
	null_loglik = nrd.loglik;

// end null 
#if COXPH
	coxph_data rgd(phd,gtd,0);
#else 
	regdata rgd(phd,gtd,0);
#endif
	std::cout << " done\n";
	std::cout.flush();







//________________________________________________________________
//Maksim, 9 Jan, 2009

if (outfilename==NULL) 
	{
	outfilename="regression";
	}

std::string outfilename_str(outfilename);
std::vector<std::ofstream*> outfile;


if (nohead!=1)
	{

	if(ngpreds==2) //All models output. One file per each model
		{
		// open a file for output
		//_____________________



		for(int i=0 ; i<5 ; i++)
			{
			outfile.push_back(new std::ofstream());
			}
	
		outfile[0]->open((outfilename_str+"_2df.out.txt").c_str());
		outfile[1]->open((outfilename_str+"_add.out.txt").c_str());
		outfile[2]->open((outfilename_str+"_domin.out.txt").c_str());
		outfile[3]->open((outfilename_str+"_recess.out.txt").c_str());
		outfile[4]->open((outfilename_str+"_over_domin.out.txt").c_str());



		if (!outfile[0]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_2df.out.txt" << "\n"; exit(1);}
		if (!outfile[1]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_add.out.txt" << "\n"; exit(1);}
		if (!outfile[2]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_domin.out.txt" << "\n"; exit(1);}
		if (!outfile[3]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_recess.out.txt" << "\n"; exit(1);}
		if (!outfile[4]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_over_domin.out.txt" << "\n"; exit(1);}
		//_____________________


		//Header
		//_____________________
		for(int i=0 ; i<outfile.size() ; i++)
			{
			(*outfile[i]) << "name" << sep << "A1" << sep << "A2" << sep << "Freq1" << sep << "MAF" << sep << "Quality" << sep << "Rsq" 
							<< sep << "n" << sep << "Mean_predictor_allele";
			if (chrom != "-1") (*outfile[i]) << sep << "chrom";
			if (mapfilename != NULL) (*outfile[i]) << sep << "position";
			}
		//_____________________
	
		if(allcov) //All covariates in output
			{
			for (int file=0; file<outfile.size() ; file++)
				for (int i =0; i<phd.n_model_terms-1;i++)
					*outfile[file] << sep << "beta_" << phd.model_terms[i] << sep << "sebeta_" << phd.model_terms[i];
			}
			*outfile[0] << sep << "beta_SNP_A1A2" << sep << "beta_SNP_A1A1" << sep << "sebeta_SNP_A1A2" << sep << "sebeta_SNP_A1A1";
			*outfile[1] << sep << "beta_SNP_addA1" << sep << "sebeta_SNP_addA1";
			*outfile[2] << sep << "beta_SNP_domA1" << sep << "sebeta_SNP_domA1";
			*outfile[3] << sep << "beta_SNP_recA1" << sep << "sebeta_SNP_recA1";
			*outfile[4] << sep << "beta_SNP_odom" << sep << "sebeta_SNP_odom";
	
		if(interaction != 0)
			{
//Han Chen
			*outfile[0] << sep << "beta_SNP_A1A2_" << phd.model_terms[interaction_cox] << sep << "sebeta_SNP_A1A2_" << phd.model_terms[interaction_cox]
								 << sep << "beta_SNP_A1A1_" << phd.model_terms[interaction_cox] << sep << "sebeta_SNP_A1A1_" << phd.model_terms[interaction_cox];
			//   #if !COXPH
	    	if(inverse_filename == NULL && !allcov) *outfile[0] << sep << "cov_SNP_A1A2_int_SNP_" << phd.model_terms[interaction_cox]
            << sep << "cov_SNP_A1A1_int_SNP_" << phd.model_terms[interaction_cox];
		// #endif
//Oct 26, 2009
			for (int file=1; file<outfile.size() ; file++)
				{		
			  *outfile[file] << sep << "beta_SNP_" << phd.model_terms[interaction_cox]  << sep << "sebeta_SNP_" << phd.model_terms[interaction_cox];
//Han Chen
    #if !COXPH
	    	if(inverse_filename == NULL && !allcov) *outfile[file] << sep << "cov_SNP_int_SNP_" << phd.model_terms[interaction_cox];
 	  #endif
//Oct 26, 2009
				}
			}
		*outfile[0] << sep << "chi2_SNP_2df\n";
		*outfile[1] << sep << "chi2_SNP_A1\n";
		*outfile[2] << sep << "chi2_SNP_domA1\n";
		*outfile[3] << sep << "chi2_SNP_recA1\n";
		*outfile[4] << sep << "chi2_SNP_odom\n";
	

		}
	else //Only additive model. Only one output file
		{
			
		// open a file for output
		//_____________________
//		if (outfilename != NULL)
//	 		{
			outfile.push_back(new std::ofstream((outfilename_str+"_add.out.txt").c_str()));
//			}
//		else
//	 		{
//			outfilename_str="regression_add.out.txt"; outfile.push_back(new std::ofstream((outfilename_str+"_add.out.txt").c_str()));
//			}

		if (!outfile[0]->is_open())
			{
			std::cerr << "Can not open file for writing: " << outfilename_str << "\n";
			exit(1);
			}
		//_____________________

		//Header
		//_____________________
			*outfile[0] << "name" << sep << "A1" << sep << "A2" << sep << "Freq1" << sep << "MAF" << sep << "Quality" << sep << "Rsq" 
							<< sep << "n" << sep << "Mean_predictor_allele";
			if (chrom != "-1") *outfile[0] << sep << "chrom";
			if (mapfilename != NULL) *outfile[0] << sep << "position";
		//_____________________


		if(allcov) //All covariates in output
			{
			for (int i =0; i<phd.n_model_terms-1;i++)
				*outfile[0] << sep << "beta_" << phd.model_terms[i] << sep << "sebeta_" << phd.model_terms[i];
			
			*outfile[0] << sep << "beta_SNP_add" << sep << "sebeta_SNP_add";
			}
		else //Only beta, sebeta for additive model go to output file
			{
			*outfile[0] << sep << "beta_SNP_add" << sep << "sebeta_SNP_add";
			}
		if(interaction != 0) *outfile[0] << sep << "beta_SNP_" << phd.model_terms[interaction_cox] << sep << "sebeta_SNP_" << phd.model_terms[interaction_cox];

		if(inverse_filename == NULL)
//Han Chen
            {
	      //            #if !COXPH
	    	if(interaction != 0 && !allcov) *outfile[0] << sep << "cov_SNP_int_SNP_" << phd.model_terms[interaction_cox];
		// 	        #endif
			*outfile[0] << sep << "chi2_SNP";
            }
//Oct 26, 2009
		*outfile[0] << "\n";


		}
	}
else
	{
	if(ngpreds==2) //All models output. One file per each model
		{
		// open a file for output
		//_____________________
//		if (outfilename==NULL) 
//			{
//			outfilename_str="regression";
//			}



		for(int i=0 ; i<5 ; i++)
			{
			outfile.push_back(new std::ofstream());
			}
	
		outfile[0]->open((outfilename_str+"_2df.out.txt").c_str());
		outfile[1]->open((outfilename_str+"_add.out.txt").c_str());
		outfile[2]->open((outfilename_str+"_domin.out.txt").c_str());
		outfile[3]->open((outfilename_str+"_recess.out.txt").c_str());
		outfile[4]->open((outfilename_str+"_over_domin.out.txt").c_str());



		if (!outfile[0]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_2df.out.txt" << "\n"; exit(1);}
		if (!outfile[1]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_add.out.txt" << "\n"; exit(1);}
		if (!outfile[2]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_domin.out.txt" << "\n"; exit(1);}
		if (!outfile[3]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_recess.out.txt" << "\n"; exit(1);}
		if (!outfile[4]->is_open()) {std::cerr << "Can not open file for writing: " << outfilename_str+"_over_domin.out.txt" << "\n"; exit(1);}
		}
	else
		{
		// open a file for output
		//_____________________
//		if (outfilename != NULL)
//	 		{
			outfile.push_back(new std::ofstream((outfilename_str+"_add.out.txt").c_str()));
//			}
//		else
//	 		{
//			outfilename_str="regression_add.out.txt"; outfile.push_back(new std::ofstream((outfilename_str+"_add.out.txt").c_str()));
//			}

		if (!outfile[0]->is_open())
			{
			std::cerr << "Can not open file for writing: " << outfilename_str << "\n";
			exit(1);
			}
		
		}
	
	}

//________________________________________________________________

/*
	if (allcov)
		{
		if (score)
			{
			outfile << sep << "beta_mu"; // << sep << "beta_SNP_A1";
			outfile << sep << "sebeta_mu"; // << sep << "sebeta_SNP_A1";
			}
		else 
			{
			for (int i =0; i<phd.n_model_terms-1;i++) 
			outfile << sep << "beta_" << phd.model_terms[i] << sep << "sebeta_" << phd.model_terms[i];
			}
		if(interactio != 0) outfile << sep << "beta_SNP_" << phd.model_terms[interaction];
		}
	if (ngpreds==2) 
		{
		outfile << sep << "beta_SNP_A1A2" << sep << "beta_SNP_A1A1" << sep 
		<< "sebeta_SNP_A1A2" << sep << "sebeta_SNP_a1A1" << sep << "chi2_SNP_2df"
		<< sep << "beta_SNP_addA1" << sep << "sebeta_SNP_addA1" << sep << "chi2_SNP_addA1"
		<< sep << "beta_SNP_domA1" << sep << "sebeta_SNP_domA1" << sep << "chi2_SNP_domA1"
		<< sep << "beta_SNP_recA1" << sep << "sebeta_SNP_recA1" << sep << "chi2_SNP_recA1"
		<< sep << "beta_SNP_odom" << sep << "sebeta_SNP_odom" << sep << "chi2_SNP_odom\n";
		}	
	else 
		{
		outfile << sep << "beta_SNP_add" << sep << "sebeta_SNP_add" << sep << "chi2_SNP_add\n";
		}
	}
*/
//	exit(1);

	
	
//________________________________________________________________
//Maksim, 9 Jan, 2009



int maxmod=5;
int start_pos, end_pos;

std::vector<std::ostringstream *> beta_sebeta;
//Han Chen
std::vector<std::ostringstream *> covvalue;
//Oct 26, 2009
std::vector<std::ostringstream *> chi2;

for(int i=0 ; i<maxmod ; i++)
	{
	beta_sebeta.push_back(new std::ostringstream());
//Han Chen
	covvalue.push_back(new std::ostringstream());
//Oct 26, 2009
	chi2.push_back(new std::ostringstream());
	}



for (int csnp=0;csnp<nsnps;csnp++) 
	{

	rgd.update_snp(gtd,csnp);
	double freq;
	if (ngpreds==2)
			freq = ((gtd.G).column_mean(csnp*2)*2.+(gtd.G).column_mean(csnp*2+1))/2.;
	else
			freq = (gtd.G).column_mean(csnp)/2.;
	int poly = 1;
	if (fabs(freq)<1.e-16 || fabs(1.-freq)<1.e-16) poly=0;
	if (fabs(mli.Rsq[csnp])<1.e-16) poly=0;



	if(ngpreds==2) //All models output. One file per each model
		{
		//Write mlinfo to output:
		for(int file=0 ; file<outfile.size() ; file++)
			{
			*outfile[file] << mli.name[csnp] << sep << mli.A1[csnp] << sep << mli.A2[csnp] << sep
										 << mli.Freq1[csnp] << sep << mli.MAF[csnp] << sep << mli.Quality[csnp] << sep << mli.Rsq[csnp] << sep
										 << phd.nids << sep << freq;
			if (chrom != "-1") *outfile[file] << sep << chrom;
			if (mapfilename != NULL) *outfile[file] << sep << mli.map[csnp];
			}


		for(int model=0 ; model<maxmod ; model++)
			{		
			if(poly)//allel freq is not to rare
				{
				#if LOGISTIC
				logistic_reg rd(rgd);
				if (score)
					rd.score(nrd.residuals,rgd,0,CHOLTOL,model, interaction, ngpreds, invvarmatrix);
				else
					rd.estimate(rgd,0,MAXITER,EPS,CHOLTOL,model, interaction, ngpreds, invvarmatrix, robust);
				#elif LINEAR
				linear_reg rd(rgd);
				if(score)
					rd.score(nrd.residuals,rgd,0,CHOLTOL,model, interaction, ngpreds, invvarmatrix);
				else
				{
				//	rd.mmscore(rgd,0,CHOLTOL,model, interaction, ngpreds, invvarmatrix);
					rd.estimate(rgd,0,CHOLTOL,model, interaction, ngpreds, invvarmatrix, robust);
				}
				#elif COXPH
				coxph_reg rd(rgd);
				rd.estimate(rgd,0,MAXITER,EPS,CHOLTOL,model, interaction, true, ngpreds,0,robust);
				#endif

				if(!allcov && model==0 && interaction==0) start_pos=rd.beta.nrow-2;
				else if(!allcov && model==0 && interaction!=0) start_pos=rd.beta.nrow-4;
				else if(!allcov && model!=0 && interaction==0) start_pos=rd.beta.nrow-1;
				else if(!allcov && model!=0 && interaction!=0) start_pos=rd.beta.nrow-2;
				else start_pos=0;

		
				for(int pos=start_pos ; pos<rd.beta.nrow ; pos++)
					{
					*beta_sebeta[model] << sep << rd.beta[pos] << sep << rd.sebeta[pos];
//Han Chen
//				#if !COXPH
				if (inverse_filename == NULL && !allcov && interaction != 0)
				   {
				   if (pos>start_pos)
				      {if (model==0)
				          {if (pos>start_pos+2)
				              {*covvalue[model] << rd.covariance[pos-3] << sep << rd.covariance[pos-2];}
                          }
                      else
               	          {*covvalue[model] << rd.covariance[pos-1];}
                      }
                   }
//                #endif	
//Oct 26, 2009
					}

				//calculate chi2
				//________________________________
				if (score==0)
					{
					*chi2[model] << 2.*(rd.loglik-null_loglik);
					}
				else
					{
					*chi2[model] << rd.chi2_score;
					}
				//________________________________
				
				
				}
			else //beta, sebeta = nan
				{
				if(!allcov && model==0 && interaction==0) start_pos=rgd.X.ncol-2;
				else if(!allcov && model==0 && interaction!=0) start_pos=rgd.X.ncol-4;
				else if(!allcov && model!=0 && interaction==0) start_pos=rgd.X.ncol-1;
				else if(!allcov && model!=0 && interaction!=0) start_pos=rgd.X.ncol-2;
				else start_pos=0;
					
				if(model==0) {end_pos=rgd.X.ncol;}
				else {end_pos=rgd.X.ncol-1;}

				if(interaction!=0) end_pos++;

				for(int pos=start_pos ; pos<end_pos ; pos++)
					{
					*beta_sebeta[model] << sep << "nan" << sep << "nan";
					}
//Han Chen
//                #if !COXPH
                if (!allcov && interaction !=0)
                   {if (model==0)
                       {*covvalue[model] << "nan" << sep << "nan";}
                   else
                       {*covvalue[model] << "nan";}
                   }
//                #endif
//Oct 26, 2009
				*chi2[model] << "nan";
				}
			}//end of moel cycle
	



//Han Chen
			*outfile[0] << beta_sebeta[0]->str() << sep;
//				#if !COXPH
				if (!allcov && interaction !=0)
                {
                *outfile[0] << covvalue[0]->str() << sep;
                }
//                #endif
            *outfile[0] << chi2[0]->str() << "\n";
			*outfile[1] << beta_sebeta[1]->str() << sep;
//				#if !COXPH
				if (!allcov && interaction !=0)
                {
                *outfile[1] << covvalue[1]->str() << sep;
                }
//                #endif
            *outfile[1] << chi2[1]->str() << "\n";
			*outfile[2] << beta_sebeta[2]->str() << sep;
//				#if !COXPH
				if (!allcov && interaction !=0)
                {
                *outfile[2] << covvalue[2]->str() << sep;
                }
//                #endif
            *outfile[2] << chi2[2]->str() << "\n";
			*outfile[3] << beta_sebeta[3]->str() << sep;
//				#if !COXPH
				if (!allcov && interaction !=0)
                {
                *outfile[3] << covvalue[3]->str() << sep;
                }
//                #endif
            *outfile[3] << chi2[3]->str() << "\n";
			*outfile[4] << beta_sebeta[4]->str() << sep;
//				#if !COXPH
				if (!allcov && interaction !=0)
                {
                *outfile[4] << covvalue[4]->str() << sep;
                }
//                #endif
            *outfile[4] << chi2[4]->str() << "\n";		
//Oct 26, 2009





		}
	else //Only additive model. Only one output file
		{
		//Write mlinfo to output:
		*outfile[0] << mli.name[csnp] << sep << mli.A1[csnp] << sep << mli.A2[csnp] << sep;
		*outfile[0] << mli.Freq1[csnp] << sep << mli.MAF[csnp] << sep << mli.Quality[csnp] << sep << mli.Rsq[csnp] << sep;
		*outfile[0] << phd.nids << sep << freq;
		if (chrom != "-1") *outfile[0] << sep << chrom;
		if (mapfilename != NULL) *outfile[0] << sep << mli.map[csnp];
		int model=0;
		if(poly)//allel freq is not to rare
			{
			#if LOGISTIC
			logistic_reg rd(rgd);
			if (score)
				rd.score(nrd.residuals,rgd,0,CHOLTOL,model, interaction, ngpreds, invvarmatrix);
			else
				rd.estimate(rgd,0,MAXITER,EPS,CHOLTOL,model, interaction, ngpreds, invvarmatrix, robust);
			#elif LINEAR
			linear_reg rd(rgd);
			if (score)
				rd.score(nrd.residuals,rgd,0,CHOLTOL,model, interaction, ngpreds, invvarmatrix);
			else
				{
//					if(inverse_filename == NULL)
//						{
						rd.estimate(rgd,0,CHOLTOL,model, interaction, ngpreds, invvarmatrix, robust);
//						}
//					else
//						{
//						rd.mmscore(rgd,0,CHOLTOL,model, interaction, ngpreds, invvarmatrix);
//						}
				}
			#elif COXPH
			coxph_reg rd(rgd);
			rd.estimate(rgd,0,MAXITER,EPS,CHOLTOL,model, interaction, true, ngpreds,0,robust);
			#endif

			if(!allcov && interaction==0) start_pos=rd.beta.nrow-1;
			else if(!allcov && interaction!=0) start_pos=rd.beta.nrow-2;
			else start_pos=0;
			

				
			for(int pos=start_pos ; pos<rd.beta.nrow ; pos++)
				{
				*beta_sebeta[0] << sep << rd.beta[pos] << sep << rd.sebeta[pos];
//Han Chen
//				#if !COXPH
				if (inverse_filename == NULL && !allcov && interaction != 0)
				   {if (pos>start_pos)
               	       {*covvalue[0] << rd.covariance[pos-1];}
                   }
//                #endif	
//Oct 26, 2009
				}





			//calculate chi2
			//________________________________
			if(inverse_filename == NULL)
				{
				if(score==0)
					{
					*chi2[0] << 2.*(rd.loglik-null_loglik);
					}
					else
					{
					*chi2[0] << rd.chi2_score;
					}
				}
			//________________________________
			}
		else //beta, sebeta = nan
			{
			if(!allcov && interaction==0) start_pos=rgd.X.ncol-1;
			else  if(!allcov && interaction!=0) start_pos=rgd.X.ncol-2;
			else start_pos=0;


	    end_pos=rgd.X.ncol;
			if(interaction!=0) {end_pos++;}
			if(interaction!=0 && !allcov) {start_pos++;} 
	


			for(int pos=start_pos ; pos<end_pos ; pos++)
				{
				*beta_sebeta[0] << sep << "nan" << sep << "nan";
				}
			if(inverse_filename == NULL)
				{
//Han Chen
//                #if !COXPH
                if (!allcov && interaction !=0)
                   {*covvalue[0] << "nan";}
//                #endif
//Oct 26, 2009
				*chi2[0] << "nan";
				}
			}
		
			if(inverse_filename == NULL)
				{
//Han Chen
				*outfile[0] << beta_sebeta[0]->str() << sep;
//				#if !COXPH
				if (!allcov && interaction !=0)
                   {*outfile[0] << covvalue[0]->str() << sep;}
//                #endif
                *outfile[0] << chi2[model]->str() << "\n";
//Oct 26, 2009
				}
			else
				{
				*outfile[0] << beta_sebeta[0]->str() << "\n";
				}
		}

	//clean chi2	
	for(int i=0 ; i<5 ; i++)
		{
		beta_sebeta[i]->str("");
//Han Chen
		covvalue[i]->str("");
//Oct 26, 2009
		chi2[i]->str("");
		}


	if (csnp % 1000 == 0)
		{
		if (csnp==0)
			{
			fprintf(stdout,"Analysis: %6.2f ...",100.*double(csnp)/double(nsnps));
			}
		else
			{
			fprintf(stdout,"\b\b\b\b\b\b\b\b\b\b%6.2f ...",100.*double(csnp)/double(nsnps));
			}
		std::cout.flush();
		}

	}

fprintf(stdout,"\b\b\b\b\b\b\b\b\b\b%6.2f",100.);

fprintf(stdout," ... done\n");
	
//________________________________________________________________
//Maksim, 9 Jan, 2009



	for(int i=0 ; i<outfile.size() ; i++)
		{	
		outfile[i]->close();
		delete outfile[i];	
		}

	return(0);
}
Example #2
0
/* GfxEntryPanel::handleAction
 * Handles the action [id]. Returns true if the action was handled,
 * false otherwise
 *******************************************************************/
bool GfxEntryPanel::handleAction(string id)
{
	// Don't handle actions if hidden
	if (!isActivePanel())
		return false;

	// We're only interested in "pgfx_" actions
	if (!id.StartsWith("pgfx_"))
		return false;

	// Mirror
	if (id == "pgfx_mirror")
	{
		// Mirror X
		getImage()->mirror(false);

		// Update UI
		gfx_canvas->updateImageTexture();
		gfx_canvas->Refresh();

		// Update variables
		image_data_modified = true;
		setModified();
	}

	// Flip
	else if (id == "pgfx_flip")
	{
		// Mirror Y
		getImage()->mirror(true);

		// Update UI
		gfx_canvas->updateImageTexture();
		gfx_canvas->Refresh();

		// Update variables
		image_data_modified = true;
		setModified();
	}

	// Rotate
	else if (id == "pgfx_rotate")
	{
		// Prompt for rotation angle
		string angles[] = { "90", "180", "270" };
		int choice = wxGetSingleChoiceIndex("Select rotation angle", "Rotate", 3, angles, 0);

		// Rotate image
		switch (choice)
		{
		case 0:
			getImage()->rotate(90);
			break;
		case 1:
			getImage()->rotate(180);
			break;
		case 2:
			getImage()->rotate(270);
			break;
		default: break;
		}

		// Update UI
		gfx_canvas->updateImageTexture();
		gfx_canvas->Refresh();

		// Update variables
		image_data_modified = true;
		setModified();
	}

	// Translate
	else if (id == "pgfx_translate")
	{
		// Create translation editor dialog
		Palette8bit* pal = theMainWindow->getPaletteChooser()->getSelectedPalette();
		TranslationEditorDialog ted(theMainWindow, pal, " Colour Remap", gfx_canvas->getImage());

		// Create translation to edit
		ted.openTranslation(prev_translation);

		// Show the dialog
		if (ted.ShowModal() == wxID_OK)
		{
			// Apply translation to image
			getImage()->applyTranslation(&ted.getTranslation(), pal);

			// Update UI
			gfx_canvas->updateImageTexture();
			gfx_canvas->Refresh();

			// Update variables
			image_data_modified = true;
			gfx_canvas->updateImageTexture();
			setModified();
			prev_translation.copy(ted.getTranslation());
		}
	}

	// Colourise
	else if (id == "pgfx_colourise")
	{
		Palette8bit* pal = theMainWindow->getPaletteChooser()->getSelectedPalette();
		GfxColouriseDialog gcd(theMainWindow, entry, pal);
		gcd.setColour(last_colour);

		// Show colourise dialog
		if (gcd.ShowModal() == wxID_OK)
		{
			// Colourise image
			getImage()->colourise(gcd.getColour(), pal);

			// Update UI
			gfx_canvas->updateImageTexture();
			gfx_canvas->Refresh();

			// Update variables
			image_data_modified = true;
			Refresh();
			setModified();
		}
		rgba_t gcdcol = gcd.getColour();
		last_colour = S_FMT("RGB(%d, %d, %d)", gcdcol.r, gcdcol.g, gcdcol.b);
	}

	// Tint
	else if (id == "pgfx_tint")
	{
		Palette8bit* pal = theMainWindow->getPaletteChooser()->getSelectedPalette();
		GfxTintDialog gtd(theMainWindow, entry, pal);
		gtd.setValues(last_tint_colour, last_tint_amount);

		// Show tint dialog
		if (gtd.ShowModal() == wxID_OK)
		{
			// Tint image
			getImage()->tint(gtd.getColour(), gtd.getAmount(), pal);

			// Update UI
			gfx_canvas->updateImageTexture();
			gfx_canvas->Refresh();

			// Update variables
			image_data_modified = true;
			Refresh();
			setModified();
		}
		rgba_t gtdcol = gtd.getColour();
		last_tint_colour = S_FMT("RGB(%d, %d, %d)", gtdcol.r, gtdcol.g, gtdcol.b);
		last_tint_amount = (int)(gtd.getAmount() * 100.0);
	}

	// Crop
	else if (id == "pgfx_crop")
	{
		Palette8bit* pal = theMainWindow->getPaletteChooser()->getSelectedPalette();
		GfxCropDialog gcd(theMainWindow, entry, pal);

		// Show crop dialog
		if (gcd.ShowModal() == wxID_OK)
		{
			// stuff
		}
	}

	// alPh/tRNS
	else if (id == "pgfx_alph" || id == "pgfx_trns")
	{
		setModified();
		Refresh();
	}

	// Optimize PNG
	else if (id == "pgfx_pngopt")
	{
		// This is a special case. If we set the entry as modified, SLADE will prompt
		// to save it, rewriting the entry and cancelling the optimization done...
		if (EntryOperations::optimizePNG(entry))
			setModified(false);
		else
			wxMessageBox("Warning: Couldn't optimize this image, check console log for info", "Warning", wxOK|wxCENTRE|wxICON_WARNING);
		Refresh();
	}

	// Extract all
	else if (id == "pgfx_extract")
	{
		extractAll();
	}

	// Convert
	else if (id == "pgfx_convert")
	{
		GfxConvDialog gcd(theMainWindow);
		gcd.CenterOnParent();
		gcd.openEntry(entry);

		gcd.ShowModal();

		if (gcd.itemModified(0))
		{
			// Get image and conversion info
			SImage* image = gcd.getItemImage(0);
			SIFormat* format = gcd.getItemFormat(0);

			// Write converted image back to entry
			format->saveImage(*image, entry_data, gcd.getItemPalette(0));
			// This makes the "save" button (and the setModified stuff) redundant and confusing!
			// The alternative is to save to entry effectively (uncomment the importMemChunk line)
			// but remove the setModified and image_data_modified lines, and add a call to refresh
			// to get the PNG tRNS status back in sync.
			//entry->importMemChunk(entry_data);
			image_data_modified = true;
			setModified();

			// Fix tRNS status if we converted to paletted PNG
			int MENU_GFXEP_PNGOPT = theApp->getAction("pgfx_pngopt")->getWxId();
			int MENU_GFXEP_ALPH = theApp->getAction("pgfx_alph")->getWxId();
			int MENU_GFXEP_TRNS = theApp->getAction("pgfx_trns")->getWxId();
			int MENU_ARCHGFX_EXPORTPNG = theApp->getAction("arch_gfx_exportpng")->getWxId();
			if (format->getName() == "PNG")
			{
				ArchiveEntry temp;
				temp.importMemChunk(entry_data);
				temp.setType(EntryType::getType("png"));
				menu_custom->Enable(MENU_GFXEP_ALPH, true);
				menu_custom->Enable(MENU_GFXEP_TRNS, true);
				menu_custom->Check(MENU_GFXEP_TRNS, EntryOperations::gettRNSChunk(&temp));
				menu_custom->Enable(MENU_ARCHGFX_EXPORTPNG, false);
				menu_custom->Enable(MENU_GFXEP_PNGOPT, true);
				toolbar->enableGroup("PNG", true);
			}
			else
			{
				menu_custom->Enable(MENU_GFXEP_ALPH, false);
				menu_custom->Enable(MENU_GFXEP_TRNS, false);
				menu_custom->Enable(MENU_ARCHGFX_EXPORTPNG, true);
				menu_custom->Enable(MENU_GFXEP_PNGOPT, false);
				toolbar->enableGroup("PNG", false);
			}

			// Refresh
			getImage()->open(entry_data, 0, format->getId());
			gfx_canvas->Refresh();
		}
	}

	// Unknown action
	else
		return false;

	// Action handled
	return true;
}
Example #3
0
// ----------------------------------------------------------------------------
// Handles the action [id].
// Returns true if the action was handled, false otherwise
// ----------------------------------------------------------------------------
bool GfxEntryPanel::handleEntryPanelAction(std::string_view id)
{
	// We're only interested in "pgfx_" actions
	if (!StrUtil::startsWith(id, "pgfx_"))
		return false;

	// For pgfx_brush actions, the string after pgfx is a brush name
	if (StrUtil::startsWith(id, "pgfx_brush"))
	{
		gfx_canvas_->setBrush(SBrush::get(std::string{ id }));
		button_brush_->setIcon(StrUtil::afterFirst(id, '_'));
	}

	// Editing - drag mode
	else if (id == "pgfx_drag")
	{
		editing_ = false;
		gfx_canvas_->setEditingMode(GfxCanvas::EditMode::None);
	}

	// Editing - draw mode
	else if (id == "pgfx_draw")
	{
		editing_ = true;
		gfx_canvas_->setEditingMode(GfxCanvas::EditMode::Paint);
		gfx_canvas_->setPaintColour(cb_colour_->colour());
	}

	// Editing - erase mode
	else if (id == "pgfx_erase")
	{
		editing_ = true;
		gfx_canvas_->setEditingMode(GfxCanvas::EditMode::Erase);
	}

	// Editing - translate mode
	else if (id == "pgfx_magic")
	{
		editing_ = true;
		gfx_canvas_->setEditingMode(GfxCanvas::EditMode::Translate);
	}

	// Editing - set translation
	else if (id == "pgfx_settrans")
	{
		// Create translation editor dialog
		TranslationEditorDialog ted(
			theMainWindow, *theMainWindow->paletteChooser()->selectedPalette(), " Colour Remap", image());

		// Create translation to edit
		ted.openTranslation(edit_translation_);

		// Show the dialog
		if (ted.ShowModal() == wxID_OK)
		{
			// Set the translation
			edit_translation_.copy(ted.getTranslation());
			gfx_canvas_->setTranslation(&edit_translation_);
		}
	}

	// Editing - set brush
	else if (id == "pgfx_setbrush")
	{
		auto p = button_brush_->GetScreenPosition() -= GetScreenPosition();
		p.y += button_brush_->GetMaxHeight();
		PopupMenu(menu_brushes_, p);
	}

	// Mirror
	else if (id == "pgfx_mirror")
	{
		// Mirror X
		image()->mirror(false);

		// Update UI
		gfx_canvas_->updateImageTexture();
		gfx_canvas_->Refresh();

		// Update variables
		image_data_modified_ = true;
		setModified();
	}

	// Flip
	else if (id == "pgfx_flip")
	{
		// Mirror Y
		image()->mirror(true);

		// Update UI
		gfx_canvas_->updateImageTexture();
		gfx_canvas_->Refresh();

		// Update variables
		image_data_modified_ = true;
		setModified();
	}

	// Rotate
	else if (id == "pgfx_rotate")
	{
		// Prompt for rotation angle
		wxString angles[] = { "90", "180", "270" };
		int      choice   = wxGetSingleChoiceIndex("Select rotation angle", "Rotate", 3, angles, 0);

		// Rotate image
		switch (choice)
		{
		case 0: image()->rotate(90); break;
		case 1: image()->rotate(180); break;
		case 2: image()->rotate(270); break;
		default: break;
		}

		// Update UI
		gfx_canvas_->updateImageTexture();
		gfx_canvas_->Refresh();

		// Update variables
		image_data_modified_ = true;
		setModified();
	}

	// Translate
	else if (id == "pgfx_remap")
	{
		// Create translation editor dialog
		auto                    pal = MainEditor::currentPalette();
		TranslationEditorDialog ted(theMainWindow, *pal, " Colour Remap", &gfx_canvas_->image());

		// Create translation to edit
		ted.openTranslation(prev_translation_);

		// Show the dialog
		if (ted.ShowModal() == wxID_OK)
		{
			// Apply translation to image
			image()->applyTranslation(&ted.getTranslation(), pal);

			// Update UI
			gfx_canvas_->updateImageTexture();
			gfx_canvas_->Refresh();

			// Update variables
			image_data_modified_ = true;
			gfx_canvas_->updateImageTexture();
			setModified();
			prev_translation_.copy(ted.getTranslation());
		}
	}

	// Colourise
	else if (id == "pgfx_colourise")
	{
		auto               pal = MainEditor::currentPalette();
		GfxColouriseDialog gcd(theMainWindow, entry_, *pal);
		gcd.setColour(last_colour);

		// Show colourise dialog
		if (gcd.ShowModal() == wxID_OK)
		{
			// Colourise image
			image()->colourise(gcd.colour(), pal);

			// Update UI
			gfx_canvas_->updateImageTexture();
			gfx_canvas_->Refresh();

			// Update variables
			image_data_modified_ = true;
			Refresh();
			setModified();
		}
		last_colour = gcd.colour().toString(ColRGBA::StringFormat::RGB);
	}

	// Tint
	else if (id == "pgfx_tint")
	{
		auto          pal = MainEditor::currentPalette();
		GfxTintDialog gtd(theMainWindow, entry_, *pal);
		gtd.setValues(last_tint_colour, last_tint_amount);

		// Show tint dialog
		if (gtd.ShowModal() == wxID_OK)
		{
			// Tint image
			image()->tint(gtd.colour(), gtd.amount(), pal);

			// Update UI
			gfx_canvas_->updateImageTexture();
			gfx_canvas_->Refresh();

			// Update variables
			image_data_modified_ = true;
			Refresh();
			setModified();
		}
		last_tint_colour = gtd.colour().toString(ColRGBA::StringFormat::RGB);
		last_tint_amount = (int)(gtd.amount() * 100.0);
	}

	// Crop
	else if (id == "pgfx_crop")
	{
		auto          image = this->image();
		auto          pal   = MainEditor::currentPalette();
		GfxCropDialog gcd(theMainWindow, image, pal);

		// Show crop dialog
		if (gcd.ShowModal() == wxID_OK)
		{
			// Prompt to adjust offsets
			auto crop = gcd.cropRect();
			if (crop.tl.x > 0 || crop.tl.y > 0)
			{
				if (wxMessageBox(
						"Do you want to adjust the offsets? This will keep the graphic in the same relative "
						"position it was before cropping.",
						"Adjust Offsets?",
						wxYES_NO)
					== wxYES)
				{
					image->setXOffset(image->offset().x - crop.tl.x);
					image->setYOffset(image->offset().y - crop.tl.y);
				}
			}

			// Crop image
			image->crop(crop.x1(), crop.y1(), crop.x2(), crop.y2());

			// Update UI
			gfx_canvas_->updateImageTexture();
			gfx_canvas_->Refresh();

			// Update variables
			image_data_modified_ = true;
			Refresh();
			setModified();
		}
	}

	// alPh/tRNS
	else if (id == "pgfx_alph" || id == "pgfx_trns")
	{
		setModified();
		Refresh();
	}

	// Optimize PNG
	else if (id == "pgfx_pngopt")
	{
		// This is a special case. If we set the entry as modified, SLADE will prompt
		// to save it, rewriting the entry and cancelling the optimization done...
		if (EntryOperations::optimizePNG(entry_))
			setModified(false);
		else
			wxMessageBox(
				"Warning: Couldn't optimize this image, check console log for info",
				"Warning",
				wxOK | wxCENTRE | wxICON_WARNING);
		Refresh();
	}

	// Extract all
	else if (id == "pgfx_extract")
	{
		extractAll();
	}

	// Convert
	else if (id == "pgfx_convert")
	{
		GfxConvDialog gcd(theMainWindow);
		gcd.CenterOnParent();
		gcd.openEntry(entry_);

		gcd.ShowModal();

		if (gcd.itemModified(0))
		{
			// Get image and conversion info
			auto image  = gcd.itemImage(0);
			auto format = gcd.itemFormat(0);

			// Write converted image back to entry
			format->saveImage(*image, entry_data_, gcd.itemPalette(0));
			// This makes the "save" button (and the setModified stuff) redundant and confusing!
			// The alternative is to save to entry effectively (uncomment the importMemChunk line)
			// but remove the setModified and image_data_modified lines, and add a call to refresh
			// to get the PNG tRNS status back in sync.
			// entry->importMemChunk(entry_data);
			image_data_modified_ = true;
			setModified();

			// Fix tRNS status if we converted to paletted PNG
			int MENU_GFXEP_PNGOPT      = SAction::fromId("pgfx_pngopt")->wxId();
			int MENU_GFXEP_ALPH        = SAction::fromId("pgfx_alph")->wxId();
			int MENU_GFXEP_TRNS        = SAction::fromId("pgfx_trns")->wxId();
			int MENU_ARCHGFX_EXPORTPNG = SAction::fromId("arch_gfx_exportpng")->wxId();
			if (format->name() == "PNG")
			{
				ArchiveEntry temp;
				temp.importMemChunk(entry_data_);
				temp.setType(EntryType::fromId("png"));
				menu_custom_->Enable(MENU_GFXEP_ALPH, true);
				menu_custom_->Enable(MENU_GFXEP_TRNS, true);
				menu_custom_->Check(MENU_GFXEP_TRNS, EntryOperations::gettRNSChunk(&temp));
				menu_custom_->Enable(MENU_ARCHGFX_EXPORTPNG, false);
				menu_custom_->Enable(MENU_GFXEP_PNGOPT, true);
				toolbar_->enableGroup("PNG", true);
			}
			else
			{
				menu_custom_->Enable(MENU_GFXEP_ALPH, false);
				menu_custom_->Enable(MENU_GFXEP_TRNS, false);
				menu_custom_->Enable(MENU_ARCHGFX_EXPORTPNG, true);
				menu_custom_->Enable(MENU_GFXEP_PNGOPT, false);
				toolbar_->enableGroup("PNG", false);
			}

			// Refresh
			this->image()->open(entry_data_, 0, format->id());
			gfx_canvas_->Refresh();
		}
	}

	// Unknown action
	else
		return false;

	// Action handled
	return true;
}