void write_ntuple_to_file(){

    TFile ofile("conductivity_experiment.root","RECREATE");

    // Initialise the TNtuple
    TNtuple cond_data("cond_data",
                      "Example N-Tuple",
                      "Potential:Current:Temperature:Pressure");

    // Fill it randomly to fake the acquired data
    TRandom3 rndm;
    float pot,cur,temp,pres;
    for (int i=0;i<10000;++i){
        pot=rndm.Uniform(0.,10.);      // get voltage
        temp=rndm.Uniform(250.,350.);  // get temperature
        pres=rndm.Uniform(0.5,1.5);    // get pressure
        cur=pot/(10.+0.05*(temp-300.)-0.2*(pres-1.)); // current
// add some random smearing (measurement errors)
        pot*=rndm.Gaus(1.,0.01); // 1% error on voltage
        temp+=rndm.Gaus(0.,0.3); // 0.3 abs. error on temp.
        pres*=rndm.Gaus(1.,0.02);// 1% error on pressure
        cur*=rndm.Gaus(1.,0.01); // 1% error on current
// write to ntuple
        cond_data.Fill(pot,cur,temp,pres);
        }

    // Save the ntuple and close the file
    cond_data.Write();
    ofile.Close();
}
Beispiel #2
0
int main(int argc, char *argv[]) {

    TRandom3 *ran = new TRandom3(0);

    vektor b = new double[N];
    vektor x = new double[N];
//     vektor b = malloc_vektor(N);
//     vektor x = malloc_vektor(N);

//     matrix A = new double[N][N];
    matrix A = malloc_matrix(N);
    double dummy = 0.;

    for (int i=0; i<N; ++i) {
        for (int j=0; j<N; ++j) {
            dummy = ran->Uniform();
            A[i][j] = dummy;
            A[j][i] = dummy;
        }
        b[i] = ran->Uniform();
        x[i] = ran->Uniform();
    }

//     print_matrix(A);
    vektor x2 = malloc_vektor(N);
    x2 = vec_copy(cg(N, A, x, b, 1000, 1e-10, 0));
//     print_vektor(x2);

    delete[] b;
    delete[] x;
//     delete[] A;
    return 0;
}
Beispiel #3
0
int main(int argc, char *argv[]) {

    TRandom3 *ran = new TRandom3(0);

    double eta[N*N];
    double phi[N*N];
    geom_pbc();
    init_matrix();

    double dummy;
    for (int i=0; i<nvol; ++i){
      for (int j=0; j<nvol; ++j){
        dummy = ran->Uniform();
        A[i][j] = dummy;
        A[j][i] = dummy;
      }
      eta[i] = ran->Uniform();
    }

    cg(phi, eta, laplace, 1000, 1e-10, 1);
    
    for (int i=0; i<nvol; ++i){
      if (nn[0][i] == 1){
	  eta[i] = 0;
      }
    }
    cg(phi, eta, dirichlet, 1000, 1e-10, 1);

    return 0;
}
Beispiel #4
0
// Code from http://www.hongliangjie.com/2012/12/19/how-to-generate-gamma-random-variables/
// Parameter b could be theta...
double gsl_ran_gamma(const double a, const double b, TRandom3 &rand)
{
  
  if (a < 1)
  {
    double u = rand.Uniform(1);
    return gsl_ran_gamma(1.0 + a, b, rand) * pow (u, 1.0 / a);
  }

  double x, v, u;
  double d = a - 1.0 / 3.0;
  double c = (1.0 / 3.0) / sqrt (d);
  
  while (1) 
  {
    do 
    {
      x = rand.Gaus(0, 1.0);
      v = 1.0 + c * x;
    }
    while (v <= 0);
      
    v = v * v * v;
    u = rand.Uniform(1);

    if (u < 1 - 0.0331 * x * x * x * x) 
      break;

    if (log (u) < 0.5 * x * x + d * (1 - v + log (v)))
      break;
  }
    
  return b * d * v;
}
Beispiel #5
0
void histo_graph(TH1D *histo,TGraph *graph,Int_t N_to_fill) {
  Int_t N_Points=graph->GetN();
  Double_t x,y;

  Double_t y_min=0.0;
  Double_t y_max=0.0;
  Double_t x_min=0.0;
  Double_t x_max=0.0;

  for (Int_t i=0;i<N_Points;i++) {
    graph->GetPoint(i,x,y);
    if (y>y_max) y_max=y;
    if (x>x_max) x_max=x;
    if (y<y_min) y_min=y;
    if (x<x_min) x_min=x;
  }
  Double_t histo_x_min=histo->GetXaxis()->GetXmin();
  Double_t histo_x_max=histo->GetXaxis()->GetXmax();
  if (histo_x_min>x_min) x_min=histo_x_min;
  if (histo_x_max<x_max) x_max=histo_x_max;

  //reverse graph order if necessary
  TGraph graph2(N_Points);
  Double_t x0,xNm1;
  graph->GetPoint(0,x0,y);
  graph->GetPoint(N_Points-1,xNm1,y);
  if (xNm1<x0) {
    for (Int_t iPoint=0;iPoint<N_Points;iPoint++) {
      Double_t x,y;
      graph->GetPoint(N_Points-iPoint,x,y);
      graph2.SetPoint(iPoint,x,y);
    }
    graph=&graph2;
  }

  TRandom3 r;
  r.SetSeed(0);

  Int_t N_tried=0;
  Int_t N_filled=0;
  while (N_filled<N_to_fill) {
    N_tried++;
    //rejection method
    x=r.Uniform(x_min,x_max);
    y=r.Uniform(0.0,y_max);
    
    if (y<graph->Eval(x)) {
      histo->Fill(x);
      N_filled++;
    }
  }
  printf("x_max=%8.6g; x_min=%8.6g; y_max=%8.6g; N_filled=%d; N_tried=%d\n",x_max,x_min,y_max,N_filled,N_tried);
  Double_t norm=(x_max-x_min)*y_max*N_filled/N_tried;
  histo->Scale(norm/histo->Integral("width"));

}
//______________________________________________________________________________
// Fill y and error vectors with random points from TRandom3
void FillRandVectors(int nPoints, vector<double> &xVector, vector< double > &yVector, vector< double > &yErrorVector, int seed = 250, double lowerBound= 10, double upperBound= 20, double lowerErrorBound = 1, double upperErrorBound= 2)
{
	//Call TRandom3
	TRandom3 *jrand = new TRandom3(seed);
	for (int i = 0; i < nPoints; i++)
	{
		xVector.push_back(i);
		yVector.push_back(jrand->Uniform(lowerBound, upperBound));
		yErrorVector.push_back(jrand->Uniform(lowerErrorBound, upperErrorBound));
	}
	delete jrand;
}
Beispiel #7
0
void gtime2(Int_t nsteps = 200, Int_t np=5000) {
   if (np > 5000) np = 5000;
   Int_t color[5000];
   Double_t cosphi[5000], sinphi[5000], speed[5000];
   TRandom3 r;
   Double_t xmin = 0, xmax = 10, ymin = -10, ymax = 10;
   TGraphTime *g = new TGraphTime(nsteps,xmin,ymin,xmax,ymax);
   g->SetTitle("TGraphTime demo 2;X;Y");
   Int_t i,s;
   Double_t phi,fact = xmax/Double_t(nsteps);
   for (i=0;i<np;i++) { //calculate some object parameters
      speed[i]  = r.Uniform(0.5,1);
      phi       = r.Gaus(0,TMath::Pi()/6.);
      cosphi[i] = fact*speed[i]*TMath::Cos(phi);
      sinphi[i] = fact*speed[i]*TMath::Sin(phi);
      Double_t rc = r.Rndm();
      color[i] = kRed;
      if (rc > 0.3) color[i] = kBlue;
      if (rc > 0.7) color[i] = kYellow;
   }
   for (s=0;s<nsteps;s++) { //fill the TGraphTime step by step
      for (i=0;i<np;i++) {
         Double_t xx = s*cosphi[i];
         if (xx < xmin) continue;
         Double_t yy = s*sinphi[i];
         TMarker *m = new TMarker(xx,yy,25);
         m->SetMarkerColor(color[i]);
         m->SetMarkerSize(1.5 -s/(speed[i]*nsteps));
         g->Add(m,s);
      }
      g->Add(new TPaveLabel(.70,.92,.98,.99,Form("shower at %5.3f nsec",3.*s/nsteps),"brNDC"),s);
   }
   g->Draw();
}
Beispiel #8
0
int decroissance_pi(float _p_pi = 1.0){

  //	random.seed(60934386)
  TRandom3 rand;
  rand.SetSeed();
  //float _p_pi;
  //cout << "Entrez l'impulsion des pions (en GeV) : p = ";
  //cin >> _p_pi;

  double x[1000] = {0.0};
  double y[1000] = {0.0};

  for (int i=0;i<1000;i++){
    //double _theta_cm_mu = rand.Uniform(TMath::Pi());
    double _theta_cm_mu = TMath::ACos(gRandom->Uniform(2.0)-1.0);
    double _phi_cm_mu = rand.Uniform(2*TMath::Pi());
    if (i < 10){
      cout << "i: " << i <<  " th_cm_mu = " << _theta_cm_mu << endl;
    }
    double _theta_lab_mu = 0.0, _p_lab_mu = 0.0;
    ThetaLab_mu(_p_pi, _theta_cm_mu, _theta_lab_mu, _p_lab_mu);
    cout << "th_lab_mu= " << _theta_lab_mu << " _p_lab_mu= " << _p_lab_mu << endl;
    x[i] = 1000*_theta_lab_mu;
    y[i] = _p_lab_mu;
  }

  TGraph *graph = new TGraph(1000, x, y);
  graph->SetTitle("Theta vs p_{LAB}");

  graph->Draw("A*");

  return 0;

}
Beispiel #9
0
//put random numbers into some vectors
void FillRandVectors(vector< double > &xVector,
                     vector< double > &yVector,
					 int n)
{
    //Call TRandom3

    int seed = 23382;
    TRandom3 *jrand = new TRandom3(seed);
    for(int i =0; i<n; i=i+1)
    {
        xVector.push_back(jrand->Uniform(20.0));
        yVector.push_back(jrand->Uniform(5.0, 20.0));
    }
	TGraph *gr = LoadGraphFromVectors(xVector, yVector);

    delete jrand;
}
double Co3Rng::NEWstest(double theta){
	
	theta = 180*theta/TMath::Pi();
	double a = -0.8816/10000 /(1/theta  -0.1117/1000 * theta) - 0.1096 - 0.01966*TMath::Exp(-0.02040*theta);
	double b = 0.4169/100 /(1/theta  -0.9891/10000 * theta) + 4.0395 - 4.3118*TMath::Exp(0.9235/1000*theta);
	double bstrich = b  + 1/TMath::Ln10();
	double gamma = sqrt(-TMath::Ln10()*a), offset = 0.5*bstrich/a;
	double norm = TMath::Erf(gamma*(TMath::Log(100)+offset)) - TMath::Erf(gamma*offset);
	double r3 = rng->Uniform();
	return exp(TMath::ErfInverse(r3*norm+TMath::Erf(gamma*offset))/gamma-offset);
	
}
Beispiel #11
0
void TestBkg(){

  
  TFile * f = new TFile("./TestBkg.root","recreate");
  TTree * tree = new TTree("flt","data");
			
  LendaEvent *e = new LendaEvent();
  tree->Branch("Event",&e);
			
  TRandom3 * r = new TRandom3();
  for (int i=0;i<100000;i++){

    Double_t v =    r->Uniform()*30.0;

    e->pushTime(30);
    e->pushTime(30);
    
    e->pushTime(v);
    
    e->pushEnergy(1);
    e->pushEnergy(1);
    e->pushEnergy(1);

    e->pushLongGate(2);
    e->pushLongGate(2);
    e->pushLongGate(2);


    e->pushShortGate(2);
    e->pushShortGate(2);
    e->pushShortGate(2);

    e->pushCubicTime(e->times[0]);
    e->pushCubicTime(e->times[1]);
    e->pushCubicTime(e->times[2]);

    
    e->pushSoftwareCFD(1);    e->pushSoftwareCFD(1);    e->pushSoftwareCFD(1);
    
    
    e->Finalize();

    tree->Fill();
    e->Clear();
  }

  tree->Write();

  f->Close();
}
Beispiel #12
0
int main(int argc, char *argv[])
{
    std::auto_ptr<TRint> application(new TRint("histInMemory", 0, 0));

    TH1F *hist1 = new TH1F("hist1", "hist1", 50, 0, 10);
    TH1F *hist2 = new TH1F("hist2", "hist2", 50, 0, 10);
    TH1F *hist3 = new TH1F("hist3", "hist3", 50, 0, 10);
    TH1F *hist4 = new TH1F("hist4", "hist4", 50, 0, 10);
    TH1F *hist5 = new TH1F("hist5", "hist5", 50, 0, 10);

    {
        TRandom3 *random = new TRandom3(1);
        for(int i = 0; 10000 > i; ++i)
        {
            hist1->Fill(random->Gaus(5, 1));
            hist2->Fill(random->Poisson(5));
            hist3->Fill(random->Uniform(0, 10));
            hist4->Fill(random->Gaus(4, 1));
            hist5->Fill(random->Poisson(3));
        }
        delete random;
    }

    TFile *output = new TFile("output.root", "RECREATE");
    TDirectory *group1 = output->mkdir("group1");
    group1->cd();

    hist1->Write();
    hist2->Write();

    TDirectory *group2 = output->mkdir("group2");
    group2->cd();

    hist3->Write();
    hist4->Write();
    hist5->Write();

    delete output;

    application->Run(true);

    delete hist1;
    delete hist2;
    delete hist3;
    delete hist4;
    delete hist5;

    return 0;
}
Beispiel #13
0
//------------------------------------------------------------------------------
void generate_rndm_numbers(double* rnd_numbers,const unsigned int n_rnd_numbers,double min, double max){
/**
 * Generate between -MAX_RND and MAX_RND double numbers
 **/
  TRandom3 rndgen;
  double init = omp_get_wtime();    
  for (unsigned int i=0;i<n_rnd_numbers;++i){      
    rnd_numbers[i] = rndgen.Uniform(min,max);
//     std::cout << "o " << min << " " << max << " " << rnd_numbers[i] << std::endl;
  }
  double delta_t = omp_get_wtime() - init;
  std::cout << "\n*** " << n_rnd_numbers 
            << " numbers (" << min << "," << max<< ") generated in " 
            << delta_t << " s \n";

  }
void prova_uniform() {

  TRandom3 rndgen;
  const int imax = 1E8;
  const double pi = 4*TMath::ATan(1);
  TH1F* prova_hist = new TH1F("P", "Prova", 1000,1,0);
  TFile* out = new TFile("prova_uniform.root","RECREATE");

  for (int i = 0; i < imax; i++) {
    prova_hist->Fill(rndgen.Uniform(2*pi));
  }
  
  prova_hist->Write();
  out->Close();
  
}
Beispiel #15
0
		double permutationCore( IDataSet * data, IDataSet * mc, int iteration )
		{
			unsigned int nD = (unsigned) data->GetDataNumber();
			unsigned int nMC = (unsigned) mc->GetDataNumber();
			// Append the two datasets
			MemoryDataSet * dataClone = new MemoryDataSet( data->GetBoundary() );
			for ( unsigned int i = 0; i < nD;  i++ ) dataClone->AddDataPoint( data->GetDataPoint((int)i) );
			for ( unsigned int j = 0; j < nMC; j++ ) dataClone->AddDataPoint( mc  ->GetDataPoint((int)j) );

			TRandom3 * rand = new TRandom3((unsigned)iteration);

			// Need to get some empty version of the dataset
			MemoryDataSet * tempMC   = new MemoryDataSet( mc->GetBoundary() );
			MemoryDataSet * tempData = new MemoryDataSet( data->GetBoundary() );

			set<unsigned int> eventNotAccepted;
			for ( unsigned int i = 0; i < nD + nMC; i++ ) eventNotAccepted.insert(i);

			unsigned int count = 0;
			set<unsigned int>::iterator iter;
			while ( count < nD ) {
				unsigned int random = (unsigned int)rand->Uniform(0., nD + nMC);
				iter = find(eventNotAccepted.begin(), eventNotAccepted.end(), random);
				if ( iter != eventNotAccepted.end() ) {
					tempData->AddDataPoint( dataClone->GetDataPoint((int)random) );
					eventNotAccepted.erase(random);
					count++;
				}
			}

			for ( iter = eventNotAccepted.begin(); iter != eventNotAccepted.end(); ++iter) {
				tempMC->AddDataPoint( dataClone->GetDataPoint((int)*iter) );
			}
			double T = calculateTstatistic( tempData, tempMC );
			//delete rand;
			//delete tempMC;
			//delete tempData;
			//delete dataClone;
			return T;
		}
