TString subtractBackground(const TString conf,
		   DYTools::TSystematicsStudy_t runMode=DYTools::NORMAL,
			   const TString plotsDirExtraTag="",
			   int performPUReweight=1){


  std::cout << "\n\nRun mode: " << SystematicsStudyName(runMode) << "\n";
  switch(runMode) {
  case DYTools::NORMAL:
  case DYTools::ESCALE_STUDY:
  case DYTools::ESCALE_STUDY_RND:
    break;
  default:
    std::cout << "subtractBackground is not ready for runMode=" << SystematicsStudyName(runMode) << "\n";
    throw 2;
  }
 
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================

  // Read from configuration file only the location of the root files
  TString inputDir;
  Double_t lumi;
  Bool_t doWeight;
  Bool_t hasData=false;

  ifstream ifs;
  ifs.open(conf.Data());
  assert(ifs.is_open());
  string line;
  int state=0;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(line[0]=='%') { 
      state++; 
      continue; 
    }
    if(state==0) {
      stringstream ss1(line); ss1 >> lumi;
      getline(ifs,line);
      stringstream ss2(line); ss2 >> doWeight;
      getline(ifs,line);
      inputDir = TString(line);
      TString escaleTag_loc,format_loc;
      getline(ifs,line);
      stringstream ss3(line); ss3 >> escaleTag_loc;
      getline(ifs,line);
      format_loc = TString(line);
      state++;
    }
    else if (state==1) {
TEST_F(LoadPlanningModelsPr2, StateSpaces)
{
  ompl_interface::ModelBasedStateSpaceSpecification spec1(kmodel_, "right_arm");
  ompl_interface::ModelBasedStateSpace ss1(spec1);
  ss1.setup();

  ompl_interface::ModelBasedStateSpaceSpecification spec2(kmodel_, "left_arm");
  ompl_interface::ModelBasedStateSpace ss2(spec2);
  ss2.setup();

  ompl_interface::ModelBasedStateSpaceSpecification spec3(kmodel_, "whole_body");
  ompl_interface::ModelBasedStateSpace ss3(spec3);
  ss3.setup();

  ompl_interface::ModelBasedStateSpaceSpecification spec4(kmodel_, "arms");
  ompl_interface::ModelBasedStateSpace ss4(spec4);
  ss4.setup();
  
  std::ofstream fout("ompl_interface_test_state_space_diagram2.dot");
  ompl::base::StateSpace::Diagram(fout);
}
示例#3
0
int xmp_access(const char *path, int mask)
{
    char *path_copy=strdup(path);
  if(strcmp(path,"/")==0) {
    //log_msg("at root");
    return 0;
  }
//  if(strcmp(path,"/")==0) {
        //log_msg("at root");
        return 0;
//  }

  string dirs=database_getval("alldirs","paths");
  string temptok="";
  stringstream dd(dirs);
  while(getline(dd,temptok,':')){
    if(strcmp(temptok.c_str(),path)==0){
      return 0;
    }
  }

  int c=0;
  for(int i=0; path[i]!='\0'; i++){
    if(path[i]=='/') c++;
  }

  //decompose path
  stringstream ss0(path+1);
  string type, attr, val, file, more;
  void* tint=getline(ss0, type, '/');
  void* fint=getline(ss0, file, '/');
  void* mint=getline(ss0, more, '/');
  int reta=0;

  //check for filetype
  if(tint){
    string types = database_getval("allfiles","types");
    stringstream ss(types.c_str());
    string token;
    while(getline(ss,token,':')){
      if(strcmp(type.c_str(),token.c_str())==0){
        reta=1;
      }
    }
    int found=0;

    do{
      //get attr and val
      found=0;
      void *aint=fint;
      string attr=file;
      void *vint=mint;
      string val=more;
      fint=getline(ss0, file, '/');
      mint=getline(ss0, more, '/');

      //check for attr
      if(reta && aint) {
        //cout << attr << endl;
        string attrs= database_getval(type,"attrs");
        stringstream ss3(attrs.c_str());
        reta=0;
        while(getline(ss3,token,':')){
          if(strcmp(attr.c_str(), token.c_str())==0){
            reta=1;
          }
        }

        //check for val
        if(reta && vint) {
          //cout << val << endl;
          if(strcmp(attr.c_str(),("all_"+type+"s").c_str())==0) {
            return 0;
          }
          string vals=database_getvals(attr);
          stringstream ss4(vals.c_str());
          reta=0;
          while(getline(ss4,token,':')){
            //cout << val << token << endl;
            if(strcmp(val.c_str(), token.c_str())==0){
              reta=1;
            }
          }

          //check for file
          if(reta && fint) {
            //cout << file << endl;
            string files=database_getval(attr, val);
            stringstream ss4(files.c_str());
            if(!mint) {
              reta=0;
              while(getline(ss4,token,':')){
                token=database_getval(token,"name");
                if(strcmp(file.c_str(), token.c_str())==0){
                  reta=1;
                }
              }
              stringstream ss5(attrs.c_str());
              while(getline(ss5,token,':')){
                if(strcmp(file.c_str(),token.c_str())==0){
                  reta=1;
                }
              }
            } else {
              found=1;
            }
          }
        }
      }
    }while(found);
  }

  if(reta && !getline(ss0, val, '/')) {
    return 0;
  }
    path=append_path(path);
    int ret = access(path, mask);
    return ret;
}
示例#4
0
config objDetection::utilities::get_Config(int argc, char* argv[])
{
	config res;
	res.camera=false;
	res.image_file=false;
	res.train_major=false;
	res.train_minor=false;
	res.show=false;
	res.back=false;
	res.outputfile=false;	res.outputToConsole=false;
	res.outputToText=false;
	res.predict_major=false;
	res.predict_minor=false;
	res.totalTime=0;
	res.Opcount=0;
	res.hsv_max_B=hsv_max_B;
	res.hsv_max_D=hsv_max_D;
	res.hsv_max_TB=hsv_max_TB;
	res.hsv_max_TY=hsv_max_TY;
	res.hsv_min_B=hsv_min_B;
	res.hsv_min_TB=hsv_min_TB;
	res.hsv_min_TY=hsv_min_TY;
	res.hsv_min_D=hsv_min_D;
	res.storage=cvCreateMemStorage(0);
	res.windowOfInterest.X=80;
	res.windowOfInterest.Y= 110;
	res.windowOfInterest.Width=540;
	res.windowOfInterest.Height= 290;


	int currentIndex=1;
	if(argv[currentIndex][0]=='c')
	{
		res.camera=true;
	}
	if(argv[currentIndex][0]=='i')
	{
		res.image_file=true;
		res.i_base.current=1;	
		//go for image file

	}
	currentIndex++;
	if(res.image_file)
	{
		res.i_base.basefile=argv[currentIndex];
		currentIndex++;
	}
	if(res.image_file)
	{
		res.i_base.image_start=atoi(argv[currentIndex]);
		currentIndex++;
	}
	if(res.image_file)
	{
		res.i_base.step=atoi(argv[currentIndex]);
		currentIndex++;
	}
	if(res.image_file)
	{
		res.i_base.image_end=atoi(argv[currentIndex]);
		currentIndex++;
	}
	if(!strcmp(argv[currentIndex],"window"))
	{
		currentIndex++;
		res.windowOfInterest.X=atoi(argv[currentIndex]);
		currentIndex++;
		res.windowOfInterest.Y=atoi(argv[currentIndex]);
		currentIndex++;
		res.windowOfInterest.Width=atoi(argv[currentIndex]);
		currentIndex++;
		res.windowOfInterest.Height=atoi(argv[currentIndex]);
		currentIndex++;
	}
	if(!strcmp(argv[currentIndex],"train_major"))
	{
		res.train_major=true;
	}
	if(!strcmp(argv[currentIndex],"train_minor"))
	{
		res.train_minor=true;
	}
	if(!strcmp(argv[currentIndex],"predict_major"))
	{
		res.predict_major=true;
	}
	if(!strcmp(argv[currentIndex],"predict_minor"))
	{
		res.predict_minor=true;
	}
	currentIndex++;
	if(currentIndex==argc)
	{
		return res;
	}
std::cout<<"loading config"<<std::endl;
	for(int i=0;i<3;i++)
	{
		if(!strcmp(argv[currentIndex],"show"))
		{
			res.show=true;
		} else if(!strcmp(argv[currentIndex],"outputToText"))
		{
			res.outputToText=true;
			currentIndex++;
			res.outputfile=argv[currentIndex];
		} else if(!strcmp(argv[currentIndex],"outputToConsole"))
		{
			res.outputToConsole=true;
		}else
			break;
		currentIndex++;
		if(currentIndex==argc)
		{
		return res;
		}
		
	}
	if(currentIndex==argc)
	{
		return res;
	}
	if(!strcmp(argv[currentIndex],"TY_min"))
	{
		currentIndex++;
		stringstream ss(argv[currentIndex]);
		double m1;
		ss>>m1;
		currentIndex++;
		stringstream ss2(argv[currentIndex]);
		double m2;
		ss2>>m2;
		currentIndex++;
		stringstream ss3(argv[currentIndex]);
		double m3;
		ss3>>m3;
		currentIndex++;
		res.hsv_min_TY= cvScalar(m1,m2,m3);
	} 
示例#5
0
int main(){

srand((unsigned)time(NULL));
std::random_device rd;
std::default_random_engine generator;
generator.seed( rd() );
std::normal_distribution<double> distribution(0.0,1.0);
//Now we read in the parameters from settings.txt
//new code
std::ifstream setting( "settings.txt" );
std::string line;
std::vector<std::string> settings;
int linenumber=0;
while(std::getline( setting, line))
    {
          if(linenumber%2==1)
              settings.push_back(line);
          linenumber++;
    }
setting.close();

double double_num;
int integer; 

std::vector < double > X0V;
std::vector < double > deltaV;
std::vector <double> sigmaV;
std::vector <double> asset_amountV;



std::istringstream ss(settings[0]);
std::string token;
while(std::getline(ss, token, ',')) 
    {
          X0V.push_back(atof(token.c_str()));
    }

double T = atof(settings[1].c_str());
double m = atof(settings[2].c_str());
double delta_t=T/m;
int Rn;
double v_0, V_0, Z, Xi, Xj, v_sum, sum_Z=0, vtotal_sum=0, Vtotal_sum=0;
double r= atof(settings[3].c_str());

std::istringstream ss2(settings[4]);
while(std::getline(ss2, token, ','))
    {
        deltaV.push_back(atof(token.c_str()));
    }

std::istringstream ss3(settings[5]);
while(std::getline(ss3, token, ','))
    {
        sigmaV.push_back(atof(token.c_str()));
    }

int Path_estimator_iterations=atof(settings[6].c_str());
double strike=atof(settings[7].c_str());
int b=atoi(settings[8].c_str());
int N=atoi(settings[9].c_str());
double quantile=atof(settings[10].c_str());
int num_assets=atof(settings[11].c_str());

std::istringstream ss4(settings[12]);
while(std::getline(ss4, token, ','))
    {
        asset_amountV.push_back(atof(token.c_str()));
    }

if(X0V.size() != num_assets || sigmaV.size() != num_assets || deltaV.size() !=num_assets || asset_amountV.size() !=num_assets){
          std::cout<<"Either the starting price, volatility, number of assets or dividend yield was not specified for all assets"<<std::endl;
           exit (EXIT_FAILURE);
       }

std::cout<<"The parameters of this simulation are:"<<std::endl;
       //Print these values to screen 
for(integer=0; integer<X0V.size(); integer++){
std::cout<<"Starting Price="<<X0V[integer]<<std::endl;
}

std::cout<<"Time to expiry="<<T<<"\n"<<"Number of time steps="<<m<<"\n"<<"interest rate="<<r<<std::endl;

for(integer=0; integer<sigmaV.size(); integer++){
    std::cout<<"volatility="<<sigmaV[integer]<<std::endl;
}

for(integer=0; integer<deltaV.size(); integer++){
    std::cout<<"dividend yield="<<deltaV[integer]<<std::endl;
}
std::cout<<"number of iterations over path estimator="<<Path_estimator_iterations<<"\n"<<"strike  price="<<strike<<"\n"<<"number of nodes per time step="<<b<<"\n"<<"number mesh generations="<<N<<"\n"<<"Number of Assets="<<num_assets<<std::endl; 

for(integer=0; integer<asset_amountV.size(); integer++){
    std::cout<<"asset amount="<<asset_amountV[integer]<<std::endl;
}

//////////////////////////////////////////
//// DECLARE AN INSTANCE OF THE PAYOFF////
//////////////////////////////////////////

GeometricPayOffPut payoff(strike);
//GeometricPayOffPut *payoff_dev;  

// CONVERT TO ARRAYS

double X0 [num_assets];
double delta [num_assets];
double sigma [num_assets];
double asset_amount [num_assets];

one_dim_array(X0V, X0, num_assets);
one_dim_array(deltaV, delta, num_assets);
one_dim_array(sigmaV, sigma, num_assets);
one_dim_array(asset_amountV, asset_amount, num_assets);


// VECTOR CODE
/*
//Mesh matrix
std::vector< std::vector< std::vector<double> > > X;
//WEIGHTS 3-dimensional matrix for step 1 and beyond
std::vector< std::vector< std::vector<double> > > W;
//2-d temp vector in MeshGen for-loop
std::vector < std::vector< double > > myvector;
//temp vecotr in MeshGen for-loop
std::vector<double > nodevector;
//2 d temp vector in WeightsGen for-loop
std::vector< std::vector<double> > dim2temp;
//1 d vector in Weightsgen for-loop
std:: vector<double> dim1temp;
//mesh estimator high bias 2-d matrix
std::vector< std::vector<double> > V;
*/
//V values from each iteration over meshes
std::vector< double > Vvector;
//v values from each iteration over meshes
std::vector< double > vvector;
//asset vector
std::vector< double > assets;
//1 d vector in Weightsgen for-loop
std:: vector<double> dim1temp;

std::vector<double> sortvector;
//std::cout<<"Before loop"<<std::endl;


// ARRAY CODE
int m_int= (int)m;

double* X;
int X_dim = (m_int) * b * (num_assets);
X= new double[X_dim];

double* W;
int W_dim = (m_int) * b * b;
W= new double[W_dim];

double* V;
int V_dim = (m_int) * b;
V = new double[V_dim];

//std::cout<<"before"<<std::endl; 
double* weight_denominator;
int denom_dim = (m_int-1) * b;
weight_denominator =new double[denom_dim];
//std::cout<<"after"<<std::endl;
for(int init=0; init<num_assets; init++){
	X0[init]=log(X0[init]);
}	


//for-loop over different meshes
for(int iterator=0; iterator<N; iterator++){
//X.clear();
//W.clear();
//V.clear();
//for-loop to generate the mesh
for(int i=0; i<m; i++){


	//myvector.clear();

	if(i==0){



	for(int l=0; l<b; l++){

		//nodevector.clear();

		for(int ll=0; ll<num_assets; ll++){
			//Z=boxmuller();//standard normally distributed variable 
			Z=distribution(generator);
		//std::cout<<"meshgen="<<Z<<std::endl;
			//Xi=X0[ll] * (exp ((r-delta[ll]-0.5*pow(sigma[ll], 2))*delta_t + sigma[ll]*sqrt(delta_t)*Z));//node value at the second time step
		//	Xi=X0[ll] +  (r-delta[ll]-0.5*pow(sigma[ll], 2))*delta_t + sigma[ll]*sqrt(delta_t)*Z;
			//nodevector.push_back(Xi);
 
	*three_dim_index(X, i, l, ll, m, b, num_assets) = X0[ll] +  (r-delta[ll]-0.5*pow(sigma[ll], 2))*delta_t + sigma[ll]*sqrt(delta_t)*Z;
		
	//X[m*b*(ll)+m*(l)+(i)]=X0[ll] +  (r-delta[ll]-0.5*pow(sigma[ll], 2))*delta_t + sigma[ll]*sqrt(delta_t)*Z;
		//three_dim_index(X, i, l, ll, m, b, Xi);

		}
	//	myvector.push_back(nodevector);	//store the value in a temp vector
		
	}
	}

	if(i>0){
	
	for(int j=0; j<b; j++){
	
	//	nodevector.clear();
	//	Rn=UniRandom(b);
//std::cout<<Rn<<std::endl;
		for(int jj=0; jj<num_assets; jj++){
			//std::cout<<"in loop"<<"\t"<<Rn<<std::endl;
			//Z=boxmuller();
			Z=distribution(generator); 
			//std::cout<<"meshgen="<<Z<<std::endl;
			//Xi=X[i-1][j][jj];
			//Xi=X[m*b*(jj)+m*(j)+(i-1)];
			Xi=*three_dim_index(X, (i-1), j, jj, m, b, num_assets);
			//Xj=Xi * (exp ((r-delta[jj]-0.5*pow(sigma[jj], 2))*delta_t + sigma[jj]*sqrt(delta_t)*Z));
			//X[m*b*(jj)+m*(j)+(i)]=Xi +  (r-delta[jj]-0.5*pow(sigma[jj], 2))*delta_t + sigma[jj]*sqrt(delta_t)*Z; 
			*three_dim_index(X, i, j, jj, m, b, num_assets)=Xi +  (r-delta[jj]-0.5*pow(sigma[jj], 2))*delta_t + sigma[jj]*sqrt(delta_t)*Z;
			//nodevector.push_back(Xj);
		}	
	//	myvector.push_back(nodevector);
	}
	}

//X.push_back(myvector);

}

//std::cout<<"after loop"<<std::endl;
meshweights(W,  m, b, sigma, delta, r, delta_t, X, num_assets, weight_denominator);
//std::cout<<"after"<<std::endl;
/*
//Weights generation for-loop 
//NOTE: W^i_(j,k) IS REPRESENTED AT W[i][k][j] where k is at step i+1 and j is at step i.
for(int I=0; I<m; I++){
//std::cout<<I<<std::endl;
//dim2temp.clear();//temporary vector
	
	if(I==0){
		for(int k=0; k<b; k++){
        	//dim1temp.clear();
			for(int j=0; j<b; j++){

				if(j==0){
					//W[m*b*(j)+m*(k)+(I)]=1;
					*three_dim_index(W, I, k, j, m, b)=1;
				}// all weights from the starting node are equal to 1

				else{
					//W[m*b*(j)+m*(k)+(I)]=0;
					*three_dim_index(W, I, k, j, m, b)=0;
				}
			}


		//dim1temp.push_back(w);
		//dim2temp.push_back(dim1temp);
	//std::cout<<"w1="<<w<<std::endl;
		}
	}


	if(I>0){

		for(int k=0; k<b; k++){	
		dim1temp.clear();
		sortvector.clear();
	//std::cout<<wdenominator<<std::endl;
		wdenominator=0;
	//std::cout<<wdenominator<<std::endl;
	//std::cout<<"k="<<k<<std::endl;
			for(int j=0; j<b; j++){
			//std::cout<<j<<std::endl;	
				w=1;
				//w=0; //set w to 1 since it will be equal to a product
				for(int jj=0; jj<num_assets; jj++){
//std::cout<< w<<std::endl;
//std::cout<<jj<<"\t"<<num_assets<<"\t"<<X[I-1][j][jj]<<"\t"<<X[I][k][jj]<<"\t"<<sigma[jj]<<"\t"<<delta[jj]<<"\t"<<r<<"\t"<<delta_t<<std::endl;
					
					//w = w + log(density(X[I-1][j][jj], X[I][k][jj], sigma[jj], r, delta[jj], delta_t));//step 1 in X is X[0] step 1 in W is W[1]	
					//w = w * density(X[I-1][j][jj], X[I][k][jj], sigma[jj], r, delta[jj], delta_t);
					//w = w * density(X[m*b*(jj)+m*(j)+(I-1)], X[m*b*(jj)+m*(k)+(I)], sigma[jj], r, delta[jj], delta_t);
					w = w * density(*three_dim_index(X, (I-1), j, jj, m, b), *three_dim_index(X, I, k, jj, m, b), sigma[jj], r, delta[jj], delta_t);
					//std::cout<<jj<<"\t"<<w<<"\t"<<density(X[I-1][j][jj], X[I][k][jj], sigma[jj], r, delta[jj], delta_t)<<std::endl;
					}
			//w = exp(w);
			dim1temp.push_back(w);
			sortvector.push_back(w);
				
			//wdenominator+=w; //this generates the denominator value in the weights formula
			//std::cout<<j<<"\t"<<"DENOM="<<wdenominator<<"\t"<<"exp(LOG(W))="<< w<<std::endl;
		
                                                                                                                      
			}
			std::sort(sortvector.begin(), sortvector.end());
			wdenominator=kahansum(sortvector);
			//	for(int sortvec=0; sortvec<b; sortvec++){
			//		wdenominator+=sortvector[sortvec];
		//	std::cout<<std::setprecision(15)<<sortvec<<"\t"<< wdenominator <<"\t"<<sortvector[sortvec]<< std::endl;
			//	}
			//wdenominator=log(wdenominator);
		//	wdenominator=exp(wdenominator);
			//devide each element by the denominator
			for(int t=0; t<b; t++){
		//	std::cout<<dim1temp[t]<<"\t"<<wdenominator<<std::endl; 
			
			//W[m*b*(t)+m*(k)+(I)]=(((double)b)*(dim1temp[t]))/wdenominator;
			*three_dim_index(W, (I), k, t, m, b)=(((double)b)*(dim1temp[t]))/wdenominator;
			
		//	dim1temp[t]=dim1temp[t]-wdenominator;		
		//	dim1temp[t]=((double)b)*exp(dim1temp[t]);
		//	std::cout<<dim1temp[t]<<std::endl;
		//	}
		//	double Sumcheck=0;	
		//	for(int sumcheck=0;sumcheck<b;sumcheck++){
		//	Sumcheck+=dim1temp[sumcheck];
		//	}	
		//	std::cout<<Sumcheck<<std::endl;
		//dim2temp.push_back(dim1temp); //dim1 is full therefore we add it onto dim2 vector
	//	}	
	
//	}

//W.push_back(dim2temp); //mesh weights matrix
}
*/
/*
std::cout<<"W[0][0][0]="<<W[0][0][0]<<std::endl;                                                                                                                                 
std::cout<<"W[0][1][0]="<<W[0][1][0]<<std::endl;
std::cout<<"W[1][0][0]="<<W[1][0][0]<<std::endl;
std::cout<<"W[1][1][0]="<<W[1][1][0]<<std::endl;
std::cout<<"W[1][0][1]="<<W[1][0][1]<<std::endl;
std::cout<<"W[1][1][1]="<<W[1][1][1]<<std::endl;
*/
//some weights checking
double check=0;
//check all the weights from X0 are 1
for(int e=0; e<b; e++){
if(*three_dim_index(W, 0, e, 0, m, b, b)!=1){
std::cout<<"there is an error with the weights. check that W[0][k][0]'s =1"<<std::endl;
}
}
//check that the weights going into a node sum to 1
for(int q=1; q<m; q++){ 
	for(int a=0; a<b; a++){
		check=0;
		for(int E=0; E<b; E++){
			//check+=W[m*b*(E)+m*(a)+(q)];
			check+=*three_dim_index(W, (q), a, E, m, b, num_assets);
		}
	}
}

V_0=MeshEstimator(strike, r, delta_t, b, m, X, W, V, asset_amount, payoff, num_assets);//high bias option price
Vvector.push_back(V_0);//vector containing high bias option prices
Vtotal_sum+=V_0;

std::cout<<"High Bias price (V_0) for mesh iteration "<<iterator<<" is "<<V_0<<std::endl;

//average over path estimators

/*
v_sum=0;
for(int f=0; f<Path_estimator_iterations; f++){
v_sum=PathEstimator(strike, r, delta_t, b,  m, sigma, delta, X0, X, W, V, asset_amount, payoff, num_assets);
}
*/
//v_0=(1/double(Path_estimator_iterations))*v_sum;
v_0=PathEstimator(strike, r, delta_t, b,  m, sigma, delta, X0, X, weight_denominator, V, asset_amount, num_assets, Path_estimator_iterations);
vvector.push_back(v_0);
vtotal_sum+=v_0;

std::cout<<"Low Bias price (v_0) for mesh iteration "<<iterator<<" is "<<v_0<<std::endl;


}//this is the end of the loop over the whole process.
print_high_payoff(b, m, X, V, asset_amount,W);
//Calculate V(N) and v(N)
V_0=(1/double(N))*Vtotal_sum;
v_0=(1/double(N))*vtotal_sum;

//calculate errors
double std_div_V=0, std_div_v=0, squaresumV=0, squaresumv=0, Verror=0, verror=0;

for(int h=0; h<N; h++){
squaresumV+=(Vvector[h]-V_0)*(Vvector[h]-V_0);
squaresumv+=(vvector[h]-v_0)*(vvector[h]-v_0);
}
std_div_V=sqrt((1/double(N))*squaresumV); //standard deviation of V
std_div_v=sqrt((1/double(N))*squaresumv); //standard deviation of v

Verror=quantile*std_div_V*(1/sqrt(double(N)));
verror=quantile*std_div_v*(1/sqrt(double(N)));

std::cout<<"V(N)_0="<<V_0<<"\t"<<"V error="<<Verror<<std::endl;
std::cout<<"v(N)_0="<<v_0<<"\t"<<"v error="<<verror<<std::endl;


std::ofstream outFile("results.txt", std::ios_base::app | std::ios_base::out);

outFile << N <<"\t"<< b <<"\t"<< Path_estimator_iterations<<"\t"<< V_0 <<"\t"<< v_0 <<"\t"<< Verror+V_0 <<"\t"<< v_0-verror << std::endl;

outFile.close();

delete[] X;
delete[] W;
delete[] V;
delete[] weight_denominator;
return 0;


}
示例#6
0
void game::run()
{
	//MissileDesc projectile(*this);
	towerDesc towr(this);

	std::string txt;

	std::string txt2 = "Life:";

	std::string txt3 = "Money:";

	std::string main = "Cam Pos";

	std::string txt4 = "Game Over";

	std::list<SceneObject *> troll;

	endgame = false;
	mouseUp = false;

	float dir = 0.0f;

	float spot_dir = 45.0f;
    float aspect_time = 0.0f;

	towerCount = 0;
	cost = 0;

	life = 20;
	money = 10;
	quit = false;
	cameraRestricted = false;
	
	selected_tower = "";

	std::stringstream ss2 (std::stringstream::in | std::stringstream::out);
	std::stringstream ss3 (std::stringstream::in | std::stringstream::out);

	/*GUI app;
	int retval = app.main(args);

	if (retval == 0)
	{
		return retval;
	}*/


	Quaternionf camera_orientation(55.0f, 0.0f, 0.0f, angle_degrees, order_YXZ);
		
	clan::OpenGLWindowDescription opengl_desc;
	opengl_desc.set_version(3, 2, false);
	clan::OpenGLTarget::set_description(opengl_desc);

	//Scene test;
	//clan::SceneCamera camera(test);
	//DisplayWindowDescription innerwindow("Hello World", Size(640, 480), true);
	//innerwindow.set_allow_resize(true);
	//innerwindow.set_fullscreen(true);

	clan::DisplayWindowDescription win_desc;
	win_desc.set_allow_resize(true);
	win_desc.set_title("Main");
	win_desc.set_size(clan::Size( 1100, 900 ), false);
	DisplayWindow window(win_desc);	
	//DisplayWindow window("main", 1200, 900, false, true);	
	//window.maximize();
	//DisplayWindow window(innerwindow);

	Rect viewport = window.get_viewport();

	GraphicContext gc = window.get_gc();

	ResourceManager resources;
	SceneCache::set(resources, std::shared_ptr<SceneCache>(new AppSceneCache()));

	ResourceManager sound_resources = XMLResourceManager::create(XMLResourceDocument("../Resources/resources.xml"));
	sound_resources_=&sound_resources;

	std::string shader_path = "../Resources/Scene3D";

	Scene scene(gc, resources, shader_path);

	sceneHolder = &scene;

	SceneCamera camera(scene);
	scene.set_camera(camera);
	scene.set_viewport(gc.get_size());

	camera.set_orientation(camera_orientation);
	camera.set_position(Vec3f(0.0f, 40.0f, down));

	Canvas canvas(window);

	image_hp = Image(canvas, "../Resources/Images/heart.png");
	image_hp.set_alignment(origin_center);
	image_hp.set_scale(0.07, 0.07);

	image_coin = Image(canvas, "../Resources/Images/coin.png");
	image_coin.set_alignment(origin_center);
	image_coin.set_scale(0.3, 0.3);


	GUIWindowManagerDirect direct(window, canvas);

	GUIManager maingui(direct, "../Resources");

	GUIComponent *win_comp = new GUIComponent(&maingui, win_desc, "");

	radial_menu = new RadialMenu(win_comp);

	radial_menu->func_selected.set(this, &game::on_radial_menu_itemselected);

	//GameComponent game_component(viewport, &maingui);

	/*Rect toolbar_rect = Rect((viewport.get_width() - 448) / 2, viewport.bottom - 56, (viewport.get_width() - 448) / 2 + 448, viewport.bottom);
	Toolbar toolbar(toolbar_rect, &game_component);	// GameComponent is the "desktop" that the toolbar sits on, as an owner

	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell1.png"), Sprite(canvas, "../Resources/Images/spell1_selected.png"), Sprite(canvas, "../Resources/Images/spell1_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell2.png"), Sprite(canvas, "../Resources/Images/spell2_selected.png"), Sprite(canvas, "../Resources/Images/spell2_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell3.png"), Sprite(canvas, "../Resources/Images/spell3_selected.png"), Sprite(canvas, "../Resources/Images/spell3_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell4.png"), Sprite(canvas, "../Resources/Images/spell4_selected.png"), Sprite(canvas, "../Resources/Images/spell4_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell5.png"), Sprite(canvas, "../Resources/Images/spell5_selected.png"), Sprite(canvas, "../Resources/Images/spell5_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell6.png"), Sprite(canvas, "../Resources/Images/spell6_selected.png"), Sprite(canvas, "../Resources/Images/spell6_clicked.png"));
	toolbar.add_item(Sprite(canvas, "../Resources/Images/spell7.png"), Sprite(canvas, "../Resources/Images/spell7_selected.png"), Sprite(canvas, "../Resources/Images/spell7_clicked.png"));
	*/

	InputDevice keyboard = window.get_ic().get_keyboard();
	InputDevice mouse = window.get_ic().get_mouse();
	clan::Font font(canvas, "Tahoma", 30); // The clan prefix is required on linux due to a namespace conflict

	SceneModel plane(gc, scene, "plane");
	SceneModel box(gc, scene, "box");
	SceneModel tower(gc, scene, "tower");
	SceneModel gate(gc,scene,"gate");

	SceneObject object(scene, plane, Vec3f(0.0f, 0.0f, 0.0f));
	
	object.rotate(180.0f, 0.0f, 0.0f);

	scene.show_skybox_stars(false);

	/*SceneObject box0(scene, tower, Vec3f(20.0f, 5.0f, 0.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ));
	SceneObject box1(scene, tower, Vec3f(-20.0f, 5.0f, 0.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ));
	SceneObject box2(scene, tower, Vec3f(0.0f, 5.0f, 20.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ));
	SceneObject box3(scene, tower, Vec3f(0.0f, 5.0f, -20.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ));
	SceneObject tower[10];*/

	SceneObject theGate(scene, gate, Vec3f(-75.0f,5.0f,60.0f), Quaternionf(0.0f,0.0f,0.0f,angle_degrees,order_YXZ));
	theGate.set_scale(Vec3f(1.0f,2.0f,2.0f));

	std::vector<SceneLight> omni_lights;
	for (int i = 0; i < 4; i++)
	{
		SceneLight omni(scene);
		omni.set_type(SceneLight::type_omni);
		omni.set_color(Vec3f(0.05f));
		omni.set_position(Quaternionf(45.0f, 45.0f + i * 90.0f, 0.0f, angle_degrees, order_YXZ).rotate_vector(Vec3f(0.0f, 0.0f, -100.0f)));
		omni.set_attenuation_end(200.0f);
		omni.set_ambient_illumination(0.025f);

		omni_lights.push_back(omni);
	}

	SceneLight spot(scene);
    spot.set_type(SceneLight::type_spot);
    spot.set_orientation(Quaternionf(45.0f, 45.0f, 0.0f, angle_degrees, order_YXZ));
    spot.set_position(spot.get_orientation().rotate_vector(Vec3f(-55.0f, 90.0f, -550.0f)));
	//spot.set_position(Vec3f(-250, 100, -430));
    spot.set_color(Vec3f(1.0f, 1.0f, 0.8f));
    spot.set_falloff(45.0f);
    spot.set_hotspot(15.0f);
    spot.set_attenuation_start(150.0f);
    spot.set_attenuation_end(1500.0f);
    spot.set_shadow_caster(true);
    spot.set_rectangle_shape(false);
	//spot.set_ambient_illumination(true);
    spot.set_aspect_ratio(1.0f);

	/*SceneLight spot(scene);
    spot.set_type(SceneLight::type_spot);
    spot.set_orientation(Quaternionf(30.0f, 30.0f, 0.0f, angle_degrees, order_YXZ));
    spot.set_position(spot.get_orientation().rotate_vector(Vec3f(0.0f, 0.0f, -100.0f)));
    spot.set_color(Vec3f(1.0f, 1.0f, 0.8f));
    spot.set_falloff(45.0f);
    spot.set_hotspot(15.0f);
    spot.set_attenuation_start(20.0f);
    spot.set_attenuation_end(200.0f);
    spot.set_shadow_caster(true);
    spot.set_rectangle_shape(false);
    spot.set_aspect_ratio(1.0f);*/

    /*SceneLight spot2(scene);
    spot2.set_type(SceneLight::type_spot);
    spot2.set_position(Vec3f(0.0f, 100.0f, 0.0f));
    spot2.set_color(Vec3f(1.0f, 1.0f, 1.0f) * 3.0f);
    spot2.set_falloff(35.0f);
    spot2.set_hotspot(30.0f);
    spot2.set_attenuation_start(20.0f);
    spot2.set_attenuation_end(130.0f);
    spot2.set_shadow_caster(true);
    spot2.set_rectangle_shape(false);
    spot2.set_ambient_illumination(0.025f);*/

	wm.NodeArray[0].setPos(75.0f,1.25f,0.0f);
	wm.NodeArray[1].setPos(-60.0f,1.25f,0.0f);
	wm.NodeArray[2].setPos(-55.0f,1.25f,-65.0f);
	wm.NodeArray[3].setPos(60.0f,1.25f,-60.0f);
	wm.NodeArray[4].setPos(55.0f,1.25f,65.0f);
	wm.NodeArray[5].setPos(-80.0f,1.25f,60.0f);
	
	Physics3DShape box_shape = Physics3DShape::box(Vec3f(5.0f));
	Physics3DShape plane_shape = Physics3DShape::box(Vec3f(75.0f, 1.0f, 75.0f));
	Physics3DShape sphere_shape = Physics3DShape::sphere(2.0f);

	Physics3DObject phys_plane(physics_world, plane_shape, Vec3f(0.0f, -0.5f, 0.0f));

	/*Physics3DObject phys_box0(physics_world, box_shape, Vec3f(20.0f, 5.0f, 0.0f), box0.get_orientation());
	Physics3DObject phys_box1(physics_world, box_shape, Vec3f(-20.0f, 5.0f, 0.0f), box1.get_orientation());
	Physics3DObject phys_box2(physics_world, box_shape, Vec3f(0.0f, 5.0f, 20.0f), box2.get_orientation());
	Physics3DObject phys_box3(physics_world, box_shape, Vec3f(0.0f, 5.0f, -20.0f), box3.get_orientation());
	Physics3DObject phys_box[10];*/

	Physics3DSweepTest sweep_test(physics_world);

	Physics3DRayTest raycast(physics_world);

	Slot slot_keyboard_key_down	= (window.get_ic().get_keyboard()).sig_key_down()	.connect(this,&game::on_key_down);
	Slot slot_keyboard_key_up	= (window.get_ic().get_keyboard()).sig_key_up()		.connect(this,&game::on_key_up);
	Slot slot_mouse_moved		= (window.get_ic().get_mouse()).sig_pointer_move()	.connect(this,&game::on_pointer_move);
	Slot slot_mouse_down			= (window.get_ic().get_mouse()).sig_key_down()		.connect(this,&game::on_pointer_down);
	Slot slot_mouse_up			= (window.get_ic().get_mouse()).sig_key_up()		.connect(this,&game::on_pointer_up);

	//________________________________________________________________
	//											           S O U N D S

	total_channels=3;
	current_channel=1;
	SoundBuffer music = SoundBuffer::resource("Music1",sound_resources);
	music.set_volume(0.3f);

	sound_session1.play();
	sound_session2.play();
	sound_session3.play();

	total_samples = 6;
	samples.resize(total_samples);
	samples[0] = SoundBuffer::resource("Explosion1",sound_resources);
	samples[1] = SoundBuffer::resource("Explosion2",sound_resources);
	samples[2] = SoundBuffer::resource("Hurt1",sound_resources);
	samples[3] = SoundBuffer::resource("Hurt2",sound_resources);
	samples[4] = SoundBuffer::resource("Powerup1",sound_resources);
	samples[5] = SoundBuffer::resource("Shoot1",sound_resources);
	
	for(int i = 0; i<total_samples; i++)
	{
		samples[i].set_volume(0.3f);
	}
	
	SoundBuffer_Session music_session = music.prepare();
	music_session_ = &music_session;

	music_session.set_looping(true);
	music_session.play();
	is_music_muted = false;

	/********Enemies(Jasper)************************/
	SceneObject enemyobj[30];
	wm.spawnCreeps();
	for(int i = 0; i < 30; i ++)
	{
		enemyobj[i] = SceneObject(scene, box);
		enemyobj[i].set_scale(Vec3f(0.25f));
		wm.enemyArray[i].setEnemyObject(&enemyobj[i]);
	}
	/***************************************/

	ElapsedTimer elapsed_timer;

	while (!quit)
	{
		float time_elapsed = elapsed_timer.seconds_elapsed();

		/*spot_dir = std::fmod(spot_dir + time_elapsed * 30.0f, 90.0f);
		aspect_time = std::fmod(aspect_time + time_elapsed * 0.2f, 2.0f);

		spot2.set_aspect_ratio(clamp(aspect_time >= 1.0f ? 2.0f - aspect_time : aspect_time, 0.1f, 1.0f));
		spot2.set_orientation(Quaternionf(65.0f + (spot_dir >= 45.0f ? 90.0f - spot_dir : spot_dir), 60.0f, dir * 4.0f, angle_degrees, order_YXZ));
		*/
		// Draw with the canvas:
		/*canvas.clear(Colorf::cadetblue);
		canvas.draw_line(0, 110, 640, 110, Colorf::yellow);
		font.draw_text(canvas, 100, 100, "Hello World!", Colorf::lightseagreen);
		// Draw any remaining queued-up drawing commands oQAn canvas:
		canvas.flush();*/

		if (!endgame)
		{
			if (mouse.get_x() <= 0 && !cameraRestricted)
			{
				mouse.set_position(0, mouse.get_y());
				camera.set_position(camera.get_position()+Vec3f(-mouse_move_speed, 0.0f, 0.0f));
				/*canvas.clear();
				font.draw_text(canvas, 100, 100, "x=0", Colorf::lightseagreen);
				canvas.flush();*/
				//window.flip();
			}
			if (mouse.get_y() <= 0 && !cameraRestricted)
			{
				mouse.set_position(mouse.get_x(), 0);
				camera.set_position(camera.get_position()+Vec3f(0.0f, 0.0f, mouse_move_speed));
				/*canvas.clear();
				font.draw_text(canvas, 100, 100, "y=0", Colorf::lightseagreen);
				canvas.flush();*/
				//window.flip();
			}
			if (mouse.get_x() >= window.get_gc().get_width()-1 && !cameraRestricted)
			{
				mouse.set_position(window.get_gc().get_width()-1, mouse.get_y());
				camera.set_position(camera.get_position()+Vec3f(mouse_move_speed, 0.0f, 0.0f));
				/*canvas.clear();
				font.draw_text(canvas, 100, 100, "x=windowRight", Colorf::lightseagreen);
				canvas.flush();*/
				//window.flip();
			}
			if (mouse.get_y() >= window.get_gc().get_height()-1 && !cameraRestricted)
			{
				mouse.set_position(mouse.get_x(), window.get_gc().get_height()-1);
				camera.set_position(camera.get_position()+Vec3f(0.0f, 0.0f, -mouse_move_speed));
				/*canvas.clear();
				font.draw_text(canvas, 100, 100, "y=windowBottom", Colorf::lightseagreen);
				canvas.flush();*/
				//window.flip();
			}

			if (mouseUp)
			{
				if (selected_tower == "Tower 1")
				{
					towr.set_type(towr.t_bullet);
					cost = 10;
				}
				else if (selected_tower == "Tower 2")
				{
					towr.set_type(towr.t_energy);
					cost = 15;
				}
				else if (selected_tower == "Tower 3")
				{
					towr.set_type(towr.t_rocket);
					cost = 20;
				}

				scene.unproject(mouse_pos, start, end);
				end *= 151;
				test = start + end;

				if (raycast.test(start, test))
				{
					if (towerCount < 10 && money >= cost)
					{
						towr.set_pos(Vec3f(raycast.get_hit_position().x, 5.0f, raycast.get_hit_position().z));
						towr.create(scene, tower, physics_world);

						money -= cost;
						towerCount++;
						cost = 0;
					}
				}
				mouseUp = false;
				//float x = mouse.get_x() - scene.world_to_projection().get_origin_x();
				//tower[0] = SceneObject(scene, box, Vec3f(camera.get_position().x, 5.0f, camera.get_position().z));
				//tower[0].set_position(Vec3f(0.0f, 5.0f, 0.0f));
				//window.flip();
				//canvas.clear(Colorf::cadetblue);
				/*canvas.draw_line(0, 110, 640, 110, Colorf::yellow);
				font.draw_text(canvas, 100, 100, "Hello World!", Colorf::lightseagreen);
				// Draw any remaining queued-up drawing commands oQAn canvas:
				canvas.flush();
				// Present the frame buffer content to the user:
				window.flip();*/
			}

			if (mouse.get_keycode(0))
			{
				
				//maingui.process_messages(0);
				//test.update();
				//show_radial_menu(mouse.get_position());
			}

			/*if (mouse.get_keycode(1))
			{
				scene.unproject(mouse.get_position(), start, end);
				end *= 151;
				Vec3f test = start + end;
				if (raycast.test(start, test))
				{
					Physics3DObject hit = raycast.get_hit_object();
					font.draw_text(canvas, 400, 100, "hit", Colorf::lightseagreen);
					//hit.set_position(Vec3f(0.0f, -10.0f, 0.0f));
					std::stringstream ss3 (std::stringstream::in | std::stringstream::out);
					ss3 << hit.get_position().y;
					txt3 = ss3.str();

					font.draw_text(canvas, 550, 100, txt3, Colorf::lightseagreen);
				}
				
				//projectile.set_pos(Vec3f(raycast.get_hit_position().x, 5.0f, raycast.get_hit_position().z));
				//projectile.fire(scene, box, physics_world);
			
				//canvas.clear(Colorf::white);
				//window.flip();
			}*/
			if (keyboard.get_keycode(keycode_control))
			{
				if (window.is_fullscreen())
				{
					//innerwindow.set_fullscreen(false);
					window.set_size(640, 480, true);
					window.restore();
				}
				else
					window.set_size(640, 480, false);
			}

			if (camera.get_position().x <= left)
			{
				camera.set_position(Vec3f(left, camera.get_position().y, camera.get_position().z));
			}
		
			if (camera.get_position().x >= right)
			{
				camera.set_position(Vec3f(right, camera.get_position().y, camera.get_position().z));
			}
		
			if (camera.get_position().z >= top)
			{
				camera.set_position(Vec3f(camera.get_position().x, camera.get_position().y, top));
			}

			if (camera.get_position().z <= down)
			{
				camera.set_position(Vec3f(camera.get_position().x, camera.get_position().y, down));
			}

			/*if(objects_for_deletion.size()>0)
			{
				std::list<Gameobject *>::iterator it;
				for(it=objects_for_deletion.begin(); it!= objects_for_deletion.end(); ++it)
				{
					delete (*it);
					//towerCount--;
				}

				objects_for_deletion.clear();
			}*/

			if(towerObjects.size()>0)
			{
				std::vector<Gameobject *>::iterator it;
				int counter = 0;
				for(it=towerObjects.begin(); it!= towerObjects.end(); ++it)
				{
					towerObjects.at(counter)->update(time_elapsed, wm.enemyArray, 30);
					counter++;
				}
			}

			if(missileObjects.size()>0)
			{
				std::list<Gameobject *>::iterator it;
				for(it=missileObjects.begin(); it!= missileObjects.end();)
				{
					//if (!(*it)->checkActive())
					(*it)->update(time_elapsed, wm.enemyArray);

					if ((*it)->checkActive())
					{
						delete(*it);
						it = missileObjects.erase(it);						
					}
					else
						it++;
				}
			}

			/*******Enemies(Updates)************************/
			wm.Update(1);
			//time_lasttime = time_elapsed;

			if(wm.life > 0)
			{
				// Put a screen here
				life -= wm.life;
				wm.life = 0;
			}

			if (wm.currLevel == 3)
			{
				endgame = true;
			}
			/***********************************************/

			//scene.update(gc, time_elapsed);

			txt3 = ":";
			ss3.str("");
			ss3.clear();
			ss3 << money;
			txt3 += ss3.str();

			font.draw_text(canvas, 550, 50, txt3, Colorf::lightseagreen);

			if (life < 0)
			{
				endgame = true;
			}

			scene.render(gc);

			/*canvas.clear(clan::Colorf(0.0f,0.0f,0.0f));
			std::stringstream ss (std::stringstream::in | std::stringstream::out);
			ss << game_time.get_time_elapsed();
			std::string troll = ss.str();
			font.draw_text(canvas, 100, 100, troll, Colorf::lightseagreen);*/
			//canvas.clear(clan::Colorf(0.0f,0.0f,0.0f));
			std::stringstream ss (std::stringstream::in | std::stringstream::out);
			ss << scene.world_to_projection().get_origin_x();
			txt = ss.str();

			txt2 = ":";
			ss2.str("");
			ss2.clear();
			ss2 << life;
			txt2 += ss2.str();

			font.draw_text(canvas, 150, 50, txt2, Colorf::lightseagreen);

			//maingui.process_messages(0);

			/*font.draw_text(canvas, 0, 100, main, Colorf::lightseagreen);
			font.draw_text(canvas, 150, 100, txt, Colorf::lightseagreen);
			font.draw_text(canvas, 250, 100, txt2, Colorf::lightseagreen);
			canvas.draw_line(0, 110, 640, 110, Colorf::yellow);*/

			maingui.render_windows();
			
			image_hp.draw(canvas, 100, 45); 
			image_coin.draw(canvas, 500, 45);
			
			window.flip();

			// Read messages from the windowing system message queue, if any are available:
			KeepAlive::process();
		}

		else
		{
			//maingui.render_windows();
			canvas.clear(Colorf::black);

			font.draw_text(canvas, 450, 400, txt4, Colorf::lightseagreen);

			window.flip();

			// Read messages from the windowing system message queue, if any are available:
			KeepAlive::process();
		}
	}
}
void makeUnfoldingMatrix(const TString input, 
			 const TString triggerSetString="Full2011DatasetTriggers",
			 int systematicsMode = DYTools::NORMAL, 
			 int randomSeed = 1, double reweightFsr = 1.0, 
			 double massLimit = -1.0, int debugMode=0)
{

  // check whether it is a calculation
  if (input.Contains("_DebugRun_")) {
    std::cout << "plotDYUnfoldingMatrix: _DebugRun_ detected. Terminating the script\n";
    return;
  }

  // normal calculation
  gBenchmark->Start("makeUnfoldingMatrix");

  if (systematicsMode==DYTools::NORMAL)
    std::cout<<"Running script in the NORMAL mode"<<std::endl;
  else if (systematicsMode==DYTools::RESOLUTION_STUDY)
    std::cout<<"Running script in the RESOLUTION_STUDY mode"<<std::endl;
  else if (systematicsMode==DYTools::FSR_STUDY)
    std::cout<<"Running script in the FSR_STUDY mode"<<std::endl;
  else if (systematicsMode==DYTools::ESCALE_RESIDUAL)
    std::cout << "Running script in the ESCALE_RESIDUAL mode\n";
  else { 
    std::cout<<"requested mode not recognized"<<std::endl;
    assert(0);
  }

  if (debugMode) std::cout << "\n\n\tDEBUG MODE is ON\n\n";
  
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
//   Bool_t doSave  = false;    // save plots?
  TString format = "png";   // output file format

  vector<TString> fnamev;   // file names   
  vector<TString> labelv;   // legend label
  vector<Int_t>   colorv;   // color in plots
  vector<Int_t>   linev;    // line style
  vector<Double_t> xsecv;
  vector<Double_t> lumiv;
  TString          dirTag;
  TString          escaleTag; // Energy scale calibrations tag

  if (1) {
    MCInputFileMgr_t mcInp; // avoid errors from empty lines
    if (!mcInp.Load(input)) {
      std::cout << "Failed to load mc input file <" << input << ">\n";
      return;
    }
    fnamev=mcInp.fileNames();
    labelv=mcInp.labels();
    colorv=mcInp.colors();
    linev=mcInp.lineStyles();
    xsecv=mcInp.xsecs();
    lumiv=mcInp.lumis();
    dirTag=mcInp.dirTag();
    escaleTag=mcInp.escaleTag();
  }
  else {
  ifstream ifs;
  ifs.open(input.Data());
  assert(ifs.is_open());
  string line;
  Int_t state=0;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(state == 0){
      dirTag = TString(line);
      getline(ifs,line);
      stringstream ss3(line); ss3 >> escaleTag;
      state++;
      continue;
    }else{
      string fname;
      Int_t color, linesty;
      stringstream ss(line);
      Double_t xsec;
      ss >> fname >> xsec >> color >> linesty;
      string label = line.substr(line.find('@')+1);
      fnamev.push_back(fname);
      labelv.push_back(label);
      colorv.push_back(color);
      linev.push_back(linesty);
      xsecv.push_back(xsec);
      lumiv.push_back(0);
    }
  }
示例#8
0
文件: test.cpp 项目: jmg217/thesis
int main(){

std::ifstream setting( "settings.txt" );
std::string line;
std::vector<std::string> settings;
int linenumber=0;
while(std::getline( setting, line))
    {
          if(linenumber%2==1)
              settings.push_back(line);
          linenumber++;
    }
setting.close();

double double_num;
int integer; 

std::vector < double > X0;
std::vector < double > delta;
std::vector <double> sigma;
std::vector <double > asset_amount;
std::istringstream ss(settings[0]);
std::string token;
while(std::getline(ss, token, ',')) 
    {
          X0.push_back(atof(token.c_str()));
    }

double T = atof(settings[1].c_str());
double m = atof(settings[2].c_str());
double delta_t=T/m;
int Rn;
double v_0, V_0, Z, Xi, Xj, w, wdenominator, v_sum, sum_Z=0, vtotal_sum=0, Vtotal_sum=0;
double r= atof(settings[3].c_str());

std::istringstream ss2(settings[4]);
while(std::getline(ss2, token, ','))
    {
        delta.push_back(atof(token.c_str()));
    }

std::istringstream ss3(settings[5]);
while(std::getline(ss3, token, ','))
    {
        sigma.push_back(atof(token.c_str()));
    }

double Path_estimator_iterations=atof(settings[6].c_str());
double strike=atof(settings[7].c_str());
int b=atoi(settings[8].c_str());
int N=atoi(settings[9].c_str());
double quantile=atof(settings[10].c_str());
int num_assets=atof(settings[11].c_str());

std::istringstream ss4(settings[12]);
while(std::getline(ss4, token, ','))
    {
        asset_amount.push_back(atof(token.c_str()));
    }


if(X0.size() != num_assets || sigma.size() != num_assets || delta.size() !=num_assets){
          std::cout<<"Either the starting price, volatility, number of assets or dividend yield was not specified for all assets"<<std::endl;
           exit (EXIT_FAILURE);
       }

std::cout<<"The parameters of this simulation are:"<<std::endl;
       //Print these values to screen 
for(integer=0; integer<X0.size(); integer++){
std::cout<<"Starting Price="<<X0[integer]<<std::endl;
}

std::cout<<"Time to expiry="<<T<<"\n"<<"Number of time steps="<<m<<"\n"<<"interest rate="<<r<<std::endl;

for(integer=0; integer<sigma.size(); integer++){
    std::cout<<"volatility="<<sigma[integer]<<std::endl;
}

for(integer=0; integer<asset_amount.size(); integer++){
    std::cout<<"asset amount="<<asset_amount[integer]<<std::endl;
}
for(integer=0; integer<delta.size(); integer++){
    std::cout<<"dividend yield="<<delta[integer]<<std::endl;
}
std::cout<<"number of iterations over path estimator="<<Path_estimator_iterations<<"\n"<<"strike  price="<<strike<<"\n"<<"number of nodes per time step="<<b<<"\n"<<"number mesh generations="<<N<<"\n"<<"Number of Assets="<<num_assets<<std::endl; 


}
示例#9
0
int main(int argc, char**argv){

  std::string input_file;
 std::string x_positions;
 std::string y_positions;
 int doFiber = 0;
 float table_x_reference = 200; //---- mm
 float table_y_reference = 350; //---- mm
 float table_x = 200; //---- mm
 float table_y = 350; //---- mm
 
 float w0 = 5.0;
 //---- configuration

 // setTDRStyle1(0,0,0,0);
 
//---- configuration

 int c;
 while ((c = getopt (argc, argv, "i:x:y:f")) != -1)
   switch (c)
     {
     case 'i': //---- input
       input_file = string(optarg);
       break;
     case 'x':
       x_positions = string(optarg);
       break;
     case 'y':
       y_positions = string(optarg);
       break;
     case 'f':
       doFiber = atoi(optarg);
       
     case '?':
       if (optopt == 'i' || optopt == 'x' || optopt == 'y'||optopt == 'f')
	 fprintf (stderr, "Option -%c requires an argument.\n", optopt);
       else if (isprint (optopt))
	 fprintf (stderr, "Unknown option `-%c'.\n", optopt);
       else
	 fprintf (stderr,
		  "Unknown option character `\\x%x'.\n",
		  optopt);
       return 1;
     default:
       exit (-1);
     }
 
 //  std::cout << " Table: " << std::endl;
 //  std::cout << "   x = " << table_x << " mm " << std::endl;
 //std::cout << "   y = " << table_y << " mm " << std::endl;
 
 
 //---- get vector of files
 
 std::vector<std::string> input_files_vector;
 std::vector<std::string> x_positions_vector;
 std::vector<std::string> y_positions_vector;
 
 std::stringstream ss(input_file);
 std::stringstream ss2(x_positions);
 std::stringstream ss3(y_positions); 
 
 cout<<"input files :"<<endl;
 
 std::string token_string;
  while(std::getline(ss, token_string, ',')) {
    std::cout << token_string << '\n';
    input_files_vector.push_back(token_string);
  }
 
  cout<<"x positions"<<endl;
 
  std::string token_string2;
  while(std::getline(ss2, token_string2, ',')) {
    std::cout << token_string2 << '\n';
    x_positions_vector.push_back(token_string2);
  }
  
  cout<<"y positions"<<endl;
  
  std::string token_string3;
  while(std::getline(ss3, token_string3, ',')) {
    std::cout << token_string3 << '\n';
    y_positions_vector.push_back(token_string3);
  }
  

  float x_tempval =GLOBAL_X;
  vector<float> x_pos;
 

 for (int i=0; i<x_positions_vector.size(); i++) 
   {
     char tab[1024];    //temp variable to use in sscanf                                                                                                                    
     strcpy(tab, x_positions_vector.at(i).c_str()); //copy the string into the array of charactars for use in sscanf       
     if (sscanf(tab,"%f",&x_tempval)!=1){
	 cout<<"can't read x_position of the "<<i<<"th input file"<<endl;
	 exit(0);}
       x_pos.push_back(x_tempval);
   }
     

  float y_tempval=GLOBAL_Y;
  vector<float> y_pos;
 

 for (int i=0; i<y_positions_vector.size(); i++) 
   {
     char tab[1024];    //temp variable to use in sscanf                                                                                                                    
     strcpy(tab, y_positions_vector.at(i).c_str()); //copy the string into the array of charactars for use in sscanf       
     if (sscanf(tab,"%f",&y_tempval)!=1){
	 cout<<"can't read y_position of the "<<i<<"th input file"<<endl;
	 exit(0);}
       y_pos.push_back(y_tempval);
   }

  TApplication* gMyRootApp = new TApplication("My ROOT Application", &argc, argv); 



  /*  TMultiGraph* Mg[8];
  char buffer[30];
  for (int k ; k<8;k++)
    {
      sprintf(buffer,"Mg%d",k);
      Mg[k]=new TMultiGraph (buffer,buffer);
    }
  */
  TH2F * histarray[8];

 
 
  char buffer[30];
  for (int k ; k<8;k++)
    {
      sprintf(buffer,"TG%d",k);
      histarray[k]=new TH2F ("buffer","buffer",64, -32, 32,64 , -32, 32);
    }
  


  for (int j=0;j<input_files_vector.size();j++){
    float shift_x=GLOBAL_X-x_pos.at(j);
    float shift_y=GLOBAL_Y-y_pos.at(j);
    cout<<"running_get_all_graphs"<<j<<"th time"<<endl;
    get_all_graphs(input_files_vector.at(j),shift_x,shift_y,histarray,j);
  }



  TCanvas* X_g = new TCanvas ("X_g","",800,600);
  TCanvas* Y_g = new TCanvas ("Y_g","",800,600);

  X_g->Divide(2,2);
  Y_g->Divide(2,2);
  
  X_g->cd(1)->SetGrid();
  histarray[0]->Draw("Colz");
  histarray[0]->GetXaxis()->SetTitle("Hodo1_x");
  histarray[0]->GetYaxis()->SetTitle("Calox_front-hodo1_x");
  gPad->Modified();
  
  X_g->cd(2)->SetGrid();
  histarray[1]->Draw("Colz");
  histarray[1]->GetYaxis()->SetTitle("Calox_front-hodo2_x");
  histarray[1]->GetXaxis()->SetTitle("Hodo2_x");
  gPad->Modified();
  
  X_g->cd(3)->SetGrid();
  histarray[2]->Draw("Colz");  
  histarray[2]->GetYaxis()->SetTitle("Hodo1_x");
  histarray[2]->GetYaxis()->SetTitle("Calox_back-hodo1_x");
  gPad->Modified();
  
  X_g->cd(4)->SetGrid();
  histarray[3]->Draw("Colz");
  histarray[3]->GetYaxis()->SetTitle("Calox_back-hodo2_x");
  histarray[3]->GetXaxis()->SetTitle("Hodo2_x");
  gPad->Modified();
    
  Y_g->cd(1)->SetGrid();   
  histarray[4]->Draw("Colz");
  histarray[4]->GetXaxis()->SetTitle("Hodo1_y");
  histarray[4]->GetYaxis()->SetTitle("Caloy_front-hodo1_y"); 
  gPad->Modified();
  
  Y_g->cd(2)->SetGrid();   
  histarray[5]->Draw("Colz");
  histarray[5]->GetXaxis()->SetTitle("Hodo2_y"); 
  histarray[5]->GetYaxis()->SetTitle("Caloy_front-hodo2_y"); 
  gPad->Modified();
 
  Y_g->cd(3)->SetGrid();   
  histarray[6]->Draw("Colz");
  histarray[6]->GetXaxis()->SetTitle("Hodo1_y");
  histarray[6]->GetYaxis()->SetTitle("Caloy_back-hodo1_y");
  gPad->Modified();


  Y_g->cd(4)->SetGrid();   
  histarray[7]->Draw("Colz");
  histarray[7]->GetYaxis()->SetTitle("Caloy_back-hodo2_y");
  histarray[7]->GetXaxis()->SetTitle("Hodo2_y");
  gPad->Modified();



  /*
  X_g->Divide(2,2);
  Y_g->Divide(2,2);

  X_g->cd(1)->SetGrid();
  Mg[0]->Draw("AP");
  Mg[0]->GetXaxis()->SetTitle("Hodo1_x");
  Mg[0]->GetYaxis()->SetTitle("Calox_front");
  gPad->Modified();
  X_g->cd(1)->BuildLegend();

  X_g->cd(2)->SetGrid();
  Mg[1]->Draw("AP");
  Mg[1]->GetYaxis()->SetTitle("Calox_front");
  Mg[1]->GetXaxis()->SetTitle("Hodo2_x");
  gPad->Modified();
  X_g->cd(2)->BuildLegend();
  
  X_g->cd(3)->SetGrid();
  Mg[2]->Draw("AP");  
  Mg[2]->GetYaxis()->SetTitle("Hodo1_x");
  Mg[2]->GetYaxis()->SetTitle("Calox_back");
  gPad->Modified();
  X_g->cd(3)->BuildLegend();
  
  X_g->cd(4)->SetGrid();
  Mg[3]->Draw("AP");
  Mg[3]->GetYaxis()->SetTitle("Calox_back");
  Mg[3]->GetXaxis()->SetTitle("Hodo2_x");
  gPad->Modified();
  X_g->cd(4)->BuildLegend();
    
  Y_g->cd(1)->SetGrid();   
  Mg[4]->Draw("AP");
  Mg[4]->GetXaxis()->SetTitle("Hodo1_y");
  Mg[4]->GetYaxis()->SetTitle("Caloy_front"); 
  gPad->Modified();
  Y_g->cd(1)->BuildLegend();
  
  Y_g->cd(2)->SetGrid();   
  Mg[5]->Draw("AP");
  Mg[5]->GetXaxis()->SetTitle("Hodo2_y"); 
  Mg[5]->GetYaxis()->SetTitle("Caloy_front"); 
  gPad->Modified();
  Y_g->cd(2)->BuildLegend();
 
  Y_g->cd(3)->SetGrid();   
  Mg[6]->Draw("AP");
  Mg[6]->GetXaxis()->SetTitle("Hodo1_y");
  Mg[6]->GetYaxis()->SetTitle("Caloy_back");
  gPad->Modified();
  Y_g->cd(3)->BuildLegend();

  Y_g->cd(4)->SetGrid();   
  Mg[7]->Draw("AP");
  Mg[7]->GetYaxis()->SetTitle("Caloy_back");
  Mg[7]->GetXaxis()->SetTitle("Hodo2_y");
  gPad->Modified();
  Y_g->cd(4)->BuildLegend();

  */

  gMyRootApp->Run(); 
  
}