int main()
{
	// Manual input:
	if (true)
	{
		vector<KLV> gen(4); // pt eta phi m
		gen[1].p4.SetCoordinates(30,  1.0, 0.5, 0);
		gen[3].p4.SetCoordinates(25, -1.0, 2.5, 0);
		gen[2].p4.SetCoordinates(15,  2.1, 1.1, 0);
		gen[0].p4.SetCoordinates(10,  2.3, 1.0, 0);
		vector<KLV> rec(3);
		rec[2].p4.SetCoordinates(20,  1.3, 0.4, 0);
		rec[0].p4.SetCoordinates(18, -0.9, 2.2, 0);
		rec[1].p4.SetCoordinates(13,  2.2, 1.1, 0);
		test(gen, rec);
	}

	// Automatic input
	TRandom3 rnd;
	for (size_t i = 0; i < 4; ++i)
	{
		vector<KLV> gen, rec;
		// GEN stuff
		for (size_t j = 0; j < (size_t)rnd.Poisson(10); ++j)
		{
			gen.push_back(KLV());
			gen.back().p4.SetCoordinates(rnd.Uniform(5, 100), rnd.Gaus(0, 5), rnd.Uniform(-M_PI, +M_PI), rnd.Gaus(0, 10));
			// RECO efficiency
			if (rnd.Uniform(0, 1) > 0.05)
			{
				rec.push_back(KLV());
				rec.back().p4.SetCoordinates(
					gen.back().p4.pt() * fabs(rnd.Gaus(0.8, 0.1)),
					gen.back().p4.eta() * fabs(rnd.Gaus(1, 0.1)),
					gen.back().p4.phi() + rnd.Uniform(0, 0.1),
					gen.back().p4.mass() * rnd.Gaus(1, 0.1));
			}
		}
		// RECO noise
		for (size_t j = 0; j < (size_t)rnd.Poisson(5); ++j)
		{
			rec.push_back(KLV());
			rec.back().p4.SetCoordinates(rnd.Uniform(1, 10), rnd.Gaus(0, 5), rnd.Uniform(-M_PI, +M_PI), rnd.Gaus(0, 10));
		}
		test(gen, rec);
	}
}
Beispiel #17
0
void proSTEGvnwithnfv3()
{
  
  int mult = atoi(getenv("MULT"));

  int tot_num=50000;  //50k events
  double MeanMult=(double)mult;
  double RMSMult=10;
  
  int ifile = atoi(getenv("IFILE")); 

  //simple toy event generator
  //TFile f(Form("/lio/lfs/cms/store/user/qixu/flow/NewSTEG/pPbDataV205m%d/vndata_50k_%d.root",mult,ifile), "RECREATE","ROOT file with histograms & tree");
  TFile f(Form("/tmp/xuq7/pPbDataV205m%d/vndata_50k_%d.root",mult,ifile), "RECREATE","ROOT file with histograms & tree");
//  TFile f(Form("vndata_50k_%d.root",mult,ifile), "RECREATE","ROOT file with histograms & tree");
  TTree *tree = new TTree("tree","Event tree with a few branches");
//  tree->Branch("npg", &b_npg, "npg/I");   // # of particles;
//  tree->Branch("phirg", &b_phirg, "phirg/F");  // RP angle;
  tree->Branch("n", &b_n, "n/I");          // same as npg;
  tree->Branch("ptg", &b_ptg, "ptg[n]/F");  // ;
  tree->Branch("etag", &b_etag, "etag[n]/F");
  tree->Branch("phig", &b_phig, "phig[n]/F");
  
  TF1 *EtaDistr = new TF1("EtaDistr","exp(-(x-2.1)^2/6.3)+exp(-(x+2.1)^2/6.3)",-4,4);
  //TF1 *PhiDistr = new TF1("PhiDistr","1+2*[0]*cos(x)+2*[1]*cos(2*x)+2*[2]*cos(3*x)+2*[3]*cos(4*x)+2*[4]*cos(5*x)+2*[5]*cos(6*x)",0,2.*TMath::Pi());
  TF1 *PhiDistr = new TF1("PhiDistr","1+2*[0]*cos(2*x)+2*[1]*cos(3*x)+2*[2]*cos(4*x)+2*[3]*cos(5*x)+2*[4]*cos(6*x)",0,2.*TMath::Pi());
  //TF1 *PtDistr  = new TF1("PtDistr","exp (-(x/.40))+0.0015*exp (-(x/1.5))", 0.2,10);	//V~0.12
  //TF1 *PtDistr  = new TF1("PtDistr","exp (-(x/0.90))+0.15*exp (-(x/15))", 0.1,10);	//V~=0.06
  TF1 *PtDistr  = new TF1("PtDistr","0.03*(exp (-(x/0.594540))+0.00499506*exp (-(x/1.89391)))", 0.3,6.0);	//Real Data
  //  TF1 *PtDistr = new TF1("PtDistr","[0]*x*TMath::Power(1+(sqrt(x*x+[1]*[1])-[1]/[2]),-[3])",0.2,10);
	//PtDistr->SetParameters(118.836,-0.335972,0.759243,118.836);	//Real data fit with Tsallis
  //TF1 *V1vsEta = new TF1("V1vsEta","-exp(-(x+1)^2)/20-x/30+exp(-(x-1)^2)/20",-2.4,2.4); 
  //TF1 *V2vsPt   = new TF1("V2vsPt","((x/3)^1.8/(1+(x/3)^1.8))*(.00005+(1/x)^0.8)",0.2,10);
  //TF1 *V2vsPt = new TF1("V2vsPt","((x/[0])^[1]/(1+(x/[2])^[3]))*(.00005+(1/x)^[4])",0.1,10);
 //	V2vsPt->SetParameters(4.81159,1.80783,3.69272,3.11889,0.931485);	//Real data V~0.05
  //	V2vsPt->SetParameters(5,1.8,3,1.8,0.8); //V~0.06
  TF1 *V2vsPt = new TF1("V2vsPt","((x/3.31699)^2.35142/(1+(x/3.49188)^3.54429))*(.00005+(1/x)^1.50600)",0.3,6.0);
  TF1 *V3vsPt = new TF1("V3vsPt","((x/3.2)^2.3/(1+(x/3.4)^2.1))*(.00005+(1/x)^1.4)",0.3,6.0);
  TF1 *V4vsPt = new TF1("V4vsPt","((x/4.8)^2.1/(1+(x/3.4)^2.1))*(.00005+(1/x)^1.4)",0.3,6.0);
  TF1 *V5vsPt = new TF1("V5vsPt","((x/6.0)^3.2/(1+(x/11.4)^2.1))*(.00005+(1/x)^1.4)",0.3,6.0);
  TF1 *V6vsPt = new TF1("V6vsPt","((x/5.6)^2.4/(1+(x/4.7)^2.1))*(.00005+(1/x)^1.4)",0.3,6.0);
 
    UInt_t iniseed = SetSeedOwn();
    gRandom->SetSeed(iniseed);
  TRandom3 *rnd = new TRandom3(0);
  
  double v1, v2, v3, v4, v5, v6, ph, myphi, mypt, myeta, phi0, Psi;
  int nnf,k;
  double neta, nphi, npt;
  int slicept;
  
  for(int i=0; i<tot_num; i++){ 
    
    Psi = rnd->Uniform(0.0,2.*TMath::Pi());
    //Psi=0;
    b_phirg = Psi; 
    b_npg = rnd->Gaus(MeanMult,RMSMult); 
    int b_npgsame = (int)b_npg * 0.10;
    n = 0;
  
    for(int j=0; j<b_npg;j++ ){
      mypt = PtDistr->GetRandom();
      myeta =  EtaDistr->GetRandom();

      //v1=V1vsEta->Eval(myeta);
      v2=V2vsPt->Eval(mypt);
      v3=V3vsPt->Eval(mypt);
      v4=V4vsPt->Eval(mypt);
      v5=V5vsPt->Eval(mypt);
      v6=V6vsPt->Eval(mypt);

      b_etag[n] = myeta;
      b_ptg[n]  = mypt;
      //PhiDistr->SetParameters(v1,v2,v3,v4,v5,v6);
      PhiDistr->SetParameters(v2,v3,v4,v5,v6);
      
      myphi = PhiDistr->GetRandom(); // randon selection dn/dphi

      myphi = myphi+Psi; // angle in lab frame -- needed for correct cumulant v2
      if (myphi>2.*TMath::Pi()) myphi=myphi-2.*TMath::Pi(); // 0 - 2*Pi
      
      b_phig[n] = myphi; // save angle in lab frame
      n++;
    }
    if(i%10==0){
    for(int j=0;j<b_npgsame;j++){
      mypt = PtDistr->GetRandom();
      myeta =  EtaDistr->GetRandom();
      b_ptg[n] = mypt;
      b_etag[n] = myeta;
      myphi = rnd->Gaus(Psi, 0.3);
      if (myphi>2.*TMath::Pi()) myphi=myphi-2.*TMath::Pi(); // 0 - 2*Pi
      b_phig[n] = myphi;
      n++;
    }
    }
    if (i%10000 == 0) cout << i << " " << "events processed" << endl;

    b_n = n;
    tree->Fill();
  } // End of loop over events
  
  cout << "writing tree" << endl;
  tree->Write();
  cout << "writing to file" << endl;
  f.Write();
  cout << "closing file" << endl;
  f.Close();
  cout << "THE END" << endl;
}
Beispiel #18
0
int main() 
{
#ifndef NO_ROOT
	TRandom3 r;r.SetSeed( (unsigned)time(NULL) ) ;
	FindMatch A;
	A.SetMaxWindow(1); 
	// create a basic spill random time distributions
	vector<uint64_t> t;	
	uint64_t lastTime=100;
	for(int i=0;i<200; ++i) // ~ eventInSPill
	{
		lastTime +=  TMath::Floor(r.Uniform(5,30.) );
		t.push_back(lastTime);
	}
	vector<uint64_t> time1,time2;

	// with a certain probability k, accept time1, time2. Smear time2 guas + a constant diff
	uint64_t delta=TMath::Floor(r.Uniform(10,100) );
	for(unsigned int i=0; i<t.size(); ++i)
		{
			// 0.0005 for 2000
		if (r.Uniform() > 0.05) time1.push_back(t[i]);
		if (r.Uniform() > 0.05) time2.push_back(
				TMath::Floor( r.Gaus(t[i],1.1) ) + delta
				);
		}
	// 
	A.SetTimes(time1,time2);
	printf("------- START -------\n");
	printf("-- >  t.size = %lu\n",t.size());
	printf("-- >  t1.size = %lu\n",time1.size());
	printf("-- >  t2.size = %lu\n",time2.size());
	long max=TMath::Max(time1.size(),time2.size());
	long diff=TMath::Abs(long(time1.size()) -long(time2.size()) ) + A.GetMaxWindow() ;
	double time = pow(max,diff) * 0.11/220.; // 116 ms -- ad hoc factors
	string timeStr="";
	if (time > 3600 ) 
		{
		long h=TMath::Floor(time/3600.);
		timeStr += Form("%ld h  ",h);
		time -= 3600*h;
		}
	if(time >60 ) 
		{
		long m=TMath::Floor(time/60.);
		timeStr += Form("%ld m  ",m);
		time -= 60*m;
		}
	timeStr += Form("%lf s",time);
	printf("-- >  time unit estimation = %s\n", timeStr.c_str());
	//uint64_t myStart=(uint64_t)time(NULL);
	timeval tv_start; 
	gettimeofday(&tv_start,NULL);
	int status=A.Run();
	//uint64_t myStop=(uint64_t)time(NULL);
	timeval tv_stop;
	gettimeofday(&tv_stop,NULL);
	//printf("USER TIME: %u\n",(unsigned int)(myStop-myStart));
	printf("USER TIME: %ld usec\n", Utility::timevaldiff( &tv_start, &tv_stop) );
	printf("     status=%d == 0\n", status ) ;
	printf("     alpha=%lf\n", A.GetAlpha() ) ;
	printf("     Window (If SLOW REDUCE)=%d\n", A.GetMaxWindow() ) ;
	printf("     Converged=%d\n", int(A.Converged()) ) ;
	// PLOT
	{
		TCanvas *c=new TCanvas("c","c",800,800);
		TH1D *h0 =new TH1D("time" ,"time;time;time" ,1000,0,2000.);
		TH1D *h1 =new TH1D("time1","time1;time;time1",1000,0,2000.);
		TH1D *h2 =new TH1D("time2","time2;time;time2",1000,0,2000.);
		TH1D *h2_shifted =new TH1D("time2_shift","time2;time;time2",2000,0,2000.) ; h2_shifted->SetLineColor(kRed);
		TPad *p0= new TPad("p0","p0",0,0,1,0.35); p0->SetTopMargin(0); p0->SetBottomMargin(.05/.35);
		TPad *p1= new TPad("p1","p1",0,0.35,1,.65);p1->SetTopMargin(0); p1->SetBottomMargin(0);
		TPad *p2= new TPad("p2","p2",0,0.65,1,1);p2->SetTopMargin(.05/.35); p2->SetBottomMargin(0);
		p0->Draw();
		p1->Draw();
		p2->Draw();
		// fill and draw time, time1,time2
		for(unsigned int i=0;i<t.size();++i) h0->Fill( t[i] );
		for(unsigned int i=0;i<time1.size();++i) h1->Fill( time1[i] ,0.5);
		for(unsigned int i=0;i<time2.size();++i) h2->Fill( time2[i] ,0.5);
		p2->cd(); h0->Draw("HIST"); h0->GetYaxis()->SetRangeUser(0,1.2);
		p1->cd(); h1->Draw("HIST"); h1->GetYaxis()->SetRangeUser(0,1.2);
		p0->cd(); h2->Draw("HIST"); h2->GetYaxis()->SetRangeUser(0,1.2);
		c->cd();
		vector<pair<uint_t,uint_t> > matched=A.GetMatch(); // positions in time1/time2
		// compute delta
		double delta=0;
		for(uint_t i=0;i<matched.size();++i)
			delta += int64_t(time1[matched[i].first])-int64_t(time2[matched[i].second]);
		delta /= matched.size();
		for(unsigned int i=0;i< matched.size() ;i++ ) 
			{
			TLine *l=new TLine();	
			//l->SetName( Form("Line_%u",i) );
			l->SetLineWidth(2);
			uint64_t x1=time1[matched[i].first];
			uint64_t x2=time2[matched[i].second];
			h2_shifted->Fill(int64_t(x2)+delta,1);
			double max=h0->GetBinLowEdge(h0->GetNbinsX()+2);
			double min=h0->GetBinLowEdge(1);
			// LeftMargin
			double rm= p2->GetRightMargin();
			double lm= p2->GetLeftMargin();
			l->DrawLineNDC( (1.-rm-lm)*(x1-min)/(max-min)+lm,.38, 
					(1.-lm-rm)*(x2-min)/(max-min)+lm,0.07);
			}
		p0->cd();
		h2_shifted->Draw("HIST SAME");
		h2->Draw("HIST SAME"); // redraw
		c->SaveAs("Matched.png");
		c->SaveAs("Matched.pdf");
		c->SaveAs("Matched.root");
	}
	return 0;
#else
	printf("ROOT is Required: Recompile w/ ROOT\n");
	return 1;
#endif
}
void Draw_BDiJetImbalance()
{
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);

  //==========================================================================//
  // SET RUNNING CONDITIONS
  //==========================================================================//
  bool print_plots = true;

  bool is_pp = false;

  // const char* inFile = "HFtag_bjet.root";
  // const char* inFile = "HFtag_bjet_pp.root";
  // const char* inFile = "/phenix/plhf/dcm07e/sPHENIX/bjetsims/test.root";
  // if (!is_pp)
  //   const char* inFile = "HFtag_bjet_AuAu0-10.root";

  const char* inDir = "/phenix/plhf/dcm07e/sPHENIX/bjetsims/ana";

  // // desired nn integrated luminosity [pb^{-1}]
  // double lumiDesired = 175;
  // if ( !is_pp )
  //   lumiDesired = 229; // AuAu 0-10% central (10B events)
  // desired nn integrated luminosity [pb^{-1}]
  double lumiDesired = 200;
  TString scol("p + p #sqrt{s_{_{NN}}} = 200 GeV");
  TString slumi(Form("#int L dt = %.0f pb^{-1} |z| < 10 cm", lumiDesired));
  if ( !is_pp )
  {
    // equivelant nn luminosity:
    // N_{evt}^{NN} / sigma_NN = N_{evt}^{AA}*Ncoll / sigma_NN
    // = 10e9 * 962 / 42e9 pb = 229 pb^-1
    double evntDesired = 24e9; // AuAu 0-10% central
    lumiDesired = evntDesired * 962 / 42e9; // AuAu 0-10% central
    scol = "0-10% Au + Au #sqrt{s_{_{NN}}}=200 GeV";
    slumi = Form("%.0fB events |z| < 10 cm", evntDesired / 1.e9);
  }

  // luminosity per file generated [pb^{-1}]
  double lumiPerFile = 99405 / (4.641e-06 * 1e12);
  double lumiRead = 0;

  double pT1min = 20;
  double pT2min = 10;
  // double etamax = 1.0;
  double etamax = 0.7;

  // double bJetEff = 0.5; // b-jet tagging efficiency
  double bJetEff = 0.60; // p+p b-jet tagging efficiency
  if ( !is_pp )
    bJetEff = 0.40;

  double bJetPur = 0.40; // b-jet tagging purity

  double RAA = 1.0;
  if (!is_pp)
    RAA = 0.6;

  const int NETACUT = 3;
  double etacut[] = {1.3, 1.0, 0.7};
  double etaColor[] = {kBlue, kRed, kBlack};

  const int PTCUT = 3;
  double ptcut[] = {10, 20, 40};
  double ptColor[] = {kBlue, kRed, kBlack};

  //==========================================================================//
  // DECLARE VARIABLES
  //==========================================================================//

  //-- tree variables
  TChain *ttree;
  Int_t           event;
  Int_t           truthjet_n;
  Int_t           truthjet_parton_flavor[100];
  Int_t           truthjet_hadron_flavor[100];
  Float_t         truthjet_pt[100];
  Float_t         truthjet_eta[100];
  Float_t         truthjet_phi[100];

  //-- histograms

  TH1D* hjet_pT = new TH1D("hjet_pT", ";p_{T}^{jet} [GeV/c]", 20, 0, 100);
  TH1D* hjet_eta = new TH1D("hjet_eta", ";#eta^{jet}", 40, -2., 2.);
  TH1D* hjet_phi = new TH1D("hjet_phi", ";#phi^{jet}", 40, -4, 4);

  TH1D* hdijet_pT1 = new TH1D("hdijet_pT1", ";p_{T,1}^{jet} [GeV/c]", 20, 0, 100);
  TH1D* hdijet_pT2 = new TH1D("hdijet_pT2", ";p_{T,2}^{jet} [GeV/c]", 20, 0, 100);
  TH1D* hdijet_xj = new TH1D("hdijet_xj", ";x_{j} = p_{T,2} / p_{T,1}; event fraction", 10, 0, 1);
  TH1D* hdijet_dphi = new TH1D("hdijet_dphi", ";|#Delta#phi_{12}|; event fraction", 10, 0, TMath::Pi());

  TH1D* hdijet_sing_pT1 = new TH1D("hdijet_sing_pT1",
                                   ";p_{T,1} [GeV/c];Fraction of Dijet / Single Accepted",
                                   20, 00, 100);
  TH1D* hdijet_sing_eta2 = new TH1D("hdijet_sing_eta2",
                                    ";#eta_{2};Fraction of Dijet / Single Accepted",
                                    15, -1.5, 1.5);
  TH1D* hdijet_eff_pT1[3];
  TH1D* hdijet_eff_eta2[3];
  for (int i = 0; i < NETACUT; i++)
  {
    hdijet_eff_pT1[i] = new TH1D(Form("hdijet_eff_pT1_%i", i),
                                 ";p_{T,1} [GeV/c];Fraction of Dijet / Single Accepted",
                                 20, 00, 100);
    hdijet_eff_pT1[i]->SetLineColor(etaColor[i]);
    hdijet_eff_pT1[i]->SetLineWidth(2);
  } // i
  for (int i = 0; i < PTCUT; i++)
  {
    hdijet_eff_eta2[i] = new TH1D(Form("hdijet_eff_eta2_%i", i),
                                  ";#eta;Fraction of Dijet / Single Accepted",
                                  15, -1.5, 1.5);
    hdijet_eff_eta2[i]->SetLineColor(etaColor[i]);
    hdijet_eff_eta2[i]->SetLineWidth(2);
  } // i

  hjet_pT->Sumw2();
  hjet_eta->Sumw2();
  hjet_phi->Sumw2();

  hdijet_pT1->Sumw2();
  hdijet_pT2->Sumw2();
  hdijet_dphi->Sumw2();
  hdijet_xj->Sumw2();

  // for fixing the uncertainties
  TH1D* hdijet_xj_fix;

  //-- other
  TRandom3 *rand = new TRandom3();

  bool acc[100];

  //==========================================================================//
  // LOAD TTREE
  //==========================================================================//
  // cout << endl;
  // cout << "--> Reading data from " << inFile << endl;

  // TFile *fin = TFile::Open(inFile);
  // if (!fin)
  // {
  //   cout << "ERROR!! Unable to open " << inFile << endl;
  //   return;
  // }

  // ttree = (TTree*) fin->Get("ttree");
  // if (!ttree)
  // {
  //   cout << "ERROR!! Unable to find ttree in " << inFile << endl;
  //   return;
  // }

  cout << endl;
  cout << "--> Reading data from dir: " << inDir << endl;

  // calculate the number of files necessary for the desired luminosity
  int nfiles = (int)(lumiDesired / lumiPerFile);
  cout << "  desired luminosity : " << lumiDesired << endl;
  cout << "  luminosity per file: " << lumiPerFile << endl;
  cout << "  N files needed     : " << nfiles << endl;


  // check the number of files found in the directory
  int nfound = (gSystem->GetFromPipe(Form("ls %s/*.root | wc -l", inDir))).Atoi();
  cout << "  N files found      : " << nfound << endl;

  if (nfound < nfiles)
  {
    cout << "WARNING!! There are not enough files for the desired luminosity." << endl;
    cout << "          Will scale the statistical uncertainties accordingly." << endl;
    // return;
  }

  // chain the desired files
  ttree = new TChain("ttree");
  int nread = 0;

  TString fileList = gSystem->GetFromPipe(Form("ls %s/*.root", inDir));

  int spos = fileList.First("\n");
  while (spos > 0 && nread < nfiles)
  {
    TString tfile = fileList(0, spos);
    // cout << tsub << endl;

    ttree->Add(tfile.Data());


    // chop off the file
    fileList = fileList(spos + 1, fileList.Length());
    spos = fileList.First("\n");
    nread++;
  }

  cout << " successfully read in " << nread << " files" << endl;
  lumiRead = lumiPerFile * nread;


  ttree->SetBranchAddress("event", &event);
  ttree->SetBranchAddress("truthjet_n", &truthjet_n);
  ttree->SetBranchAddress("truthjet_parton_flavor", truthjet_parton_flavor);
  ttree->SetBranchAddress("truthjet_hadron_flavor", truthjet_hadron_flavor);
  ttree->SetBranchAddress("truthjet_pt", truthjet_pt);
  ttree->SetBranchAddress("truthjet_eta", truthjet_eta);
  ttree->SetBranchAddress("truthjet_phi", truthjet_phi);

  Long64_t nentries = ttree->GetEntries();


  //==========================================================================//
  // GET MOMENTUM IMBALANCE
  //==========================================================================//
  cout << endl;
  cout << "--> Running over " << nentries << endl;

  int iprint = 0;
  for (Long64_t ientry = 0; ientry < nentries; ientry++)
  {
    ttree->GetEntry(ientry);

    if (ientry % 100000 == 0) cout << "----> Processing event " << ientry << endl;

    //-- apply acceptance to each jet
    for (int i = 0; i < truthjet_n; i++)
      acc[i] = (rand->Uniform() < bJetEff);
      // acc[i] = (rand->Uniform() < bJetEff) && (rand->Uniform() < RAA);

    //-- get kinematics for all b-jets
    for (int i = 0; i < truthjet_n; i++)
    {
      if (TMath::Abs(truthjet_parton_flavor[i]) != 5)
        continue;

      // single b-jet kinematics
      hjet_pT->Fill(truthjet_pt[i]);
      hjet_eta->Fill(truthjet_eta[i]);
      hjet_phi->Fill(truthjet_phi[i]);

      for (int j = i + 1; j < truthjet_n; j++)
      {
        if (TMath::Abs(truthjet_parton_flavor[j]) != 5)
          continue;


        // find the leading and subleading jets
        int i1, i2;
        double pT1, pT2;
        double phi1, phi2;
        double eta1, eta2;
        bool acc1, acc2;

        if (truthjet_pt[i] > truthjet_pt[j])
        {
          i1 = i;
          i2 = j;
        }
        else
        {
          i1 = j;
          i2 = i;
        }

        pT1 = truthjet_pt[i1];
        phi1 = truthjet_phi[i1];
        eta1 = truthjet_eta[i1];
        acc1 = acc[i1];

        pT2 = truthjet_pt[i2];
        phi2 = truthjet_phi[i2];
        eta2 = truthjet_eta[i2];
        acc2 = acc[i2];



        if (iprint < 20)
        {
          cout << " ientry: " << ientry << endl
               << "        i1:" << i1 << " pT1:" << pT1 << " eta1:" << eta1 << " acc1:" << acc1 << endl
               << "        i2:" << i2 << " pT2:" << pT2 << " eta2:" << eta2 << " acc2:" << acc2 << endl;
          iprint++;
        }



        // check if we accept the leading jet
        // only take RAA hit once
        if ( pT1 < pT1min || TMath::Abs(eta1) > etamax || !acc1  || rand->Uniform() > RAA)
          continue;

        // calculate the delta phi
        double dphi = TMath::Abs(TMath::ATan2(TMath::Sin(phi1 - phi2), TMath::Cos(phi1 - phi2)));
        if (dphi > TMath::Pi())
          cout << " " << truthjet_phi[i] << " " << truthjet_phi[j] << " " << dphi << endl;

        // calculate efficiency for finding the dijet
        hdijet_sing_pT1->Fill(pT1);

        // cut on the subleading jet
        if ( pT2 < pT2min || TMath::Abs(eta2) > etamax || !acc2 )
          continue;

        hdijet_sing_eta2->Fill(eta2);


        // fill efficiency for finding the dijet
        for (int k = 0; k < NETACUT; k++)
        {
          if ( TMath::Abs(eta2) < etacut[k])
            hdijet_eff_pT1[k]->Fill(pT1);
        }
        for (int k = 0; k < PTCUT; k++)
        {
          if (pT2 > ptcut[k])
            hdijet_eff_eta2[k]->Fill(eta2);
        }

        hdijet_dphi->Fill(dphi);

        if ( dphi < 2.*TMath::Pi() / 3)
          continue;


        // fill diagnostic histograms

        hdijet_pT1->Fill(pT1);
        hdijet_pT2->Fill(pT2);
        hdijet_xj->Fill(pT2 / pT1);

      } // j
    } // i

  } // ientry

  // first get some statistics
  cout << " N b dijets: " << hdijet_dphi->Integral() << endl;
  cout << " N b dijets w / dphi cut: " << hdijet_xj->Integral() << endl;

  // calculate efficiencies
  for (int i = 0; i < NETACUT; i++)
  {
    hdijet_eff_pT1[i]->Divide(hdijet_sing_pT1);
    cout << " i: " << hdijet_eff_pT1[i]->GetMaximum() << endl;
  }
  for (int i = 0; i < PTCUT; i++)
  {
    hdijet_eff_eta2[i]->Divide(hdijet_sing_eta2);
  }

  //-- normalize to integral 1
  hdijet_dphi->Scale(1. / hdijet_dphi->Integral());
  hdijet_xj->Scale(1. / hdijet_xj->Integral());

  //-- scale statistical uncertainties if not enough simulated events
  if ( lumiRead < lumiDesired )
  {
    cout << endl;
    cout << "-- Scaling statistical uncertainties by:" << endl;
    cout << "  sqrt(" << lumiRead << "/" << lumiDesired << ") = "
         << TMath::Sqrt(lumiRead / lumiDesired) << endl;
    for (int ix = 1; ix <= hdijet_xj->GetNbinsX(); ix++)
    {
      double be = hdijet_xj->GetBinError(ix);
      be = be * TMath::Sqrt(lumiRead / lumiDesired);
      hdijet_xj->SetBinError(ix, be);
    } // ix
  }

  //-- fix statistical uncertainties for purity
  hdijet_xj_fix = (TH1D*) hdijet_xj->Clone("hdijet_xj_fix");
  hdijet_xj_fix->SetLineColor(kRed);
  hdijet_xj_fix->SetMarkerColor(kRed);
  for (int ix = 1; ix <= hdijet_xj->GetNbinsX(); ix++)
  {
    double bc = hdijet_xj->GetBinContent(ix);
    double be = hdijet_xj->GetBinError(ix);

    // increase the bin error due to the purity
    // need to square it, once for each bjet
    be = be / TMath::Sqrt(bJetPur * bJetPur);
    hdijet_xj_fix->SetBinError(ix, be);
  } // ix



  //==========================================================================//
  // <x_j>
  //==========================================================================//
  cout << endl;
  cout << "--> Calculating <x_j>" << endl;

  double sum = 0;
  double w = 0;
  double err = 0;
  for (int i = 1; i <= hdijet_xj->GetNbinsX(); i++)
  {
    double c = hdijet_xj->GetBinContent(i);
    if (c > 0)
    {
      sum += c * hdijet_xj->GetBinCenter(i);
      w += c;
      err += TMath::Power(c * hdijet_xj->GetBinError(i), 2);
    }
  }
  double mean = sum / w;
  err = TMath::Sqrt(err) / w;

  cout << "  <x_j>=" << mean << " +/- " << err << endl;

  //==========================================================================//
  // PLOT OBJECTS
  //==========================================================================//
  cout << endl;
  cout << "-- > Plotting" << endl;

  hdijet_xj->SetMarkerStyle(kFullCircle);
  hdijet_xj->SetMarkerColor(kBlack);
  hdijet_xj->SetLineColor(kBlack);
  // hdijet_xj->GetYaxis()->SetTitleFont(63);
  // hdijet_xj->GetYaxis()->SetTitleSize(24);
  // hdijet_xj->GetYaxis()->SetTitleOffset(1.4);
  // hdijet_xj->GetYaxis()->SetLabelFont(63);
  // hdijet_xj->GetYaxis()->SetLabelSize(20);
  // hdijet_xj->GetXaxis()->SetTitleFont(63);
  // hdijet_xj->GetXaxis()->SetTitleSize(24);
  // hdijet_xj->GetXaxis()->SetTitleOffset(1.0);
  // hdijet_xj->GetXaxis()->SetLabelFont(63);
  // hdijet_xj->GetXaxis()->SetLabelSize(20);

  hdijet_xj_fix->SetMarkerStyle(kFullCircle);
  hdijet_xj_fix->SetMarkerColor(kBlack);
  hdijet_xj_fix->SetLineColor(kBlack);

  hdijet_dphi->SetMarkerStyle(kFullCircle);
  hdijet_dphi->SetMarkerColor(kBlack);
  hdijet_dphi->SetLineColor(kBlack);
  hdijet_dphi->GetYaxis()->SetTitleFont(63);
  hdijet_dphi->GetYaxis()->SetTitleSize(24);
  hdijet_dphi->GetYaxis()->SetTitleOffset(1.4);
  hdijet_dphi->GetYaxis()->SetLabelFont(63);
  hdijet_dphi->GetYaxis()->SetLabelSize(20);
  hdijet_dphi->GetXaxis()->SetTitleFont(63);
  hdijet_dphi->GetXaxis()->SetTitleSize(24);
  hdijet_dphi->GetXaxis()->SetTitleOffset(1.0);
  hdijet_dphi->GetXaxis()->SetLabelFont(63);
  hdijet_dphi->GetXaxis()->SetLabelSize(20);

  hdijet_pT1->SetLineColor(kBlue);
  hdijet_pT2->SetLineColor(kRed);

  TH1D* heff_axis_pt = new TH1D("heff_axis_pt",
                                "; p_{T, 1} [GeV / c]; Fraction of Dijet / Single Accepted",
                                20, 00, 100);
  heff_axis_pt->SetMinimum(0);
  heff_axis_pt->SetMaximum(1.);
  heff_axis_pt->GetYaxis()->SetTitleFont(63);
  heff_axis_pt->GetYaxis()->SetTitleSize(24);
  heff_axis_pt->GetYaxis()->SetTitleOffset(1.4);
  heff_axis_pt->GetYaxis()->SetLabelFont(63);
  heff_axis_pt->GetYaxis()->SetLabelSize(20);
  heff_axis_pt->GetXaxis()->SetTitleFont(63);
  heff_axis_pt->GetXaxis()->SetTitleSize(24);
  heff_axis_pt->GetXaxis()->SetTitleOffset(1.0);
  heff_axis_pt->GetXaxis()->SetLabelFont(63);
  heff_axis_pt->GetXaxis()->SetLabelSize(20);

  TH1D* heff_axis_eta = new TH1D("heff_axis_eta",
                                 "; #eta_{2}; Fraction of Dijet / Single Accepted",
                                 150, -1.5, 1.5);
  heff_axis_eta->SetMinimum(0);
  heff_axis_eta->SetMaximum(1.);
  heff_axis_eta->GetYaxis()->SetTitleFont(63);
  heff_axis_eta->GetYaxis()->SetTitleSize(24);
  heff_axis_eta->GetYaxis()->SetTitleOffset(1.4);
  heff_axis_eta->GetYaxis()->SetLabelFont(63);
  heff_axis_eta->GetYaxis()->SetLabelSize(20);
  heff_axis_eta->GetXaxis()->SetTitleFont(63);
  heff_axis_eta->GetXaxis()->SetTitleSize(24);
  heff_axis_eta->GetXaxis()->SetTitleOffset(1.0);
  heff_axis_eta->GetXaxis()->SetLabelFont(63);
  heff_axis_eta->GetXaxis()->SetLabelSize(20);

  for (int i = 0; i < NETACUT; i++)
    hdijet_eff_pT1[i]->SetLineColor(etaColor[i]);

//-- legends
  TLegend *leg_jetpt = new TLegend(0.6, 0.5, 0.95, 0.95);
  leg_jetpt->SetFillStyle(0);
  leg_jetpt->SetBorderSize(0);
  leg_jetpt->SetTextFont(63);
  leg_jetpt->SetTextSize(12);
  leg_jetpt->AddEntry(hjet_pT, "Inclusive b - jet", "L");
  leg_jetpt->AddEntry(hdijet_pT1, "leading b - jet", "L");
  leg_jetpt->AddEntry(hdijet_pT2, "subleading b - jet", "L");


//-- other
  TLatex ltxt;
  ltxt.SetNDC();
  ltxt.SetTextFont(63);
  ltxt.SetTextSize(20);

//==========================================================================//
// PLOT
//==========================================================================//

// plot b-jet kinematics
  TCanvas *cjet = new TCanvas("cjet", "b - jet", 1200, 400);
  cjet->SetMargin(0, 0, 0, 0);
  cjet->Divide(3, 1);

  cjet->GetPad(1)->SetMargin(0.12, 0.02, 0.12, 0.02);
  cjet->GetPad(2)->SetMargin(0.12, 0.02, 0.12, 0.02);
  cjet->GetPad(3)->SetMargin(0.12, 0.02, 0.12, 0.02);

  cjet->cd(1);
  gPad->SetLogy();
  hjet_pT->GetYaxis()->SetRangeUser(0.5, 1.5 * hjet_pT->GetMaximum());
  hjet_pT->GetXaxis()->SetRangeUser(0, 50);
  hjet_pT->Draw();
  // hdijet_pT1->Draw("same");
  // hdijet_pT2->Draw("same");

  // leg_jetpt->Draw("same");

  cjet->cd(2);
  hjet_eta->Draw("HIST");

  cjet->cd(3);
  hjet_phi->Draw("HIST");


// plot dijet eff
  TCanvas *ceff = new TCanvas("ceff", "eff", 1200, 600);
  ceff->Divide(2, 1);
  ceff->GetPad(1)->SetMargin(0.12, 0.02, 0.12, 0.02);
  ceff->GetPad(1)->SetTicks(1, 1);
  ceff->GetPad(2)->SetMargin(0.12, 0.02, 0.12, 0.02);
  ceff->GetPad(2)->SetTicks(1, 1);

  ceff->cd(1);

  heff_axis_pt->Draw();

  for (int i = 0; i < NETACUT; i++)
    hdijet_eff_pT1[i]->Draw("L same");

  ceff->cd(2);

  heff_axis_eta->Draw();

  for (int i = 0; i < NETACUT; i++)
    hdijet_eff_eta2[i]->Draw("L same");

// plot dijet checks
  TCanvas *cdijet2 = new TCanvas("cdijet2", "dijet", 1200, 600);
  cdijet2->SetMargin(0, 0, 0, 0);
  cdijet2->Divide(2, 1);

  cdijet2->GetPad(1)->SetMargin(0.12, 0.02, 0.12, 0.02);
  cdijet2->GetPad(2)->SetMargin(0.12, 0.02, 0.12, 0.02);

  cdijet2->cd(1);
  hdijet_xj->Draw();

  ltxt.DrawLatex(0.2, 0.92, "Di b-jets (Pythia8)");
  ltxt.DrawLatex(0.2, 0.86, "p + p #sqrt{s_{_{NN}}}=200 GeV");
  ltxt.DrawLatex(0.2, 0.80, "anti - k_ {T}, R = 0.4");
  ltxt.DrawLatex(0.2, 0.74, Form("p_{T, 1} > % .0f GeV", pT1min));
  ltxt.DrawLatex(0.2, 0.68, Form("p_{T, 2} > % .0f GeV", pT2min));
  ltxt.DrawLatex(0.2, 0.62, Form(" | #Delta#phi_{12}| > 2#pi/3"));

  cdijet2->cd(2);
  hdijet_dphi->Draw();






  // make this one consistent with sPHENIX style
  TCanvas *cdijet = new TCanvas("cdijet", "dijet", 600, 600);
  // cdijet->SetMargin(0.12, 0.02, 0.12, 0.02);
  // cdijet->SetTicks(1, 1);
  cdijet->cd();
  hdijet_xj_fix->GetYaxis()->SetRangeUser(0, 0.3);
  hdijet_xj_fix->Draw();
  // hdijet_xj->Draw("same");


  TLegend *legsphenix = new TLegend(0.15, 0.5, 0.5, 0.9);
  legsphenix->SetFillStyle(0);
  legsphenix->SetBorderSize(0);
  legsphenix->AddEntry("", "#it{#bf{sPHENIX}} Simulation", "");
  legsphenix->AddEntry("", "Di b-jets (Pythia8, CTEQ6L)", "");
  // if (is_pp)
  // {
  //   legsphenix->AddEntry("", "p + p #sqrt{s_{_{NN}}} = 200 GeV", "");
  //   legsphenix->AddEntry("", Form("#int L dt = %.0f pb^{-1} |z| < 10 cm", lumiDesired), "");
  // }
  // else
  // {
  //   legsphenix->AddEntry("", "0-10% Au + Au #sqrt{s_{_{NN}}}=200 GeV", "");
  //   legsphenix->AddEntry("", "10B events |z| < 10 cm", "");
  // }
  legsphenix->AddEntry("", scol.Data(), "");
  legsphenix->AddEntry("", slumi.Data(), "");
  legsphenix->AddEntry("", "anti-k_{T}, R = 0.4", "");
  legsphenix->AddEntry("", Form(" |#eta| < %.1f", etamax), "");
  legsphenix->AddEntry("", Form(" |#Delta#phi_{12}| > 2#pi/3"), "");
  legsphenix->AddEntry("", Form("p_{T, 1} > % .0f GeV", pT1min), "");
  legsphenix->AddEntry("", Form("p_{T, 2} > % .0f GeV", pT2min), "");
  legsphenix->AddEntry("", Form("%.0f%% b-jet Eff, %.0f%% b-jet Pur.", bJetEff * 100., bJetPur * 100.), "");
  legsphenix->Draw("same");

  // ltxt.DrawLatex(0.2, 0.92, "Di b-jets (Pythia8)");
  // if (is_pp)
  // {
  //   ltxt.DrawLatex(0.2, 0.86, "p + p #sqrt{s_{_{NN}}} = 200 GeV");
  //   ltxt.DrawLatex(0.2, 0.80, "#int L dt = 175 pb^{-1} |z| < 10 cm");
  // }
  // else
  // {
  //   ltxt.DrawLatex(0.2, 0.86, "0-10% Au + Au #sqrt{s_{_{NN}}}=200 GeV");
  //   ltxt.DrawLatex(0.2, 0.80, "10B events |z| < 10 cm");
  // }
  // ltxt.DrawLatex(0.2, 0.74, "anti-k_{T}, R = 0.4");
  // ltxt.DrawLatex(0.2, 0.68, Form("p_{T, 1} > % .0f GeV", pT1min));
  // ltxt.DrawLatex(0.2, 0.62, Form("p_{T, 2} > % .0f GeV", pT2min));
  // ltxt.DrawLatex(0.2, 0.56, Form(" |#eta| < %.0f", etamax));
  // ltxt.DrawLatex(0.2, 0.50, Form(" |#Delta#phi_{12}| > 2#pi/3"));


  //==========================================================================//
  // PRINT PLOTS
  //==========================================================================//
  if (print_plots)
  {
    if (is_pp)
    {
      // cjet->Print("bjet_kinematics_pp.pdf");
      // cdijet2->Print("dibjet_2panel_pp.pdf");
      cdijet->Print("dibjet_imbalance_pp.pdf");
      cdijet->Print("dibjet_imbalance_pp.C");
      cdijet->Print("dibjet_imbalance_pp.root");

      TFile *fout = new TFile("dibjet_imbalance_histos_pp.root","RECREATE");
      fout->cd();
      hdijet_xj->Write();
      hdijet_xj_fix->Write();
      fout->Close();
      delete fout;

    }
    else
    {
      cdijet->Print("dibjet_imbalance_AuAu0-10.pdf");
      cdijet->Print("dibjet_imbalance_AuAu0-10.C");
      cdijet->Print("dibjet_imbalance_AuAu0-10.root");

      TFile *fout = new TFile("dibjet_imbalance_histos_AuAu0-10.root","RECREATE");
      fout->cd();
      hdijet_xj->Write();
      hdijet_xj_fix->Write();
      fout->Close();
      delete fout;
    }
  }

}
Beispiel #20
0
void fitter() {

  // Style
  labstyle();
  
  //Create Canvas
  TCanvas *c_pdf_gen = new TCanvas("c_pdf_gen","canvas histo",500,500);
  c_pdf_gen->cd();
 
  // Create Function
  TF1 *f_pdf = new TF1("f_pdf",pdf_func,a_min,a_max,8);
  // Set function parameter
  f_pdf->SetParameter(0, 1.    );//N
  f_pdf->SetParameter(1, fs    );//fs
  f_pdf->SetParameter(2, fA    );//fA
  f_pdf->SetParameter(3, mA    );//mA
  f_pdf->SetParameter(4, sA    );//sA
  f_pdf->SetParameter(5, mB    );//mB
  f_pdf->SetParameter(6, sB    );//sB
  f_pdf->SetParameter(7, slope );//slope
  
  // Set histogram axis labels
  f_pdf->GetXaxis()->SetTitle("Invariant mass [GeV/#font[10]{c^{2}}] ");
  f_pdf->GetYaxis()->SetTitle("a.u.");

  // Draw histogram
  f_pdf ->Draw();
      
  // Save canvas in .pdf and .epr format 
  c_pdf_gen->Print("./_fig/pdf_gen.pdf");
  c_pdf_gen->Print("./_fig/pdf_gen.eps");

  // ######################################################################
  // ##################### Data sample generation #########################
  // ######################################################################

  //Create Canvas
  TCanvas *c_histo_gen = new TCanvas("c_histo_gen","canvas histo",500,500);
  c_histo_gen->cd();
 
  //Create Histrogram
  TH1F *histo_gen = new TH1F("histo","",100,a_min,a_max);
  
  //Fill the histogram
  Double_t x_var;
  Double_t y_var;
  
  Int_t i;
  i=0;
  while(i<N){
    x_var= a_min + (a_max - a_min)*randGen.Uniform();
    y_var= 0.4 * randGen.Uniform();  
    if(y_var < f_pdf->Eval(x_var)){
    histo_gen->Fill(x_var);
    i++;
    };
  };

  // Set histogram Axis Labels
  histo_gen->GetXaxis()->SetTitle("Invariant mass [GeV/#font[10]{c^{2}}] ");
  histo_gen->GetYaxis()->SetTitle("Events per 0.1 GeV/#font[10]{c^{2}} "); 
  
  // Plot the histogram
  histo_gen -> Draw();

  // Save canvas in .pdf and .epr format
  c_histo_gen->Print("./_fig/histo_gen.pdf");
  c_histo_gen->Print("./_fig/histo_gen.eps");


  // ######################################################################
  // ############################# Fitter #################################
  // ######################################################################

  // Create Function
  TF1 *f_pdf_fit = new TF1("f_pdf_fit",pdf_fit,a_min,a_max,8);
  // Set Initial Parameters  (usually you don't know precisely them!!!)
  f_pdf_fit->SetParameter(0, 100000 );//N
  f_pdf_fit->SetParameter(1,  0.3   );//fs
  f_pdf_fit->SetParameter(2,  0.7   );//fA
  f_pdf_fit->SetParameter(3,  4.    );//mA
  f_pdf_fit->SetParameter(4,  0.3   );//sA
  f_pdf_fit->SetParameter(5,  5.    );//mB
  f_pdf_fit->SetParameter(6,  0.3   );//sB
  f_pdf_fit->SetParameter(7, -0.5   );//slope

  f_pdf_fit->SetParNames("N","fs","fA","mA","sA","mB","sB","slope");

  cout << "#####################  Minimal Fit ##################" << endl;

  // For more details please take a look at the ROOT Referecence Guide 
  // In particular for TH1 --> http://root.cern.ch/root/html/TH1.html#TH1:Fit 
  // In particular for TGraph and TGraphErrors --> https://root.cern.ch/root/html/TGraph.html
  histo_gen -> Fit(f_pdf_fit,"","",a_min,a_max);
 
  Double_t fit_chi2 = f_pdf_fit->GetChisquare();
  Int_t    fit_ndof = f_pdf_fit->GetNDF();
  Double_t fit_prob = f_pdf_fit->GetProb();

  cout << "chi2 = " << fit_chi2 << endl;
  cout << "ndof = " << fit_ndof << endl;
  cout << "prob = " << fit_prob << endl;

  cout << "#####################  Fit and Covariance Matrix ##################" << endl;

  // To access coveriance matrix and other fit information

  TFitResultPtr r = histo_gen->Fit(f_pdf_fit,"S","",a_min,a_max);  //Fit(myFunc,"S");
  TMatrixDSym cov = r->GetCovarianceMatrix();  //  to access the covariance matrix
  Double_t chi2   = r->Chi2(); // to retrieve the fit chi2
  Double_t par0   = r->Parameter(0); // retrieve the value for the parameter 0
  Double_t err0   = r->ParError(0); // retrieve the error for the parameter 0
  r->Print("V");     // print full information of fit including covariance matrix
  
  cout << endl;
  cout << "chi2 = " << chi2 << endl;
  cout << "par0 = " << par0 << endl;
  cout << "err0 = " << err0 << endl;
  cout << "cov(2,3)=" << cov(2,3) << endl;
  
  // Save canvas in .pdf and .epr format
  c_histo_gen->Print("./_fig/histo_fit.pdf");
  c_histo_gen->Print("./_fig/histo_fit.eps");


}
Beispiel #21
0
/**
 * The main function.
 */
int main(int argc, char **argv) {
	int seed = 1234;
	string output_filename("JakeFitResult.root");
	string output_directory("./executables/DalitzFit/");
	string input_filename("JPSIPSMC.ACC.root");
	string input_directory("./executables/DalitzFit/");
	string output_file_suffix("");
	if (argc > 1)
		output_directory = argv[1];
	if (argc > 2)
		output_filename = argv[2];
	if (argc > 3)
		input_directory = argv[3];
	if (argc > 4)
		input_filename = argv[4];
	if (argc > 5)
		seed = atoi(argv[5]);
	if (argc > 6)
		output_file_suffix = argv[6];

	// create correct output file name
	boost::filesystem::path input_file(input_filename);
	string input_file_path = input_directory + "/" + input_filename;
	if (output_file_suffix != "")
		input_file_path = input_directory + "/" + input_file.stem().string()
				+ "_" + output_file_suffix + input_file.extension().string();

	Logging log("log", boost::log::trivial::debug); //initialize logging

	BOOST_LOG_TRIVIAL(info)<< "  ComPWA Copyright (C) 2013  Mathias Michel ";
	BOOST_LOG_TRIVIAL(info)<< "  This program comes with ABSOLUTELY NO WARRANTY; for details see license.txt";
	BOOST_LOG_TRIVIAL(info)<< std::endl;

	DalitzKinematics* kin =
			dynamic_cast<DalitzKinematics*>(DalitzKinematics::createInstance(
					"jpsi", "gamma", "pi0", "pi0"));

	//DPKinematics kin("J/psi","gamma","pi0","pi0");
	//DPKinematics kin("D0","gamma","K-","K+");
	//static dataPoint* point = dataPoint::instance(kin);

	bool useFctTree = false, resultGen = true;

	const char* pPath = getenv("COMPWA_DIR");
	std::string path = "";
	try {
		path = std::string(pPath);
	} catch (std::logic_error& ex) {
		BOOST_LOG_TRIVIAL(error)<<"Environment Variable COMPWA_DIR not set?"<<std::endl;
	}

	std::string resoFile = path + "/executables/DalitzFit/Jake_ypipi.xml";
	boost::property_tree::ptree pt;
	read_xml(resoFile, pt, boost::property_tree::xml_parser::trim_whitespace);
	auto fitAmpPtr = new AmpSumIntensity("amp",normStyle::none,
			std::shared_ptr<Efficiency>(new UnitEfficiency()), nFitEvents);
	fitAmpPtr->Configure(pt);
	std::shared_ptr<Amplitude> amps( fitAmpPtr );

	BOOST_LOG_TRIVIAL(info)<< "Load Modules";
    std::string file = "executables/DalitzFit/JPSIDATA.ACC.root";
    std::shared_ptr<JakeReader> myReader(
        new JakeReader(file, "kin"));
	//std::shared_ptr<RootReader> myReader(
			//new RootReader(input_file_path, "data"));
	myReader->resetWeights(); //setting weights to 1
	std::shared_ptr<JakeReader> myPHSPReader(
			new JakeReader(input_file_path, "kin"));
	myPHSPReader->setEfficiency(shared_ptr<Efficiency>(new UnitEfficiency())); //setting efficiency to 1

	//std::shared_ptr<Amplitude> amps(new AmpSumIntensity(M, Br, m1, m2, m3,"J/psi","gamma","pi0","pi0", ini));
	// Initiate parameters
	ParameterList par;
	std::shared_ptr<Optimizer::ControlParameter> esti;
	amps->FillParameterList(par); //perfect startvalues
	esti = MinLogLH::createInstance(amps, myReader, myPHSPReader, nStartEvent,
			nFitEvents);
	MinLogLH* contrPar = dynamic_cast<MinLogLH*>(&*(esti->Instance()));
	std::shared_ptr<FunctionTree> tree;
	if (useFctTree) {
		contrPar->setUseFunctionTree(1);
		tree = contrPar->getTree();
	}

	//  if(useFctTree){//using tree?
	//    esti = MinLogLH::createInstance(amps, myReader, myPHSPReader, nStartEvent, nFitEvents);
	//  }else{
	//    BOOST_LOG_TRIVIAL(debug)<<"allMasses: try to get MassContainer...";
	//    allMasses myEvtMasses(myReader->getMasses(nStartEvent,nFitEvents));
	//    allMasses myPhspMasses(myPHSPReader->getMasses(nStartEvent,nFitEvents));
	//    BOOST_LOG_TRIVIAL(debug)<<"EvtMasses: "<< myEvtMasses.nEvents <<" events and "<< myEvtMasses.nInvMasses <<" inv masses";
	//    BOOST_LOG_TRIVIAL(debug)<<"PHSPMasses: "<< myPhspMasses.nEvents <<" events and "<< myPhspMasses.nInvMasses <<" inv masses";
	////    physicsTree = amps->functionTree(myPhspMasses,myEvtMasses);
	//    allMasses emptyMasses;
	////    amps->iniFunctionTree(myEvtMasses,myPhspMasses,emptyMasses);
	////    physicsTree = amps->getPhysicsTree();
	//    if(!physicsTree){
	//      BOOST_LOG_TRIVIAL(error)<<"Physics Trees not setup correctly, quitting";
	//      return 0;
	//    }
	////    phspTree = amps->getPhspTree();
	//    if(!phspTree){
	//      BOOST_LOG_TRIVIAL(error)<<"Phsp Trees not setup correctly, quitting";
	//      return 0;
	//    }
	//
	//    BOOST_LOG_TRIVIAL(debug)<<"Check Trees: ";
	//    if(!physicsTree->sanityCheck()) return 0;
	//    if(!phspTree->sanityCheck()) return 0;
	//    //BOOST_LOG_TRIVIAL(info)<<physicsTree<<std::endl;
	//    //BOOST_LOG_TRIVIAL(info)<<phspTree<<std::endl;
	//    physicsTree->recalculate();
	//    phspTree->recalculate();
	//    BOOST_LOG_TRIVIAL(debug)<<physicsTree<<std::endl;
	//    BOOST_LOG_TRIVIAL(debug)<<phspTree<<std::endl;
	//    BOOST_LOG_TRIVIAL(debug)<<"Evt Tree: "<<(std::dynamic_pointer_cast<DoubleParameter>(physicsTree->head()->getValue()))->GetValue();
	//    BOOST_LOG_TRIVIAL(debug)<<"Phsp Tree: "<<(std::dynamic_pointer_cast<DoubleParameter>(phspTree->head()->getValue()))->GetValue();
	//    BOOST_LOG_TRIVIAL(info)<<"Trees are set up"<<std::endl;
	//
	//    esti = MinLogLH::createInstance(physicsTree, phspTree, myEvtMasses.nEvents);

	//    dataPoint myPoint(myReader->getEvent(0));
	//    std::shared_ptr<TreeNode> LogNode = (physicsTree->head()->getChildren())[0];
	//    std::shared_ptr<TreeNode> IntNode = (LogNode->getChildren())[0];
	//    std::shared_ptr<TreeNode> AmpNodeEff = (IntNode->getChildren())[0];
	//    std::shared_ptr<TreeNode> AmpNode = (AmpNodeEff->getChildren())[1];
	//    std::shared_ptr<TreeNode> ResNode = (AmpNode->getChildren())[0];
	//    std::shared_ptr<TreeNode> BWNode = (ResNode->getChildren())[0];
	//    std::shared_ptr<TreeNode> ADNode = (ResNode->getChildren())[2];
	//
	//    std::shared_ptr<MultiComplex> resoChild = std::dynamic_pointer_cast<MultiComplex>( ResNode->getValue() );
	//    std::shared_ptr<MultiDouble> intensChild = std::dynamic_pointer_cast<MultiDouble>( IntNode->getValue() );
	//    std::shared_ptr<MultiComplex> bwChild = std::dynamic_pointer_cast<MultiComplex>( BWNode->getValue() );
	//    std::shared_ptr<MultiDouble> adChild = std::dynamic_pointer_cast<MultiDouble>( ADNode->getValue() );
	//    std::shared_ptr<MultiComplex> ampChild = std::dynamic_pointer_cast<MultiComplex>( AmpNode->getValue() );
	//
	//    BOOST_LOG_TRIVIAL(debug) << "InvMasses first Evt from dataPoint: \t" << myPoint.getVal("m23sq") << " \t " << myPoint.getVal("m13sq");
	//    BOOST_LOG_TRIVIAL(debug) << "InvMasses first Evt from allMasses: \t" << (myEvtMasses.masses_sq[std::make_pair(2,3)])[0] << " \t " << (myEvtMasses.masses_sq[std::make_pair(1,3)])[0];
	//
	//    BOOST_LOG_TRIVIAL(debug) << "First BW first Evt classical: \t" <<  (amps->getFirstBW(myPoint,par));
	//    BOOST_LOG_TRIVIAL(debug) << "First BW first Evt from tree: \t" << (bwChild->GetValue()*adChild->GetValue());
	//
	//    BOOST_LOG_TRIVIAL(debug) << "FirstReso first Evt classical: \t" <<  amps->getFirstReso(myPoint,par);
	//    BOOST_LOG_TRIVIAL(debug) << "FirstReso first Evt from tree: \t" << resoChild->GetValue();
	//
	//    BOOST_LOG_TRIVIAL(debug) << "First Amp first Evt classical: \t" <<  amps->getFirstAmp(myPoint,par);
	//    BOOST_LOG_TRIVIAL(debug) << "First Amp first Evt from tree: \t" << ampChild->GetValue();
	//
	//    BOOST_LOG_TRIVIAL(debug) << "Intensity of first data event classical: \t" << amps->intensity(myPoint,par).GetParameterValue(0);
	//    BOOST_LOG_TRIVIAL(debug) << "Intensity of first data event from tree: \t" << intensChild->GetValue();
	//    BOOST_LOG_TRIVIAL(debug)<<"Finish consistency checks"<<std::endl;
	//  }

	//std::shared_ptr<ControlParameter> esti = MinLogLH::createInstance(amps, myReader, myPHSPReader);
	//std::shared_ptr<Estimator> esti(new MinLogLH(amps, myReader, myPHSPReader));
	std::shared_ptr<Optimizer::Optimizer> opti(new Optimizer::Minuit2::MinuitIF(esti, par));

	ParameterList test;
	/*if(useFctTree)
	 if(!amps->functionTree(test))
	 return 1;*/

	//return 0;
	BOOST_LOG_TRIVIAL(info)<< "LH with optimal parameters: " << esti->controlParameter(par);
	if (useFctTree)
		BOOST_LOG_TRIVIAL(info)<<tree;
		//exit(1);
	double startInt[par.GetNDouble()], optiInt[par.GetNDouble()];
	for (unsigned int i = 0; i < par.GetNDouble(); i++) {
		std::shared_ptr<DoubleParameter> tmp = par.GetDoubleParameter(i);
		optiInt[i] = tmp->GetValue();
		//if (/*i < 2 ||*/ i > 10 /*|| i%4==2 || i%4==3 */) { //omega's and f0 fixed
			//if(i<2 || i>3 || i%2==1){ //omega's and f0 fixed
		//	tmp->FixParameter(true);
		//} else {
		//	tmp->FixParameter(true); if(i==5) tmp->FixParameter(false);
		//	BOOST_LOG_TRIVIAL(debug)<< *tmp;
			//tmp->SetValue(tmp->GetValue()+0.5);			///((i+1)));
		//	tmp->SetError(tmp->GetValue());
		//	if (!tmp->GetValue())
		//		tmp->SetError(1.);
		//}
		startInt[i] = tmp->GetValue();
	}

	BOOST_LOG_TRIVIAL(info)<< "LH with following parameters: " << esti->controlParameter(par);
	for (unsigned int i = 0; i < par.GetNDouble(); i++) {
		BOOST_LOG_TRIVIAL(info)<< par.GetDoubleParameter(i)->GetName() << " = " << par.GetDoubleParameter(i)->GetValue();
	}

	// std::cout << "Fixing 5 of 7 parameters " << std::endl;
	//for(unsigned int i=2; i<par.GetNDouble(); i++){
	//    par.GetDoubleParameter(i).FixParameter(true);
	//  }

	BOOST_LOG_TRIVIAL(info)<< "Start Fit";
	std::shared_ptr<FitResult> genResult = opti->exec(par);
	BOOST_LOG_TRIVIAL(info)<< "Final LH = " << genResult->getResult();

	BOOST_LOG_TRIVIAL(info)<< "Optimierte intensitäten: " << esti->controlParameter(par);
	for (unsigned int i = 0; i < par.GetNDouble(); i++) {
		BOOST_LOG_TRIVIAL(info)<< par.GetDoubleParameter(i)->GetName() << " = " << par.GetDoubleParameter(i)->GetValue()
		<< "   [ start: " << startInt[i] << " ," << " optimal: " << optiInt[i] << " ]";
	}

	/*AmplitudeSetup iniTrue(resoFile);	//put start parameters here
	std::shared_ptr<Amplitude> trueAmp(
			new AmpSumIntensity(iniTrue, AmpSumIntensity::normStyle::none,
					std::shared_ptr<Efficiency>(new UnitEfficiency()),
					myReader->getNEvents()));
	ParameterList truePar;
	trueAmp->fillStartParVec(truePar); //true values
	genResult->setTrueParameters(truePar);
	genResult->print();
	amps->printFractions();*/

	string output_file_path = output_directory + "/fitresult.txt";
	if (output_file_suffix != "")
		output_file_path = output_directory + "/fitresult_" + output_file_suffix
				+ ".txt";
	//genResult->writeText(output_file_path);
	output_file_path = output_directory + "/simplefitresult.txt";
	if (output_file_suffix != "")
		output_file_path = output_directory + "/simplefitresult_"
				+ output_file_suffix + ".txt";
	//genResult->writeSimpleText(output_file_path);

	//  if(useFctTree){
	//    BOOST_LOG_TRIVIAL(debug)<<physicsTree<<std::endl;
	//    BOOST_LOG_TRIVIAL(debug)<<phspTree<<std::endl;
	//  }

	if (!resultGen)
		return 0;

	//Plot result
	TH2D* bw12 = new TH2D("bw12", "inv. mass-sq of particles 1&2 Generated",
			1000, 0., 10., 1000, 0., 10.);
	bw12->GetXaxis()->SetTitle("m_{12}^{2} / GeV^{2}");
	bw12->GetXaxis()->CenterTitle();
	bw12->GetYaxis()->SetTitle("#");
	bw12->GetYaxis()->CenterTitle();
	TH2D* bw13 = new TH2D("bw13", "inv. mass-sq of particles 1&3 Generated",
			1000, 0., 10., 1000, 0., 10.);
	bw13->GetXaxis()->SetTitle("m_{13}^{2} / GeV^{2}");
	bw13->GetXaxis()->CenterTitle();
	bw13->GetYaxis()->SetTitle("#");
	bw13->GetYaxis()->CenterTitle();
	TH2D* bw23 = new TH2D("bw23", "inv. mass-sq of particles 2&3 Generated",
			1000, 0., 10., 1000, 0., 10.);
	bw23->GetXaxis()->SetTitle("m_{23}^{2} / GeV^{2}");
	bw23->GetXaxis()->CenterTitle();
	bw23->GetYaxis()->SetTitle("#");
	bw23->GetYaxis()->CenterTitle();

	JakeReader myReaderPHSP(input_file_path, "kin");
	unsigned int maxEventsPHSP = myReaderPHSP.getNEvents();
	//double masssq12PHSP, masssq13PHSP, masssq23PHSP;
	TH2D* bw12PHSP = new TH2D("bw12PHSP", "inv. mass-sq of particles 1&2 PHSP",
			1000, 0., 10., 1000, 0., 10.);
	bw12PHSP->GetXaxis()->SetTitle("m_{12}^{2} / GeV^{2}");
	bw12PHSP->GetXaxis()->CenterTitle();
	bw12PHSP->GetYaxis()->SetTitle("#");
	bw12PHSP->GetYaxis()->CenterTitle();
	TH2D* bw13PHSP = new TH2D("bw13PHSP", "inv. mass-sq of particles 1&3 PHSP",
			1000, 0., 10., 1000, 0., 10.);
	bw13PHSP->GetXaxis()->SetTitle("m_{13}^{2} / GeV^{2}");
	bw13PHSP->GetXaxis()->CenterTitle();
	bw13PHSP->GetYaxis()->SetTitle("#");
	bw13PHSP->GetYaxis()->CenterTitle();
	TH2D* bw23PHSP = new TH2D("bw23PHSP", "inv. mass-sq of particles 2&3 PHSP",
			1000, 0., 10., 1000, 0., 10.);
	bw23PHSP->GetXaxis()->SetTitle("m_{23}^{2} / GeV^{2}");
	bw23PHSP->GetXaxis()->CenterTitle();
	bw23PHSP->GetYaxis()->SetTitle("#");
	bw23PHSP->GetYaxis()->CenterTitle();

	TH2D* bw12FIT = new TH2D("bw12FIT",
			"inv. mass-sq of particles 1&2 FitResult", 1000, 0., 10., 1000, 0.,
			10.);
	bw12FIT->GetXaxis()->SetTitle("m_{12}^{2} / GeV^{2}");
	bw12FIT->GetXaxis()->CenterTitle();
	bw12FIT->GetYaxis()->SetTitle("#");
	bw12FIT->GetYaxis()->CenterTitle();
	TH2D* bw13FIT = new TH2D("bw13FIT",
			"inv. mass-sq of particles 1&3 FitResult", 1000, 0., 10., 1000, 0.,
			10.);
	bw13FIT->GetXaxis()->SetTitle("m_{13}^{2} / GeV^{2}");
	bw13FIT->GetXaxis()->CenterTitle();
	bw13FIT->GetYaxis()->SetTitle("#");
	bw13PHSP->GetYaxis()->CenterTitle();
	TH2D* bw23FIT = new TH2D("bw23FIT",
			"inv. mass-sq of particles 2&3 FitResult", 1000, 0., 10., 1000, 0.,
			10.);
	bw23FIT->GetXaxis()->SetTitle("m_{23}^{2} / GeV^{2}");
	bw23FIT->GetXaxis()->CenterTitle();
	bw23FIT->GetYaxis()->SetTitle("#");
	bw23FIT->GetYaxis()->CenterTitle();

	TH2D* bw12DIFF = new TH2D("bw12DIFF",
			"inv. mass-sq of particles 1&2 FitResult", 1000, 0., 10., 1000, 0.,
			10.);
	bw12DIFF->GetXaxis()->SetTitle("m_{12}^{2} / GeV^{2}");
	bw12DIFF->GetXaxis()->CenterTitle();
	bw12DIFF->GetYaxis()->SetTitle("#");
	bw12DIFF->GetYaxis()->CenterTitle();
	TH2D* bw13DIFF = new TH2D("bw13DIFF",
			"inv. mass-sq of particles 1&3 FitResult", 1000, 0., 10., 1000, 0.,
			10.);
	bw13DIFF->GetXaxis()->SetTitle("m_{13}^{2} / GeV^{2}");
	bw13DIFF->GetXaxis()->CenterTitle();
	bw13DIFF->GetYaxis()->SetTitle("#");
	bw13PHSP->GetYaxis()->CenterTitle();
	TH2D* bw23DIFF = new TH2D("bw23DIFF",
			"inv. mass-sq of particles 2&3 FitResult", 1000, 0., 10., 1000, 0.,
			10.);
	bw23DIFF->GetXaxis()->SetTitle("m_{23}^{2} / GeV^{2}");
	bw23DIFF->GetXaxis()->CenterTitle();
	bw23DIFF->GetYaxis()->SetTitle("#");
	bw23DIFF->GetYaxis()->CenterTitle();

	double masssq12, masssq13, masssq23;
	for (unsigned int i = 0; i < myReader->getNEvents(); i++) {
		Event event(myReader->getEvent(i));

		//myReader.getEvent(-1, a, b, masssq);
		//if(!myReader.getEvent(i, event)) continue; TODO: try exception
		if (!event.getNParticles() == 3)
			continue;
		//if(!event) continue;
		//cout << "Event: \t" << i << "\t NParticles: \t" << event.getNParticles() << endl;
		const Particle &a(event.getParticle(0));
		const Particle &b(event.getParticle(1));
		const Particle &c(event.getParticle(2));
		masssq12 = pow(a.E + b.E, 2) - pow(a.px + b.px, 2) - pow(a.py + b.py, 2)
				- pow(a.pz + b.pz, 2);
		masssq13 = pow(a.E + c.E, 2) - pow(a.px + c.px, 2) - pow(a.py + c.py, 2)
				- pow(a.pz + c.pz, 2);
		masssq23 = pow(b.E + c.E, 2) - pow(b.px + c.px, 2) - pow(b.py + c.py, 2)
				- pow(b.pz + c.pz, 2);

		bw12->Fill(masssq12, masssq13);
		bw13->Fill(masssq13, masssq12);
		bw23->Fill(masssq23, masssq12);
	}

	// TH2D* bw12DIFF = (TH2D*)bw12->Clone("bw12DIFF");
	// TH2D* bw13DIFF = (TH2D*)bw13->Clone("bw13DIFF");
	// TH2D* bw23DIFF = (TH2D*)bw23->Clone("bw23DIFF");

	for (unsigned int i = 0; i < maxEventsPHSP; i++) {
		Event event(myReaderPHSP.getEvent(i));

		//myReader.getEvent(-1, a, b, masssq);
		//if(!myReader.getEvent(i, event)) continue; TODO: try exception
		if (!event.getNParticles() == 3)
			continue;
		//if(!event) continue;
		//cout << "Event: \t" << i << "\t NParticles: \t" << event.getNParticles() << endl;
		const Particle &a(event.getParticle(0));
		const Particle &b(event.getParticle(1));
		const Particle &c(event.getParticle(2));
		masssq12 = pow(a.E + b.E, 2) - pow(a.px + b.px, 2) - pow(a.py + b.py, 2)
				- pow(a.pz + b.pz, 2);
		masssq13 = pow(a.E + c.E, 2) - pow(a.px + c.px, 2) - pow(a.py + c.py, 2)
				- pow(a.pz + c.pz, 2);
		masssq23 = pow(b.E + c.E, 2) - pow(b.px + c.px, 2) - pow(b.py + c.py, 2)
				- pow(b.pz + c.pz, 2);

		bw12PHSP->Fill(masssq12, masssq13);
		bw13PHSP->Fill(masssq13, masssq12);
		bw23PHSP->Fill(masssq23, masssq12);

		vector<double> x;
		x.push_back(sqrt(masssq23));
		x.push_back(sqrt(masssq13));
		x.push_back(sqrt(masssq12));
		//bw12FIT->Fill(masssq12,masssq13,1000*amps->intensity(x,par));
		//  bw13FIT->Fill(masssq13,masssq12,1000*amps->intensity(x,par));
		// bw23FIT->Fill(masssq23,masssq12,1000*amps->intensity(x,par));
	}

	//Generation
	TRandom3 rando;
	TLorentzVector W(0.0, 0.0, 0.0, M);		//= beam + target;

	//(Momentum, Energy units are Gev/C, GeV)
	Double_t masses[3] = { m1, m2, m2 };
	TGenPhaseSpace event;
	event.SetDecay(W, 3, masses);

	TLorentzVector *pGamma, *pPip, *pPim, pPm23, pPm13, pPm12;
	double weight, m23sq, m13sq, m12sq, maxTest = 0;
	ParameterList paras(par);
	if (useFctTree) {
		paras.RemoveDouble("ma");
		paras.RemoveDouble("mb");
		paras.RemoveDouble("mc");
	}

	BOOST_LOG_TRIVIAL(info)<< "Einschwingen";
	unsigned int schwingFactor = 10;
	if (myReader->getNEvents() < 1000)
		schwingFactor = 1000;
	for (unsigned int schwing = 0;
			schwing < schwingFactor * myReader->getNEvents(); schwing++) {
		weight = event.Generate();

		pGamma = event.GetDecay(0);
		pPip = event.GetDecay(1);
		pPim = event.GetDecay(2);

		pPm23 = *pPim + *pPip;
		pPm13 = *pGamma + *pPim;
		pPm12 = *pGamma + *pPip;

		m23sq = pPm23.M2();
		m13sq = pPm13.M2();
		m12sq = pPm12.M2();

		dataPoint point;
		try{
			Kinematics::instance()->FillDataPoint(0,1,m23sq,m13sq,point);
		} catch (BeyondPhsp& ex){
			continue;
		}

		//		m12sq = kin.getThirdVariableSq(m23sq,m13sq);
		//point->setMsq(3,m12sq); point->setMsq(4,m13sq); point->setMsq(5,m23sq);
		//		m12sq=M*M+m1*m1+m2*m2+m3*m3-m13sq-m23sq;
		if (std::fabs(m12sq - kin->getThirdVariableSq(m23sq, m13sq)) > 0.01) {
			std::cout << m12sq << " " << kin->getThirdVariableSq(m23sq, m13sq)
					<< std::endl;
			std::cout << "   " << m23sq << " " << m13sq << " " << m12sq
					<< std::endl;
		}

		//call physics module
		vector<double> x;
		x.push_back(sqrt(m23sq));
		x.push_back(sqrt(m13sq));
		x.push_back(sqrt(m12sq));
		//ParameterList intensL = amps->intensity(x, paras);
		double AMPpdf = amps->intensity(point).GetDoubleParameterValue(0);
		//double AMPpdf = intensL.GetDoubleParameter(0)->GetValue();
		//double AMPpdf = testBW.intensity(x, minPar);

		//mb.setVal(m13);
		//double m13pdf = totAmp13.getVal();//fun_combi2->Eval(m13);
		if (maxTest < (weight * AMPpdf))
			maxTest = (weight * AMPpdf);

	}

	maxTest *= 1.1;
	BOOST_LOG_TRIVIAL(info)<< "Start generation of y pi0 pi0 Dalitz Result";
	unsigned int i = 0;
	do {
		weight = event.Generate();

		pGamma = event.GetDecay(0);
		pPip = event.GetDecay(1);
		pPim = event.GetDecay(2);

		pPm23 = *pPim + *pPip;
		pPm13 = *pGamma + *pPim;
		pPm12 = *pGamma + *pPip;

		m23sq = pPm23.M2();
		m13sq = pPm13.M2();
		m12sq = pPm12.M2();

		dataPoint dataP;
		dataP.setVal(0, m23sq);
		dataP.setVal(1, m13sq);

		// m12sq=M*M-m13sq-m23sq;
		//if(m12sq<0){
		//cout << tmpm12_sq << "\t" << M*M << "\t" << m13_sq << "\t" << m23_sq << endl;
		//continue;
		//  m12sq=0.0001;
		// }

		TParticle fparticleGam(22, 1, 0, 0, 0, 0, *pGamma, W);
		TParticle fparticlePip(211, 1, 0, 0, 0, 0, *pPip, W);
		TParticle fparticlePim(-211, 1, 0, 0, 0, 0, *pPim, W);

		//call physics module
		//dataPoint dataP; dataP.setVal("m23sq",m23sq);	dataP.setVal("m13sq",m13sq);
		//        vector<double> x;
		//        x.push_back(sqrt(m23sq));
		//        x.push_back(sqrt(m13sq));
		//        x.push_back(sqrt(m12sq));
		double AMPpdf = amps->intensity(dataP).GetDoubleParameterValue(0);
		//double AMPpdf = amps->intensity(x, par);

		double test = rando.Uniform(0, maxTest);

		//mb.setVal(m13);
		//double m13pdf = totAmp13.getVal();//fun_combi2->Eval(m13);
		if (maxTest < (weight * AMPpdf))
			cout << "Einschwingen zu kurz!" << endl;
		if (test < (weight * AMPpdf)) {
			i++;

			bw12FIT->Fill(m12sq, m13sq);
			bw13FIT->Fill(m13sq, m12sq);
			bw23FIT->Fill(m23sq, m12sq);

			if(i%1000 == 0) BOOST_LOG_TRIVIAL(debug)<< "Event " << i;
		}


	} while (i < (myReader->getNEvents()/10.));

	bw12DIFF->Add(bw12, 1.0);
	bw23DIFF->Add(bw23, 1.0);
	bw13DIFF->Add(bw13, 1.0);
	bw12DIFF->Divide(bw12FIT);
	bw23DIFF->Divide(bw23FIT);
	bw13DIFF->Divide(bw13FIT);
	// bw12DIFF = new TH2D(*bw12 - *bw12FIT);
	// bw23DIFF = new TH2D(*bw23 - *bw23FIT);
	// bw13DIFF = new TH2D(*bw13 - *bw13FIT);

	boost::filesystem::path output_file(output_filename);
	output_file_path = output_directory + "/" + output_filename;
	if (output_file_suffix != "")
		output_file_path = output_directory + "/" + output_file.stem().string()
				+ "_" + output_file_suffix + output_file.extension().string();

	TFile output(output_file_path.c_str(), "RECREATE", "ROOT_Tree");
	bw12->Write();
	bw13->Write();
	bw23->Write();
	bw12PHSP->Write();
	bw13PHSP->Write();
	bw23PHSP->Write();
	bw12FIT->Write();
	bw13FIT->Write();
	bw23FIT->Write();
	bw12DIFF->Write();
	bw13DIFF->Write();
	bw23DIFF->Write();
	output.Write();
	output.Close();

	BOOST_LOG_TRIVIAL(info)<< "Done";

	return 0;
}
Beispiel #22
0
void acc_zone(){

	TRandom3 rndgen;

  //efficienze
    float eps1 [3][3] = {{0.7498,0.729,0.725},{0.746,0.713,0.7336},{0.7833,0.7471,0.7786}};
    float eps2 [3][3] = {{0.6204,0.5303,0.5673},{0.6307,0.5626,0.6080},{0.7440,0.6701,0.7241}};
    float eps3 [3][3] = {{0.5743,0.4255,0.6121},{0.6176,0.4701,0.6620},{0.7229,0.6124,0.7621}};
    double  rxmax, rymax, rD12, rD23, reps1[3][3], reps2[3][3], reps3[3][3];
    int cx1, cx2, cx3, cy1, cy2, cy3;
  float s_eps1 = 0.003;
  float s_eps2 = 0.003;
  float s_eps3 = 0.003;
  double theta, W1,W2,W3, phi,x1,x2,x3,y1,y2,y3;
  int j = 0;
  
 TH1F* hacc = new TH1F("a","Distribuzione accettanza; a; # esperimenti", 100, 0.2, 0.3);
 TH1F* haccA = new TH1F("aA","Distribuzione accettanza; aA (cm^2); # esperimenti", 100, 400, 600);

 TFile rfile("accettanza_zone.root","RECREATE");

  for (int a = 1; a <= nexp; a++) { 
    cout << "Experiment n. " << a << ": " << endl;
      rxmax = xmax + rndgen.Uniform(2*s_xmax)-s_xmax;
      rymax = ymax + rndgen.Uniform(2*s_ymax)-s_ymax;
      rD12 = D12 + rndgen.Uniform(2*s_D12)-s_D12;
      rD23 = D23 + rndgen.Uniform(2*s_D23)-s_D23;
      for (int m = 0; m < 3; m++) {
	for (int n = 0; n < 3; n++) {
	  reps1[m][n] = rndgen.Gaus(eps1[m][n],s_eps1); //inserire distribuzione corretta
	  reps2[m][n] = rndgen.Gaus(eps2[m][n],s_eps2);
	  reps3[m][n] = rndgen.Gaus(eps3[m][n],s_eps3);
	}
      }
    for (int i = 1; i <= imax;) {
            
      theta = rndgen.Uniform(2*atan(1.)); 
      W1 = rndgen.Uniform(1);
      if (sin(theta)*pow(cos(theta),2) > W1) { // distribuzione: cos^2(theta) dcos(theta)
	i+=1;
	//	if (i%int(double(imax)/10) == 0) cout << double(i)/double(imax)*100 << "%" << endl;
	phi = rndgen.Uniform(8*atan(1.));
	x2 = (rndgen.Uniform(rxmax)-rxmax/2.);
	y2 = (rndgen.Uniform(rymax)-rymax/2.);
	x1 = tan(theta)*cos(phi)*rD12 + x2;
	y1 = tan(theta)*sin(phi)*rD12 + y2;
	x3 = -tan(theta)*cos(phi)*rD23+x2;
	y3 = -tan(theta)*sin(phi)*rD23 + y2;
	W1 = rndgen.Uniform(1);
	W2 = rndgen.Uniform(1);
	W3 = rndgen.Uniform(1);

	cx1 = cell(x1,rxmax);
	cx2 = cell(x2,rxmax);
	cx3 = cell(x3,rxmax);
	cy1 = cell(y1,rymax);
	cy2 = cell(y2,rymax);
	cy3 = cell(y3,rymax);

	if ((pow(x1,2) <= pow(rxmax,2)/4) && (pow(y1,2) <= pow(rymax,2)/4) && (pow(x3,2) <= pow(rxmax,2)/4) && (pow(y3,2) <= pow(rymax,2)/4) && W1 < reps1[cx1][cy1] && W2 < reps2[cx2][cy2] && W3 < reps3[cx3][cy3]){
	  
	  j+=1;}
      }
    }

    cout << "Generati: " << imax << endl;
    cout << "Accettati: " << j << endl;
    cout << "Accettanza: " << double(j)/double(imax) << endl;
hacc->Fill(double(j)/double(imax));   
haccA->Fill(double(j)/double(imax)*rxmax*rymax); //le moltiplico anche per l'area perché nel flusso accettanza e area compaiono insieme
    j = 0;
  }
  cout << "Accettanza media: " << hacc->GetMean()*xmax*ymax << endl;
  hacc->Write();
  haccA->Write();
}
Beispiel #23
0
void acc_media(){

	TRandom3 rndgen;

  //efficienze
  //  float eps1 [3][3] = {{0.612,0.662,0.762},{0.425,0.470,0.612},{0.574,0.618,0.722}};
	double  rxmax, rymax, rD12, rD23, reps1, reps2, reps3; 
  float eps1 = 0.745;
  float s_eps1 = 0.003;
  float eps2 = 0.5658;
  float s_eps2 = 0.003;
  float eps3 = 0.6066;
  float s_eps3 = 0.003;
  double theta, W1,W2,W3, phi,x1,x2,x3,y1,y2,y3;
  int j = 0;
  
 TH1F* hacc = new TH1F("a","Distribuzione accettanza; a; # esperimenti", 100, 0.2, 0.3);
 TH1F* haccA = new TH1F("aA","Distribuzione accettanza; aA (cm^2); # esperimenti", 100, 400, 600);

 TFile rfile("accettanza_media.root","RECREATE");

  for (int a = 1; a <= nexp; a++) { 
    cout << "Experiment n. " << a << ": " << endl;
      rxmax = xmax + rndgen.Uniform(2*s_xmax)-s_xmax;
      rymax = ymax + rndgen.Uniform(2*s_ymax)-s_ymax;
      rD12 = D12 + rndgen.Uniform(2*s_D12)-s_D12;
      rD23 = D23 + rndgen.Uniform(2*s_D23)-s_D23;
      reps1 = rndgen.Gaus(eps1,s_eps1); //inserire distribuzione corretta
      reps2 = rndgen.Gaus(eps2,s_eps2);
      reps3 = rndgen.Gaus(eps3,s_eps3);
    for (int i = 1; i <= imax;) {
            
      theta = rndgen.Uniform(2*atan(1.)); 
      W1 = rndgen.Uniform(1);
      if (sin(theta)*pow(cos(theta),2) > W1) { // distribuzione: cos^2(theta) dcos(theta)
	i+=1;
	//	if (i%int(double(imax)/10) == 0) cout << double(i)/double(imax)*100 << "%" << endl;
	phi = rndgen.Uniform(8*atan(1.));
	x2 = (rndgen.Uniform(rxmax)-rxmax/2.);
	y2 = (rndgen.Uniform(rymax)-rymax/2.);
	x1 = tan(theta)*cos(phi)*rD12 + x2;
	y1 = tan(theta)*sin(phi)*rD12 + y2;
	x3 = -tan(theta)*cos(phi)*rD23+x2;
	y3 = -tan(theta)*sin(phi)*rD23 + y2;
	W1 = rndgen.Uniform(1);
	W2 = rndgen.Uniform(1);
	W3 = rndgen.Uniform(1);
      
	if ((pow(x1,2) <= pow(rxmax,2)/4) && (pow(y1,2) <= pow(rymax,2)/4) && (pow(x3,2) <= pow(rxmax,2)/4) && (pow(y3,2) <= pow(rymax,2)/4) && W1 < reps1 && W2 < reps2 && W3 < reps3){
	  
	  j+=1;}
      }
    }

    cout << "Generati: " << imax << endl;
    cout << "Accettati: " << j << endl;
    cout << "Accettanza: " << double(j)/double(imax) << endl;
hacc->Fill(double(j)/double(imax));   
haccA->Fill(double(j)/double(imax)*rxmax*rymax); //le moltiplico anche per l'area perché nel flusso accettanza e area compaiono insieme
    j = 0;
  }
  cout << "Accettanza media: " << hacc->GetMean()*xmax*ymax << endl;
  hacc->Write();
  haccA->Write();
}
void SimRC_eventisuareatotale(int seed)
{
	double x[N_events], y[N_events], z[N_events], zfin[N_events], x1final[N_events], y1final[N_events], xfin[N_events], yfin[N_events], phi[N_events], theta[N_events], x1[N_events], y1[N_events], z1[N_events], phi1[N_events], theta1[N_events]; // all the necessary array
	double uniform, u;
	TRandom3 *rand = new TRandom();
	rand->SetSeed(seed); // to set the seed
	int counterge = 0;		//to count good events
	int k = 0;		//dynamic counter 
	for (int i = 0; i < N_events; i++) {
		//rand->SetSeed(0);		//forget about this, it's wrong; I kept it only to remember not to use it
		x[i] = rand->Uniform(-square,L+square);		//generates N_events values along X
		y[i] = rand->Uniform(-square, D+square);
		phi[i] = rand->Uniform(0, 2*PI);
		uniform = 0;
		u = 2;
		while (M*u > M*cos(uniform)*cos(uniform)*sin(uniform)) {		//rejection condition
			u = rand->Uniform(0, 1);
			uniform = rand->Uniform(0, PI / 2);
		};
		theta[i] = uniform;
		if (x[i] >= 0 && x[i] <= L && y[i] >= 0 && y[i] <= D) {
			z[i] = 0;
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x[i];
			y1final[counterge] = y[i];
			counterge++; 
			k++;
			//cout << k << endl;
		}
		else if (x[i] < 0 && phi[i] >PI / 2 && phi[i] < PI && (y[i] - x[i] * tan(phi[i])) > 0 && (y[i] - x[i] * tan(phi[i])) < D && theta[i] > atan(x[i] / (cos(phi[i]) * sp))) {
			z[i] = -x[i] / (cos(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = 0;
			y1final[counterge] = (y[i] - x[i] * tan(phi[i]));
			counterge++;
			k++;
			//cout << k << endl;			
		}
		else if (x[i] < 0 && phi[i] >PI / 2 && phi[i] < PI && (y[i] + x[i] * tan(PI-phi[i])) > D && x[i]-(D-y[i])/ tan(PI-phi[i]) > 0 && x[i] - (D - y[i]) / tan(PI-phi[i]) <L && theta[i] > atan((y[i]-D) / (sin(PI-phi[i]) * sp))) {
			z[i] = -(y[i] - D) / (sin(PI - phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			y1final[counterge] = D;
			x1final[counterge] = x[i] - (D - y[i]) / tan(PI - phi[i]);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] < 0 && phi[i] >PI && phi[i] < 3*PI/2 && (y[i] - x[i] * tan(phi[i])) > 0 && (y[i] - x[i] * tan(phi[i])) < D && theta[i] > atan(-x[i] / (cos(PI-phi[i]) * sp))) {
			z[i] = -x[i] / (cos(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = 0;
			y1final[counterge] = (y[i] - x[i] * tan(phi[i]));
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] < 0 && phi[i] >PI && phi[i] < 3 * PI / 2 && x[i] - y[i] / tan(phi[i]) > 0 && x[i] - y[i] / tan(phi[i]) < L&& (y[i] - x[i] * tan(phi[i])) < 0 && theta[i] > atan(-y[i] / (sin(phi[i]-PI) * sp))) {
			z[i] = y[i] / (sin(phi[i] - PI) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			y1final[counterge] = 0;
			x1final[counterge] = x[i] - y[i] / tan(phi[i]);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] > L && phi[i] > 0 && phi[i] < PI / 2 && (y[i] - (x[i] - L) * tan(phi[i])) > 0 && (y[i] - (x[i] - L) * tan(phi[i])) < D && theta[i] > atan((x[i] - L) / (cos(phi[i]) * sp))) {
			z[i] = -(x[i] - L) / (cos(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = L;
			y1final[counterge] = y[i] - (x[i] - L) * tan(phi[i]);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] > L && phi[i] > 0 && phi[i] < PI / 2 && (y[i] - (x[i] - L) * tan(phi[i])) > D && x[i] - (y[i] - D) / tan(phi[i]) > 0 && x[i] - (y[i] - D) / tan(phi[i]) < L && theta[i] > atan((y[i]-D) / (sin(phi[i]) * sp))) {
			z[i] = -(y[i] - D) / (sin(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			y1final[counterge] = D;
			x1final[counterge] = x[i] - (y[i] - D) / tan(phi[i]);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] > L && phi[i] > 3 * PI / 2 && (y[i] + (x[i]-L) / tan(phi[i] - 3 * PI / 2)) > 0  && (y[i] + (x[i]-L) / tan(phi[i] - 3 * PI / 2)) < D && theta[i] > atan((x[i]-L) / (sin(phi[i] - 3 * PI / 2) * sp))) {
			z[i]  = -(x[i] - L) / (sin(phi[i] - 3 * PI / 2) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = L;
			y1final[counterge] = y[i] + (x[i] - L) / tan(phi[i] - 3 * PI / 2);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] > L && phi[i] > 3 * PI / 2 && x[i] + y[i] * tan(phi[i] - 3 * PI / 2) > 0 && x[i] + y[i] * tan(phi[i] - 3 * PI / 2) < L && (y[i] + (x[i] - L) / tan(phi[i] - 3 * PI / 2)) < 0 && theta[i] > atan(-y[i] / (sin(2*PI-phi[i]) * sp))) {
			z[i] = y[i] / (sin(2 * PI - phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			y1final[counterge] = 0;
			x1final[counterge] = x[i] + y[i] * tan(phi[i] - 3 * PI / 2);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (y[i] < 0 && phi[i] > PI && phi[i] < 3 * PI/2 && (x[i] - y[i] / tan(phi[i]-PI)) > 0 && (x[i] - y[i] / tan(phi[i]-PI)) < L && theta[i] > atan(-y[i] / (sin(phi[i]-PI) * sp))) {
			z[i] = y[i] / (sin(phi[i]-PI) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x [i] - y[i] / tan(phi[i] - PI);
			y1final[counterge] = 0;
			counterge++;
			k++;
			//cout << k << endl;
			}
		//else if (y[i] < 0 && phi[i] > PI && phi[i] < 3 * PI / 2 && (x[i] - y[i] / tan(phi[i] - PI)) > 0 - D / (tan(phi[i] - PI)) && (x[i] - y[i] / tan(phi[i] - PI)) < 0 && theta[i] > atan(-x[i] / (cos(phi[i]-PI) * sp))) {
		//counterge++;
		//z[i] = -x[i] / (cos(phi[i] - PI) * tan(theta[i]));
		//xfinal[i] = 0;
		//yfinal[i] = -x[i]*tan(phi[i]-PI)+y[i];//correggere
		//k++;
		//cout << k << endl;
		//i++;
		//}
		else if (y[i] < 0 && phi[i] > 3 * PI / 2 && phi[i] < 2 * PI && (x[i] + y[i] / tan(2 * PI - phi[i])) > 0 && (x[i] + y[i] / tan(2*PI-phi[i])) < L && theta[i] > atan(-y[i] / (sin(2*PI-phi[i]) * sp))) {
			z[i] = y[i] / (sin(2*PI-phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x[i] + y[i] / tan(2 * PI - phi[i]);
			y1final[counterge] = 0;
			counterge++;
			k++;
			//cout << k << endl;
		}
		//else if (y[i] < 0 && phi[i] > 3 * PI / 2 && (x[i] + y[i] / tan(2 * PI - phi[i])) > L && (x[i] + y[i] / tan(phi[i])) < L + D / (tan(2 * PI - phi[i])) && theta[i] > atan((x[i] - L) / (cos(2 * PI - phi[i]) * sp))) {
		//counterge++;
		//z[i] = (x[i] - L) / (cos(2 * PI - phi[i]) * tan(theta[i]));
		//xfinal[i] = L;		
		//yfinal[i] = (x[i] - L) * tan(2 * PI - phi[i]) + y[i];//correggere
		//k++;
		//cout << k << endl;
		//i++;
		//}
		else if (y[i] > D && phi[i] > 0 && phi[i]  < PI / 2 && (x[i] - (y[i] - D) / tan(phi[i])) > 0 && (x[i] - (y[i] - D) / tan(phi[i])) < L && theta[i] > atan((y[i] - D) / (sin(phi[i]) * sp))) {
			z[i] = -(y[i] - D) / (sin(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x[i] - (y[i] - D) / tan(phi[i]);
			y1final[counterge] = D;
			counterge++;
			k++;
			//cout << k << endl;
		}
		//else if (y[i] > D && phi[i] > 0 && phi[i]  < PI / 2 && (x[i] - (y[i] - D) / tan(phi[i])) > L && (x[i] - (y[i] - D) / tan(phi[i])) < L + D / (tan(phi[i])) && theta[i] > atan((x[i]-L) / (cos(phi[i]) * sp))) {
		//counterge++;
		//z[i] = (x[i] - L) / (cos(phi[i]) * tan(theta[i]));
		//xfinal[i] = L;		//correggere
		//yfinal[i] = y[i] - (x[i]-L)/tan(phi[i]);
		//k++;
		//cout << k << endl;
		//i++;
		//}
		else if (y[i] > D && phi[i] > PI / 2 && phi[i] < PI && (x[i] + (y[i] - D) / tan(PI - phi[i])) > 0 && (x[i] + (y[i] - D) / tan(PI - phi[i])) < L  && theta[i] > atan ( (y[i] - D) / (sin(PI-phi[i]) * sp))) {
			z[i] = -(y[i] - D) / (sin(PI-phi[i]) * tan(theta[i])); 
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x[i] + (y[i] - D) / tan(PI - phi[i]);
			y1final[counterge] = D;
			counterge++;
			k++;
			//cout << k << endl;
		}
		//else if (y[i] > D && phi[i] > PI / 2 && phi[i] < PI && (x[i] + (y[i] - D) / tan(PI - phi[i])) > 0 - D / (tan(PI - phi[i])) && (x[i] + (y[i] - D) / tan(PI - phi[i])) < 0  && theta[i] > atan(-x[i] / (cos(PI-phi[i]) * sp))) {
		//counterge++;
		//z[i] = -x[i] / (cos(PI - phi[i]) * tan(theta[i]));
		//xfinal[i] = 0;
		//yfinal[i] = y[i]+x[i]/tan(PI-phi[i]);//correggere
		//k++;
		//cout << k << endl;
		//i++;
		//}
		else continue;		//calculations need to be checked

	}
	
	double counter = 0;		// counter for coincidence events
	double counterz = 0;
	double counterzcoin = 0;
	for (int i = 0; i < counterge; i++) {
		xfin[i] = x1[i] - (H + z1[i]) * tan(theta1[i]) * cos(phi1[i]);		// these should be correct
		yfin[i] = y1[i] - (H + z1[i]) * tan(theta1[i]) * sin(phi1[i]);
		if (0 <= xfin[i] && xfin[i] <= L && yfin[i] >= 0 && yfin[i] <= D) counter++;
		if (z1[i] != 0) counterz++;		//counts the event fallen on the sp thick side
		if (0 <= xfin[i] && xfin[i] <= L && yfin[i] >= 0 && yfin[i] <= D && z[i] != 0) counterzcoin++;
	}
	
	cout << "Il numero di eventi e': " << counterge << endl << "Il numero di eventi in coincidenza e': " << counter << endl << "La percentuale in coincidenza e': " << counter/counterge * 100  << "%" << endl << "Il numero di eventi totali controllato e': " << N_events << endl << "Il numero totale buono di eventi e': " << counterge << endl << "Il numero totale di eventi passato lateralmente e': " << counterz << endl << "Il numero totale di eventi passati lateralmente e in coincidenza e' : " << counterzcoin << endl;		// this ends the program
	
	/*const int n1 = 2*counterge;		//I write the files all in one file to plot in the end
	double xfinal1[n1];
	double yfinal1[n1];
	double zfinal1[n1];
	for (int i = 0; i < counterge; i++) {
		xfinal1[i] = x1final[i];
		yfinal1[i] = y1final[i];
		zfinal1[i] = z1[i];
		xfinal1[i + counterge] = xfin[i];
		yfinal1[i + counterge] = yfin[i];
		zfinal1[i + counterge] = -H;
	}
		
	TCanvas *c1 = new TCanvas("c1", "", 200, 10, 600, 400);		//finally the plot
	c1->SetFillColor(10);
	c1->SetGrid();
	TGraph2D *grafico = new TGraph2D(n1, xfinal1, yfinal1, zfinal1);
	grafico->SetTitle("Slabs coincidence 3D, H = 0.08 m, square = 10 m");
	grafico->SetMarkerColor(2);
	grafico->GetXaxis()->SetTitle("X-Axis [m]");
	grafico->GetYaxis()->SetTitle("Y-Axis [m]");
	grafico->GetZaxis()->SetTitle("Z-Axis [m]");
	grafico->Draw("PCOL");*/
	return;
} 
Beispiel #25
0
void keys(TString sam="0", TString smooth = "100") {
  gSystem->Load("libHtml");
  gSystem->Load("libMinuit");
  gSystem->Load("libRooFitCore.so");
  gSystem->Load("libRooFitModels.so");
  using namespace RooFit;
  time_t start,end;
  time (&start);
  double dif;
  RooRealVar mmiss2("candM2","candM2",-4,12);
  RooRealVar pstarl("candPstarLep","candPstarLep",0.,2.4);

  RooArgSet myVars(mmiss2,pstarl);

  TString inputfile = "fitSamples/pdfSample"; inputfile += sam; inputfile += ".root";
  cout << "File = " << inputfile << endl;	
  TChain c("ntp1");
  c.Add(inputfile);
  RooDataSet  data("data","data",myVars);

  Int_t MCType,MCSubmode,MCDssmode,MCD,MCPions,MCCombB,MCCombDs,MCDoubleSL,
    candTruLep,candDstarType,isBzero,isSP6,MCTaumode,trueLepCharge;
  Float_t candM2,candPstarLep;
  Float_t truePPi0,trueDssPPi0,CTL,CTV,Chi,Q2,trueDmass;
  c.SetBranchAddress("MCType",&MCType);
  c.SetBranchAddress("MCSubmode",&MCSubmode);
  c.SetBranchAddress("MCDssmode",&MCDssmode);
  c.SetBranchAddress("MCD",&MCD);
  c.SetBranchAddress("MCPions",&MCPions);
  c.SetBranchAddress("MCCombB",&MCCombB);
  c.SetBranchAddress("MCCombDs",&MCCombDs);
  c.SetBranchAddress("MCDoubleSL",&MCDoubleSL);
  c.SetBranchAddress("candLepTru",&candTruLep);
  c.SetBranchAddress("candDstarType",&candDstarType);
  c.SetBranchAddress("isBzero",&isBzero);
  c.SetBranchAddress("isSP6",&isSP6);
  c.SetBranchAddress("MCTaumode",&MCTaumode);
  c.SetBranchAddress("truePPi0",&truePPi0);
  c.SetBranchAddress("trueDssPPi0",&trueDssPPi0);
  c.SetBranchAddress("trueCTL",&CTL);
  c.SetBranchAddress("trueCTV",&CTV);
  c.SetBranchAddress("trueChi",&Chi);
  c.SetBranchAddress("trueQ2",&Q2);
  c.SetBranchAddress("trueLepCharge",&trueLepCharge);
  c.SetBranchAddress("trueDmass",&trueDmass);
  c.SetBranchAddress("candM2",&candM2);
  c.SetBranchAddress("candPstarLep",&candPstarLep);
  TRandom3 rand; int ran;
  int transform = 1;
  TCanvas mm("mm","KEYS fits to mmiss-pstarl",1200,800);
  gStyle->SetPalette(1);
  double All = 8;
  TH2F rotated("rotated","Rotated m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  TH2F ori("ori","Original m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  //TH2F totcov("ori2","Original m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  double r11, r12, Xmean, Ymean;
  double x[] = {-2,-1,1,2};
  double y[] = {-4,-2,2,4};
  if(transform ==1){
    c.Draw("candPstarLep:candM2>>cov(200,-4,12,200,0,2.4)","","contz");
    TH2F *totcov = (TH2F*)gDirectory->Get("cov");
    //for(int i=0;i<4;i++)totcov.Fill(x[i],y[i]);
    double xx = totcov->GetRMS(1); xx = xx*xx;
    double yy = totcov->GetRMS(2); yy = yy*yy;
    double xy = totcov->GetCovariance();
    Xmean = totcov->GetMean(1);
    Ymean = totcov->GetMean(2);
    double lambda = (-sqrt(xx*xx-2*xx*yy+4*xy*xy+yy*yy)+xx+yy)/2;
    double lambda2 = (sqrt(xx*xx-2*xx*yy+4*xy*xy+yy*yy)+xx+yy)/2;
    if(lambda2>lambda) lambda = lambda2;
    r11 = (lambda-yy)/xy;
    r12 = -1/sqrt(r11*r11+1);
    r11 = -r11/sqrt(r11*r11+1);
    if(r12*r11>0&&r12<0 || r12*r11<0&&r11<0){
      r12 = -r12;
      r11 = -r11;
    }
    cout<<"RMSx "<<xx<<", RMSy "<<yy<<", lambda "<<lambda<<" and covariance "<<xy<<endl;
  }
  double mmp, plp;
  double entries = c.GetEntries();
  //entries = 4;
  for (int evt = 0 ; evt < entries; evt ++) {
    ran = rand.Uniform(entries);
    //c.GetEvent(ran);
    c.GetEvent(evt);
    double Mx = candM2-Xmean, Py = candPstarLep-Ymean;
    mmp = r11*(Mx)+r12*(Py);
    plp = -r12*(Mx)+r11*(Py);
    ori.Fill(Mx,Py);
    rotated.Fill(mmp,plp);
    mmiss2.setVal(candM2);
    pstarl.setVal(candPstarLep);
//     if (MCType == 0)
//       totWeight.setVal(myWM->getCombWeight(MCCombB,MCCombDs,MCDoubleSL,candTruLep));
//     else
//       totWeight.setVal(myWM->getEventWeight(candType,candDstarType,MCType,MCSubmode,MCDssmode,MCD,MCPions,
// 					    isBzero,isSP6,MCTaumode,truePPi0,trueDmass,CTL,CTV,Chi,Q2,
// 					    trueLepCharge,candM2));
    data.add(RooArgSet(mmiss2,pstarl));
  }
  //data.setWeightVar(totWeight);
  ori.Draw("contz");
  mm.SaveAs("original.eps");
  rotated.Draw("contz");
  mm.SaveAs("rotated.eps");
  cout<<"("<<r11<<", "<<r12<<") and covariance "<<rotated.GetCovariance()<<endl;
  return;

  double smoo = smooth.Atof()/100.;
  Roo2DKeysPdf DPpdf("DPpdf","DPpdf",mmiss2,pstarl,data,"av",smoo);
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after finding the KEYS function"<<endl;
  time (&start);
  int ntotbin = 800;
  TH2F *h2 = new TH2F("h2","KEYS",ntotbin,-4,12,ntotbin,0,2.4);
  DPpdf.fillHistogram(h2,RooArgList(mmiss2,pstarl));
  TString hname = "AWG82/results/keys/root/hKeys"; hname += sam; hname += "_"; hname += smooth; hname += ".root";
  TFile* hfile = new TFile(hname,"RECREATE"); 
  h2->Write();
  hfile->Close();
  cout<<"KEYS histogram saved in "<<hname<<endl;
  RooDataHist* Rdh2 = new RooDataHist("Rdh2","KEYS",RooArgList(mmiss2,pstarl),h2);
  RooHistPdf* Rh2 = new RooHistPdf("Rh2","KEYS",RooArgList(mmiss2,pstarl),*Rdh2,2);
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after making histogram"<<endl;
  time (&start);

  Float_t xlow,xhigh;
  Int_t nbinx,nbiny,Sam = sam.Atoi();
  xlow = -4;
  xhigh = 12;
  nbinx = 80;
  nbiny = 80;
  if (Sam==0 || Sam==2 || Sam==10 || Sam==12 || Sam == 20 || Sam == 23 || Sam == 26 || Sam == 29) {
    xlow = -2; xhigh = 4;
    if (Sam > 12) {nbinx = 40; nbiny = 40;}
  }
  else if (Sam==1 || Sam==11) {
    xlow = -2; xhigh = 6;
  }
  if (Sam==6 || Sam==7 || Sam==16 || Sam==17) {
    nbinx = 40; nbiny = 40;
  }
  if (Sam==8 || Sam==18) {
    xhigh = 4; nbinx = 40; nbiny = 40;
  }
  if (Sam==9 || Sam==19) {
    nbinx = 40; nbiny = 40;
  }
  if (Sam==21 || Sam==22 || Sam==24 || Sam==25 || Sam==27 || Sam==28 || Sam==30 || Sam==31) {
    xhigh = 8; nbinx = 40; nbiny = 20;
  }
  if (Sam > 31) {
    nbinx = 40; nbiny = 20;
  }

  TString M2titles[] = {"0 < p*_{l} < 1 GeV","1 < p*_{l} < 1.4 GeV","1.4 < p*_{l} < 1.8 GeV",
		      "1.8 < p*_{l} < 2.4 GeV","0 < p*_{l} < 2.4 GeV"};
  TString Pltitles[] = {"-4 < m^{2}_{miss} < 1.5 GeV^{2}","1.5 < m^{2}_{miss} < 12 GeV^{2}",
			"-4 < m^{2}_{miss} < 12 GeV^{2}"};
  TString M2cuts[] = {"candPstarLep<1","candPstarLep>1&&candPstarLep<1.4",
		      "candPstarLep>1.4&&candPstarLep<1.8","candPstarLep>1.8&&candPstarLep<2.4", ""};
  TString Plcuts[] = {"candM2<1.5","candM2>=1.5",""};
  double limits[] = {0, 1, 1.4, 1.8, 2.4};
  int binlim[5];
  for(int i=0;i<5;i++) binlim[i] = limits[i]/2.4*ntotbin;

  TString psname = "AWG82/results/keys/eps/eps2Keys"; psname+=sam; psname+="_";
  psname += smooth; psname += ".ps";
  double tot = 0;
  mm.Print(psname+"[");
  TH1F *hm2[5], *m2[5], *hpl[3], *pl[3];
  TString M2names[5], Plnames[3];
  for(int i=0;i<5;i++){
    M2names[i] = "hm2_"; M2names[i] += i;
    hm2[i] = new TH1F(M2names[i],M2titles[i],ntotbin,-4,12); 
    if(i<3) {
      Plnames[i] = "hpl_"; Plnames[i] += i;
      hpl[i] = new TH1F(Plnames[i],Pltitles[i],ntotbin,0,2.4); 
    }
  }    
  for(int i=0;i<5;i++){
    TString hname = "m2"; hname += i;
    TString vari = "candM2>>"; vari+=hname; vari+="("; vari+= nbinx; vari+=",";vari+= xlow; 
    vari+=",";vari+= xhigh; vari+=")";
    c.Draw(vari,M2cuts[i]);
    m2[i] = (TH1F*)gDirectory->Get(hname);
    m2[i]->SetXTitle("m^{2}_{miss} [GeV^{2}]");
    m2[i]->SetTitle(M2titles[i]);
    m2[i]->Sumw2();
    m2[i]->SetMarkerStyle(20);
    m2[i]->SetMarkerSize(1);
    gStyle->SetOptStat(0);
    if(i<4){
      for(int j=1; j<ntotbin+1; j++){
	double binVal = 0;
	for(int binp = binlim[i]+1; binp < binlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(j,binp)*entries*ntotbin*(xhigh-xlow)/nbinx/16;	
	}
	hm2[i]->SetBinContent(j,binVal);
      }
    } 
    hm2[i]->SetLineColor(4);
    hm2[i]->SetLineWidth(2);
    if(i<4) hm2[4]->Add(hm2[i]);
  }
  int plbinlim[3] = {0,ntotbin*5.5/16,ntotbin};
  for(int i=0;i<3;i++){
    TString hname = "pl"; hname += i;
    TString vari = "candPstarLep>>"; vari+=hname; vari+="("; vari+= nbiny; vari+=",0,2.4)";
    c.Draw(vari,Plcuts[i]);
    pl[i] = (TH1F*)gDirectory->Get(hname);
    pl[i]->SetXTitle("p*_{l} [GeV]");
    pl[i]->SetTitle(Pltitles[i]);
    pl[i]->Sumw2();
    pl[i]->SetMarkerStyle(20);
    pl[i]->SetMarkerSize(1);
    gStyle->SetOptStat(0);
    if(i<2){
      for(int j=1; j<ntotbin+1; j++){
	double binVal = 0;
	for(int binp = plbinlim[i]+1; binp < plbinlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(binp,j)*entries*ntotbin/nbiny;	
	}
	hpl[i]->SetBinContent(j,binVal);
      }
    }
    hpl[i]->SetLineColor(4);
    hpl[i]->SetLineWidth(2);
    if(i<2) hpl[2]->Add(hpl[i]);
  }
  m2[4]->Draw("e1"); hm2[4]->Draw("c same"); mm.Print(psname);
  pl[2]->Draw("e1"); hpl[2]->Draw("c same"); mm.Print(psname);
  for(int i=0;i<4;i++){
    m2[i]->Draw("e1"); hm2[i]->Draw("c same"); mm.Print(psname);
  }
  for(int i=0;i<2;i++){
    pl[i]->Draw("e1"); hpl[i]->Draw("c same"); mm.Print(psname);
  }
  mm.Print(psname+"]");
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after plotting data. Written "<<psname<<endl;
  return; 

} 
Beispiel #26
0
void figureOutpiover2(int ptBin, double ptCutLo, double ptCutHi, int massBin, double mCutLo, double mCutHi, int etaBin, double etaCutLo, double etaCutHi) {

    //OPTIONS AND CUTS------------
    bool useBlueBeam = false;
    bool useYellowBeam = true;
    double PI = 3.14159265359;


    if (useBlueBeam && useYellowBeam) {
        cout << "using both beams" << endl;
    }
    if (useBlueBeam && !useYellowBeam) {
        cout << "using blue beam" << endl;
    }
    if (!useBlueBeam && useYellowBeam) {
        cout << "using yellow beam" << endl;
    }


    //PION PAIR CUTS:
    /*
     double ptCutLo = 4;
     double ptCutHi = 10;
     double mCutLo = .4;
     double mCutHi = 1;
     double etaCutLo = -1.4;
     double etaCutHi = 1.4;
     //*/
    //double phiCutLo = -.5;
    //double phiCutHi = .5;

    //----------------------------


    //LOAD LIBS
    cout << "\n";
    gROOT->Macro("StRoot/LoadLibs.C");
    gSystem->Load("pionPair");
    cout << " loading of pionPair library done" << endl;


    //SET UP INPUT FILE
    //TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/all2012dataAll.root");
    //TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOutputWithinRad/allWithRadcut.root");
    TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOutAllDataTry1/allDataTry1.root");





    //SET UP TREE TO RECEIVE INPUT
    pionPair* pair1 = new pionPair();
    TTree* pairTree = infile->Get("pionPairTree");
    pairTree->SetBranchAddress("pionPair", &pair1);


    //SET UP HISTOGRAMS

    //event variable histograms
    TH1D* hInvarM    = new TH1D("invarM","invarM",80,0,2);
    TH1D* hEtaTot	   = new TH1D("etaTot","etaTot",60,-1.5,1.5);
    TH1D* hPhiR      = new TH1D("hPhiR","hPhiR",60,-4,4);
    TH1D* hPhiS      = new TH1D("hPhiS","hPhiS",60,-4,4);
    TH1D* hPhiSR     = new TH1D("hPhiSR","hPhiSR",60,-4,4);
    TH1D* hTheta     = new TH1D("hTheta","hTheta",30,-0.85,4);
    TH1D* hCosTheta  = new TH1D("hCosTheta","hCosTheta",80,-1,1);
    TH1D* hZ         = new TH1D("hZ","hZ",80,0,1);
    TH1D* hPtot      = new TH1D("hPtot","hPtot",80,0,20);
    TH1D* hPtTOT     = new TH1D("hPt","hPt",80,0,15);

    //histos for asym analysis
    double histMin = -PI;
    double histMax =  PI;
    const int binNumber = 16;

    TH1D * hNumberUp   = new TH1D("hNumberUp","hNumberUp",binNumber,histMin,histMax);
    TH1D * hNumberDown = new TH1D("hNumberDown","hNumberDown",binNumber,histMin,histMax);

    TH1D * hDiff  = new TH1D("hNumberSum","hNumberSum",binNumber,histMin,histMax);
    TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);


    //BEAM POLARIZATION

    ifstream polFile;
    polFile.open("/star/u/klandry/ucladisk/2012IFF/BeamPolarization2012.txt");


    map<int, double> polarizationOfFill_Y;
    map<int, double> polErrOfFill_Y;

    map<int, double> polarizationOfFill_B;
    map<int, double> polErrOfFill_B;



    int    fill;
    int    beamE;
    int    startT;
    string plusminus;

    double pAvrgBlue;
    double pErrAvrgBlue;

    double pInitialBlue;
    double pErrInitialBlue;
    double dPdTBlue;
    double dPdTErrBlue;

    double pAvrgYellow;
    double pErrAvrgYellow;

    double pInitialYellow;
    double pErrInitialYellow;
    double dPdTYellow;
    double dPdTErrYellow;

    string header;

    for (int i=0; i<19; i++) {
        polFile >> header;
    }

    while (!polFile.eof())
    {

        polFile >> fill;
        polFile >> beamE;
        polFile >> startT;

        polFile >> pAvrgBlue;
        polFile >> plusminus;
        polFile >> pErrAvrgBlue;

        polFile >> pInitialBlue;
        polFile >> plusminus;
        polFile >> pErrInitialBlue;

        polFile >> dPdTBlue;
        polFile >> plusminus;
        polFile >> dPdTErrBlue;

        polFile >> pAvrgYellow;
        polFile >> plusminus;
        polFile >> pErrAvrgYellow;

        polFile >> pInitialYellow;
        polFile >> plusminus;
        polFile >> pErrInitialYellow;

        polFile >> dPdTYellow;
        polFile >> plusminus;
        polFile >> dPdTErrYellow;


        polarizationOfFill_B[fill] = pAvrgBlue/100.;
        polErrOfFill_B[fill] = pErrAvrgBlue/100.;

        polarizationOfFill_Y[fill] = pAvrgYellow/100.;
        polErrOfFill_Y[fill] = pErrAvrgYellow/100.;



    }

    double avgPolOfBinUp[binNumber];
    double polOfBinSumUp[binNumber];

    double avgPerrorOfBinUp[binNumber];
    double pErrorOfBinUp[binNumber];

    double avgPolOfBinDown[binNumber];
    double polOfBinSumDown[binNumber];

    double avgPerrorOfBinDown[binNumber];
    double pErrorOfBinDown[binNumber];

    for (int i=0; i<binNumber; i++)
    {
        avgPolOfBinUp[i] = 0;
        polOfBinSumUp[i] = 0;

        avgPerrorOfBinUp[i] = 0;
        pErrorOfBinUp[i] = 0;

        avgPolOfBinDown[i] = 0;
        polOfBinSumDown[i] = 0;

        avgPerrorOfBinDown[i] = 0;
        pErrorOfBinDown[i] = 0;

    }


    //   ======================================================================
    //============================================================================
    //START ANALYSIS==============================================================
    //============================================================================
    //   ======================================================================

    cout << pairTree->GetEntries() << endl;

    cout << "\n";
    cout << "<----STARTING ANALYSIS---->" << endl;
    cout << "\n";


    double blueFillNo;
    double yellowFillNo;

    int bin;

    TLorentzVector sum;
    TLorentzVector sumY;
    TLorentzVector sumB;

    TRandom3 r;


    int totalPairsFinal = 0;


    for (int iPair = 0; iPair < pairTree->GetEntries(); iPair++)
    {
        if (iPair%10000 == 0) {
            cout << "processing pair number " << iPair << endl;
        }
        //cout << "processing pair number " << iPair << endl;


        //if (iPair == 80000){break;}

        pairTree->GetEntry(iPair);




        if (pair1->withinRadius(0.05, 0.3))
        {

            bool triggerFired = false;
            bool fromKaon = false;

            StTriggerId trigId = pair1->triggerIds();


            if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621))
            {
                triggerFired = true;
            }

            if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
            {
                triggerFired = true;
            }


            if (pair1->invarientMass() > .4921 && pair1->invarientMass() < .4990)
            {
                fromKaon = true;
            }



            if (triggerFired)
            {


                blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
                yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam

                //cout << blueFillNo << "  " << yellowFillNo << endl;


                if (polarizationOfFill_B[blueFillNo] == 0 || polarizationOfFill_Y[yellowFillNo] == 0)
                {
                    continue;
                }


                hInvarM->Fill(pair1->invarientMass());

                TVector3 spinVec;


                sum = pair1->piPlusLV() + pair1->piMinusLV();
                sumB = sum; //blue beam.


                //yellow beam must rotate around y axis by pi so the eta cut can be the same for both beams.
                sumY = sum;
                sumY.RotateY(PI);


                double randomSpin = r.Uniform(0, 1);

                int randomSpinBit;

                if (randomSpin >=0 && randomSpin <0.25)  {
                    randomSpinBit = 5;
                }
                if (randomSpin >=0.25 && randomSpin <0.5) {
                    randomSpinBit = 6;
                }
                if (randomSpin >=0.5 && randomSpin <0.75) {
                    randomSpinBit = 9;
                }
                if (randomSpin >=0.75 && randomSpin <1.0) {
                    randomSpinBit = 10;
                }


                //CHECK CUTS
                if (sumB.Pt() > ptCutLo && sumB.Pt() < ptCutHi && sumB.M() > mCutLo && sumB.M() < mCutHi && sumB.Eta() > etaCutLo && sumB.Eta() < etaCutHi && useBlueBeam == true)
                {

                    //BLUE BEAM SPIN UP: spin bin 9 and 10
                    if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
                    {
                        bin = hNumberUp->FindBin(pair1->phiSR('b'));
                        //hNumberUp->Fill(pair1->phiSR('b'));



                        polOfBinSumUp[bin] += polarizationOfFill_B[blueFillNo];
                        pErrorOfBinUp[bin] += polErrOfFill_B[blueFillNo];
                    }

                    //BLUE BEAM SPIN DOWN: spin bin 5 and 6
                    if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
                    {
                        bin = hNumberDown->FindBin(pair1->phiSR('b'));
                        hNumberDown->Fill(pair1->phiSR('b'));

                        polOfBinSumDown[bin] += polarizationOfFill_B[blueFillNo];
                        pErrorOfBinDown[bin] += polErrOfFill_B[blueFillNo];
                    }

                }//end blue cuts

                TVector3 Pa;
                Pa.SetXYZ(0, 0, 1);   //blue is unpolarized beam

                TVector3 Pb;
                Pb.SetXYZ(0, 0, -1);  //yellow is polarized beam


                if (sumY.Pt()>ptCutLo && sumY.Pt() < ptCutHi && sumY.M() > mCutLo && sumY.M() < mCutHi && sumY.Eta() > etaCutLo && sumY.Eta() < etaCutHi && useYellowBeam == true)
                {

                    //YELLOW BEAM SPIN UP: spin bin 6 and 10
                    //if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
                    if (randomSpinBit == 6 || randomSpinBit == 10)

                    {

                        totalPairsFinal++;


                        spinVec.SetXYZ(0, 1, 0);

                        TVector3 Ph = pair1->piPlusLV().Vect() + pair1->piMinusLV().Vect();
                        TVector3 Rh  = pair1->piPlusLV().Vect() - pair1->piMinusLV().Vect();


                        double cosPhi_S = -Pb.Unit().Cross(Ph).Unit() * Pb.Unit().Cross(spinVec).Unit();

                        double cosPhi_R = Ph.Unit().Cross(Pb).Unit() * Ph.Unit().Cross(Rh).Unit();

                        double sinPhi_S = Ph.Cross(spinVec) * Pb.Unit() / (Pb.Unit().Cross(Ph).Mag() * Pb.Unit().Cross(spinVec).Mag());

                        double sinPhi_R = Pb.Cross(Rh) * Ph.Unit() / (Ph.Unit().Cross(Pb).Mag() * Ph.Unit().Cross(Rh).Mag());



                        double sinPhi_S_R = sinPhi_S*cosPhi_R - cosPhi_S*sinPhi_R;

                        double cosPhi_S_R = cosPhi_S*cosPhi_R + sinPhi_S*sinPhi_R;



                        double phi_S_R;

                        if (cosPhi_S_R >= 0)
                        {
                            phi_S_R = asin(sinPhi_S_R);
                        }
                        else if (cosPhi_S_R < 0)
                        {

                            if (sinPhi_S_R >= 0)
                            {
                                phi_S_R = TMath::Pi() - asin(sinPhi_S_R);
                            }
                            if (sinPhi_S_R < 0)
                            {
                                phi_S_R = -TMath::Pi() - asin(sinPhi_S_R);
                            }

                        }

                        //cout <<  "phisr = " << phi_S_R << endl;



                        bin = hNumberUp->FindBin(phi_S_R);
                        hNumberUp->Fill(phi_S_R);

                        polOfBinSumUp[bin] += polarizationOfFill_Y[yellowFillNo];
                        pErrorOfBinUp[bin] += polErrOfFill_Y[yellowFillNo];
                    }
                    //YELLOW BEAM SPIN DOWN: spin bit 5 and 9
                    if (randomSpinBit == 5 || randomSpinBit == 9)
                    {

                        totalPairsFinal++;

                        spinVec.SetXYZ(0, -1, 0);

                        TVector3 Ph = pair1->piPlusLV().Vect() + pair1->piMinusLV().Vect();
                        TVector3 Rh  = pair1->piPlusLV().Vect() - pair1->piMinusLV().Vect();


                        double cosPhi_S = -Pb.Unit().Cross(Ph).Unit() * Pb.Unit().Cross(spinVec).Unit();

                        double cosPhi_R = Ph.Unit().Cross(Pa).Unit() * Ph.Unit().Cross(Rh).Unit();

                        double sinPhi_S = Ph.Cross(spinVec) * Pb.Unit() / (Pb.Unit().Cross(Ph).Mag() * Pb.Unit().Cross(spinVec).Mag());

                        double sinPhi_R = Pa.Cross(Rh) * Ph.Unit() / (Ph.Unit().Cross(Pa).Mag() * Ph.Unit().Cross(Rh).Mag());



                        double sinPhi_S_R = sinPhi_S*cosPhi_R - cosPhi_S*sinPhi_R;

                        double cosPhi_S_R = cosPhi_S*cosPhi_R + sinPhi_S*sinPhi_R;



                        double phi_S_R;

                        if (cosPhi_S_R >= 0)
                        {
                            phi_S_R = asin(sinPhi_S_R);
                        }
                        else if (cosPhi_S_R < 0)
                        {

                            if (sinPhi_S_R >= 0)
                            {
                                phi_S_R = TMath::Pi() - asin(sinPhi_S_R);
                            }
                            if (sinPhi_S_R < 0)
                            {
                                phi_S_R = -TMath::Pi() - asin(sinPhi_S_R);
                            }

                        }

                        //	cout <<  "phisr = " << phi_S_R << endl;


                        bin = hNumberDown->FindBin(phi_S_R);
                        hNumberDown->Fill(phi_S_R);

                        polOfBinSumDown[bin] += polarizationOfFill_Y[yellowFillNo];
                        pErrorOfBinDown[bin] += polErrOfFill_Y[yellowFillNo];
                    }
                }//end yellow cuts





            }//end triger check
        }//end radius check
    }//end pairTree loop


    //CALCULATE ASYMMETRY BIN BY BIN
    cout << "\n";
    cout << "<----CALCULATING ASYMMETRY---->" << endl;
    cout << "\n";
    //*
    for (int ibin=1; ibin<=binNumber; ibin++)
    {

        if (ibin <= binNumber*0.5)
        {
            double nUp   = hNumberUp->GetBinContent(ibin);
            double nUpPi = hNumberUp->GetBinContent(ibin+binNumber*0.5);

            double nDown   = hNumberDown->GetBinContent(ibin);
            double nDownPi = hNumberDown->GetBinContent(ibin+binNumber*0.5);


            cout << nUp << "  " << nUpPi << "  " << nDown << "  " << nDownPi << "  "  << endl;

            int binIndexPi = ibin+binNumber*0.5;

            double avgPolA = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi])/(nUp+nDownPi);
            double avgPolB = (polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUpPi+nDown);

            double realAvgPol = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi]+polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUp+nUpPi+nDown+nDownPi);

        }
        else
        {
            double nUp   = hNumberUp->GetBinContent(ibin);
            double nUpPi = hNumberUp->GetBinContent(ibin-binNumber*0.5);

            double nDown   = hNumberDown->GetBinContent(ibin);
            double nDownPi = hNumberDown->GetBinContent(ibin-binNumber*0.5);

            int binIndexPi = ibin-binNumber*0.5;

            cout << nUp << "  " << nUpPi << "  " << nDown << "  " << nDownPi << "  "  << endl;


            double avgPolA = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi])/(nUp+nDownPi);
            double avgPolB = (polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUpPi+nDown);

            double realAvgPol = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi]+polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUp+nUpPi+nDown+nDownPi);

            double realAvgPolE = (pErrorOfBinUp[ibin]+pErrorOfBinDown[binIndexPi]+pErrorOfBinUp[binIndexPi]+pErrorOfBinDown[ibin])/(nUp+nUpPi+nDown+nDownPi);

        }


        cout << avgPolA << "   " << avgPolB << endl;




        hDiff->SetBinContent(ibin, sqrt(nUp*nDownPi) - sqrt(nDown*nUpPi));

        //hAut->SetBinContent(ibin, (1/avgPolA * sqrt(nUp*nDownPi) - 1/avgPolB * sqrt(nDown*nUpPi)) / (sqrt(nUp*nDownPi) + sqrt(nDown*nUpPi))    );


        hAut->SetBinContent(ibin, 1/realAvgPol * (sqrt(nUp*nDownPi) - sqrt(nDown*nUpPi)) / (sqrt(nUp*nDownPi) + sqrt(nDown*nUpPi))    );




        //error
        if (realAvgPol*pow(sqrt(nUp*nDownPi)+sqrt(nDown*nUpPi), 2) != 0)
        {

            double a = sqrt(nUp*nDownPi);
            double b = sqrt(nUpPi*nDown);


            double firstTerm = realAvgPol**2 * (nUpPi*nDown*(nUp+nDownPi) + nDownPi*nUp*(nUpPi+nDown));

            //double secondTerm = ((nUp*nDownPi)**2 +(nUpPi*nDown)**2 - 2*nUp*nDown*nUpPi*nDownPi)*realAvgPolE**2;

            double secondTerm = 0;


            double binError = 1/realAvgPol**2 * 1/(a+b)**2 * sqrt(firstTerm + secondTerm);


        }
        else
        {
            double binError = 0.01;
            cout << "bin " << ibin << " Has problem with error" << endl;
        }

        hAut->SetBinError(ibin, binError);

    }//end Asym calc

    //*/

    //DRAW HISTOGRAMS

    hInvarM->Draw();

    TCanvas* cNup = new TCanvas();
    hNumberUp->Draw();

    TCanvas* cNdown = new TCanvas();
    hNumberDown->Draw();

    TCanvas* cAut = new TCanvas();
    cAut->SetName("cAut");

    TF1* fitFunc = new TF1("fitFunc","[0]*sin(x)+[1]",-PI,PI);
    //hAut->Fit("fitFunc","R");
    hAut->Draw();

    hAut->GetXaxis()->SetTitle("#phi_{S} - #phi_{R}");

    char title[150];
    sprintf(title, "%.1f < P_{T}^{#pi^{+}#pi^{-}} < %.1f  %.1f < M_{inv}^{#pi^{+}#pi^{-}} < %.1f  %.1f < #eta^{#pi^{+}#pi^{-}} < %.1f", ptCutLo, ptCutHi, mCutLo, mCutHi, etaCutLo, etaCutHi);

    hAut->SetTitle(title);





    //SAVE CANVAS


    stringstream pt;
    stringstream eta;
    stringstream mass;

    string part1 = "_ptBin";
    string part2 = "_massBin";
    string part3 = "_etaBin";

    string ptBinStr;
    string etaBinStr;
    string massBinStr;


    pt << ptBin;

    eta << etaBin;

    mass << massBin;

    if (ptBin == 9) {
        ptBinStr = "All";
    }
    else {
        ptBinStr = pt.str();
    }

    if (massBin == 9) {
        massBinStr = "All";
    }
    else {
        massBinStr = mass.str();
    }

    if (etaBin == 9) {
        etaBinStr = "All";
    }
    else {
        etaBinStr = eta.str();
    }

    cout << "total pairs " << totalPairsFinal << endl;

    string outFileName = "./resultsTesting/piover2issue"+part1+ptBinStr+part2+massBinStr+part3+etaBinStr+".root";
    TFile* outFile = new TFile(outFileName.c_str(),"Recreate");


    cout << "---WRITING FILE---" << endl;
    //cAut->SaveAs(outFileName.c_str());
    hAut->Write();
    hNumberUp->Write();
    hNumberDown->Write();

    cout << "---END---" << endl;
}
Beispiel #27
0
void Dep_area(){		// name of file

using namespace std;


double pedgeL= 2.0;		// distance from the left edge to the p implant
double nedgeR= 2.0;		// distance from the right edge to the n implant

double data [31][2];		// define array to store data
int n=0;			// n by m array
int m=0;			

for (double bias=2.0;bias<=60.0;bias+=2.0){		// loop to create of graph for each bias value and output data to an array


	
	TString str =TString::Format("../TCAD/SimpleCMOS/DepletionSimRemesh/extraction_bias=%.1f_pedgeL=%.1f_nedgeR=%.1f.txt",bias,pedgeL,nedgeR);		// does some magic, creates string with name of file
	TGraph2D *gr= new TGraph2D(str,"%lg %lg %lE");		// creates graph called gr and reads file
	TRandom3 *rando = new TRandom3();



	gr->Draw("colz");	// draws 2D graph


	double tot_area = 2500;
	int in_dep = 0;		// no. of throws inside the depletion zone
	int total  = 0;		// total of number of throws


	for (int i=0;i<100000;i++){

		// make a throw, defines x and y coordinates
		double x= rando->Uniform(0,100.);		
		double y= rando->Uniform(0,25.);
	
		double econc= gr->Interpolate(x,y);		// electron concentration, obtains value of throw
		total+=1;
	
		if(econc<1e13){
	
			in_dep+=1;				// inside the depletion region if electron concentration is less than 1e13
		}	
		
	}

	// write result to array
	data[n][m]= bias;
	m++;
	data[n][m]= tot_area*double(in_dep)/total;
	n++;
	m=0;


}

// write array to text file
ofstream myfile ("../TCAD_Analysis/SimpleCMOS_2d/1pixel/Bias_Dep_SimplePixel.txt");
if (myfile.is_open()) {

    	for (int k = 0; k < 31; k++) {
	
		for (int l = 0; l < 2; l++) {
		
			myfile << data[0+k][0+l] << " ";
			
			}
			
		myfile << endl;	
		
 	 }

}


TGraph *graph= new TGraph("../TCAD_Analysis/SimpleCMOS_2d/1pixel/Bias_Dep_SimplePixel.txt","%lg %lg");		// creates a graph called graph and reads file

// makes graph look fancy...ish
graph->SetLineColor(2);
graph->SetLineWidth(1);
graph->SetMarkerSize(0.9);
graph->SetMarkerStyle(21);
graph->SetTitle("Depletion area vs. bias for a simple pixel");
graph->GetXaxis()->SetTitle("Bias (-V)");
graph->GetYaxis()->SetTitle("Depletion Area (#mum^{2})");
graph->GetXaxis()->CenterTitle();
graph->GetYaxis()->CenterTitle();

graph->Draw("ACP");		// draws graph

}
SimulationOutput* LightSimulator::Run(){
    
  TRandom3 randgen = TRandom3(0);

  if (debug) cout << ntoys*nrays << " light propagations to simulate" << endl;

  long counter_ray=0;

  if (output) delete output;
  output = new SimulationOutput(deposit);
    
  if (!isinsideboundaries()) return output;

  for (int nrun = 0; nrun<ntoys; nrun++){
            
    vector<Int_t> myphotons(4,0);

    for (int nray = 0; nray<nrays; nray++){

      counter_ray++;
      //	if (counter_ray%(ntoys*nrays/10)==0) cout << "Done " << counter_ray << " rays" << endl;

      Double_t phi = randgen.Uniform(-Pi(),Pi());
      Double_t costheta = randgen.Uniform(-1,1);
      TVector3 dir; dir.SetMagThetaPhi(1,ACos(costheta),phi);
      LightRay lr(deposit.position,dir);

      bool matched = false;
      Int_t matchx = 999;
      Int_t matchy = 999;
      Int_t firstmatchx = 999;
      Int_t firstmatchy = 999;

      Int_t index=0;
      MatchObject m;
      vector<MatchObject> matches;
      while (index>=0 && index<pars.max_distance_unit_propagation && index<Max(firstmatchx,firstmatchy)){
	if (propray(lr,kNS,index,matchx,m)){
	  if (!matched) firstmatchx=matchx;
	  matched=true;
	  matches.push_back(m);
	}
	if (propray(lr,kEW,index,matchy,m)){
	  if (!matched) firstmatchy=matchy;
	  matched=true;
	  matches.push_back(m);
	}
	index++;
      }

      vector<GoodMatchObject> goodmatches=convert_matches(matches);
	
      Double_t pathxy = pars.max_distance_unit_propagation*10*pars.xtalsize;
      GoodMatchObject finalmatch;
      for (size_t i=0; i<goodmatches.size(); i++){
	Double_t path = sqrt(pow(goodmatches[i].positionx-lr.origin.x(),2)+pow(goodmatches[i].positiony-lr.origin.y(),2));
	if (path<pathxy) {pathxy=path; finalmatch=goodmatches[i];}
      }
      if (pathxy>1e4){
	if (debug) cout << "LOOPER" << endl;
	continue;
      }

      Int_t channel = findchannel(finalmatch.x,finalmatch.y)-1;
     
      if (debug) cout << finalmatch.x << " " << finalmatch.y << " " << pathxy << " " << channel+1 << endl;

      Double_t path3d = pathxy/Sin(lr.dirvect.Theta());
     
      TVector3 rotated_origin_xy = lr.origin; rotated_origin_xy.SetZ(0);
      TVector3 rotated_impact = TVector3(finalmatch.positionx,finalmatch.positiony,0);
      TRotation r;
      r.RotateZ(-Pi()/4);
      rotated_origin_xy = r*rotated_origin_xy;
      rotated_impact = r*rotated_impact;

      Int_t nx = 0;
      Int_t ny = 0;
      Int_t nz = 0;
      {
	Int_t sx = finalmatch.x+finalmatch.y;
	if (sx==0) nx=0;
	else if (sx>0) nx = sx/2-1;
	else nx = TMath::Abs(sx)/2;
	Int_t dy = finalmatch.y-finalmatch.x;
	if (dy==0) ny=0;
	else if (dy>0) ny = dy/2-1;
	else ny = TMath::Abs(dy)/2;
	Float_t finalz = path3d*Cos(lr.dirvect.Theta())+deposit.position.z()-pars.xtalheight/2;
	nz = Int_t((fabs(finalz)+pars.xtalheight/2)/pars.xtalheight);
      }
      Int_t all_crossings = nx+ny+nz;

      Int_t my_paper_refl = 0;

      TVector2 difference = TVector2(fabs(rotated_origin_xy.x()-rotated_impact.x()),fabs(rotated_origin_xy.y()-rotated_impact.y()));
      if (difference.Phi()<limit_angle) my_paper_refl+=nx;
      if (Pi()/2-difference.Phi()<limit_angle) my_paper_refl+=ny;
      if (lr.dirvect.Theta()<limit_angle) my_paper_refl+=nz;

      Double_t att_absorption_point = randgen.Exp(pars.light_att_length);
      if (path3d>att_absorption_point) continue;

      Double_t prob_loss_in_reflections = pow(pars.eff_reflection_paper,my_paper_refl)*pow(pars.eff_reflection_total,all_crossings-my_paper_refl);
      if (randgen.Uniform()>prob_loss_in_reflections*pars.eff_lightcoll) continue;
	
      Double_t scintillation_delay = randgen.Exp(pars.scintillation_typ_timescale);

      Double_t arrival_time = deposit.time+path3d/pars.speed_of_light+scintillation_delay;
      if (arrival_time>pars.limit_arrival_time) continue;

      myphotons.at(channel)++;
      output->chamfer_pulseshape[channel]->Fill(arrival_time);
      output->reflections_paper->Fill(my_paper_refl);
      output->reflections_total->Fill(all_crossings-my_paper_refl);
      output->reflections_all->Fill(all_crossings);
      output->optical_path->Fill(path3d);
	
    }

    for (int i=0; i<4; i++) output->chamfer_photons[i]->Fill(myphotons[i]);

  }

  for (int i=0; i<4; i++) Normalize(output->chamfer_pulseshape[i]);
  Normalize(output->reflections_paper);
  Normalize(output->reflections_total);
  Normalize(output->reflections_all);
  Normalize(output->optical_path);

  return output;

};
//funzione che restituisce la coppia di punti x,y tra 0 e 1
//i & servono per passare gli argomenti come "referenza" e non come valore, in modo tale che siano modificabili dall'interno della funzione
  void generate(double &x, double &y) { 

    x = rndgenerator.Uniform();
    y = rndgenerator.Uniform();
 
  }
void ex3n()
{
	gStyle->SetOptFit(011);
	TCanvas *c =new TCanvas("c","superimposing",0,0,1080,860);//creating canvas for the histogram
	
	TRandom3 gen;//invoking the random number generator
	Double_t j=0,k=0,mean,m; //declaring counters and parameters for calculation
	Double_t pi, sum, var=0 ;
	Double_t devia;
	TH1F *h=new TH1F("h","mean distribution",60000,0,6);//calling the histogram class
	Int_t N=1000,q;//fixing N 
	TF1 *f =new TF1("f", "gaus"); //creating function to fit
	//TF1 *f1 = new TF1("f1","0.00357583/TMath::Sqrt(x)", 1000,5000);
	for(q=0;q<3;q++)
	{
	if(q==0)
{
	for(int z=0;z<10000;z++)//loops to calculate pi and fill the histogram
	{	
	for(int i=0; i<100;i++)
		{
			Double_t x= gen.Uniform(-1.,1);
			Double_t y=gen.Uniform(-1.,1.);
			if(x*x+y*y<=1)
				{
					j++;
					}
				else {k++;}
				pi=(j/(j+k))*4;
				
				
			}
				
				h->Fill(pi);
				
				
					}h->Fit("f");
devia=f->GetParameter(2);
cout<<"100"<<"\t"<<devia<<endl;
}

if(q==1)
{
	for(int z=0;z<10000;z++)//loops to calculate pi and fill the histogram
	{	
	for(int i=0; i<1000;i++)
		{
			Double_t x= gen.Uniform(-1.,1);
			Double_t y=gen.Uniform(-1.,1.);
			if(x*x+y*y<=1)
				{
					j++;
					}
				else {k++;}
				pi=(j/(j+k))*4;
				
				
			}
				
				h->Fill(pi);
				
				
					}h->Fit("f");
devia=f->GetParameter(2);
cout<<"1000"<<"\t"<<devia<<endl;
}
if(q==2)
{
	for(int z=0;z<10000;z++)//loops to calculate pi and fill the histogram
	{	
	for(int i=0; i<5000;i++)
		{
			Double_t x= gen.Uniform(-1.,1);
			Double_t y=gen.Uniform(-1.,1.);
			if(x*x+y*y<=1)
				{
					j++;
					}
				else {k++;}
				pi=(j/(j+k))*4;
				
				
			}
				
				h->Fill(pi);
				
				
					}h->Fit("f");

}

devia=f->GetParameter(2);
cout<<"5000"<<"\t"<<devia<<endl;
}


}