Пример #1
0
TGraph* autogain152(TH1 *hist) {

   hist->GetXaxis()->SetRangeUser(200.,16000.);
   TSpectrum *s = new TSpectrum();
   Int_t nfound = s->Search(hist,6,"",0.08); //This will be dependent on the source used.
   printf("Found %d candidate peaks to fit\n",nfound);
   if(nfound > 6)
      nfound = 6;

   std::vector<float> vec;
   for(int x=0;x<nfound;x++)
      vec.push_back(s->GetPositionX()[x]);

   std::sort(vec.begin(),vec.end());

   Float_t energies[] = {121.7830, 244.6920, 344.276, 778.903, 964.131, 1408.011};
   TGraph* slopefit = new TGraph(nfound, &(vec[0]), energies);

   printf("Now fitting: Be patient\n");
   slopefit->Fit("pol1");
   if(slopefit->GetFunction("pol1")->GetChisquare() > 10.) {
      slopefit->RemovePoint(slopefit->GetN()-1);
      slopefit->Fit("pol1");
   }
   TChannel *chan = 0;
   slopefit->Draw("AC*");

   return slopefit;
}
Пример #2
0
void fitSys(char *infname = "background_PbPb.dat")
{
    TGraph *g = new TGraph(infname);
    TF1 *f = new TF1("f","[0]+[1]/(x)+[2]/x/x+[3]*x");
    g->Draw("ap");
    g->Fit("f");
    g->Fit("f");
    g->Fit("f");
}
Пример #3
0
double get_correctionFactorbb(){

 double xx[5] = {39, 62.4, 200, 2760, 5000};
 double yy[5] = {0.00944, 0.0709, 1.81, 94.92, 180};

 TGraph *g = new TGraph(5);
 for(int i=0; i<5; i++){
        g->SetPoint(i,xx[i],yy[i]);
 }

 TCanvas *c = new TCanvas("c","c",600,450);
 g->SetMarkerStyle(20);
 g->Draw("AP");
 c->SetLogy();
 c->SetLogx();

 TF1 *f = new TF1("f","[0]+[1]*x+[2]*x*x",0,300);
 //TF1 *f = new TF1("f","[0]*pow(x,[1])",0,5500);
 //f->SetParameters(0,-5);
 g->Fit(f,"R");

 double corr = (f->Eval(193))/(f->Eval(200));

 return corr;

}
Пример #4
0
/*============================================================================*/
void gaus1peakfit(Char_t *s, Float_t x1, Float_t x2, Float_t x3, Float_t x4)
{
  Double_t par[5],epar[5],x[4],y[4];
  TH1 *hist;
  hist = (TH1 *) gROOT->FindObject(s);
  setcanvas(1);
  TCanvas *c1=(TCanvas*) gROOT->FindObject("c1");
  if(c1==NULL)setcanvas(1);
  c1->Clear();
  hist->SetAxisRange(x1-30,x4+30);
  hist->Draw();

  //--**-- Linear background estimation --**--//
  x[0] = x1;
  x[1] = x2;
  x[2] = x3;
  x[3] = x4;
  Int_t bin1 = hist->FindBin(x1);
  y[0] = hist->GetBinContent(bin1);
  Int_t bin2 = hist->FindBin(x2);
  y[1] = hist->GetBinContent(bin2);
  Int_t bin3 = hist->FindBin(x3);
  y[2] = hist->GetBinContent(bin3);
  Int_t bin4 = hist->FindBin(x4);
  y[3] = hist->GetBinContent(bin4);
  TGraph *g = new TGraph(4,x,y);
  TF1 *fpol1 = new TF1("POL1","pol1",x1,x4);
  g->Fit(fpol1,"RQN");
  par[3]=fpol1->GetParameter(0);
  par[4]=fpol1->GetParameter(1);

  //--**-- Gaussian Peak estimation without background --**--//
  TF1 *fgaus = new TF1("GAUS","gaus",x2,x3);
  hist->Fit(fgaus,"RQN");
  fgaus->GetParameters(&par[0]);

  //--**-- Final Peak Fit with Background --**--//
  TF1 *func = new TF1("FGAUS","gaus(0)+pol1(3)",x1,x4);
  func->SetParameters(par);
  hist->Fit(func,"R+QN");
  func->GetParameters(par);
  epar[0]=func->GetParError(0);
  epar[1]=func->GetParError(1);
  epar[2]=func->GetParError(2);
  Double_t fwhm = par[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm = epar[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N0 = par[0]*(TMath::Sqrt(TMath::TwoPi())*par[2]);
  Double_t r0 = epar[0]/par[0];
  Double_t r2 = epar[2]/par[2];
  Double_t eN0= N0*TMath::Sqrt(r0*r0+r2*r2);
  printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
          par[1],epar[1],fwhm,efwhm,N0,eN0);
  //printf("%11.4f %11.4f %11.0f %11.0f\n",
  //        par[1],epar[1],N0,eN0);
  func->SetLineWidth(0.5);
  func->SetLineStyle(1);
  func->SetLineColor(4);
  func->SetFillColor(4);
  func->Draw("same");
}
Пример #5
0
TGraph* autogain(TH1 *hist,TNucleus *nuc) {    //Display The fits on a TPad  

   if(!hist || !nuc)
      return 0;

   nuc->SetSourceData();

   if(nuc->GetA() == 152) {
      return autogain152(hist);
   }

// Search
   hist->GetXaxis()->SetRangeUser(200.,16000.);
   TSpectrum *s = new TSpectrum();
   Int_t nfound = s->Search(hist,6,"",0.1); //This will be dependent on the source used.
   printf("Found %d candidate peaks to fit\n",nfound);
// Match

   nuc->TransitionList.Sort();

   std::vector<float> engvec;
   TIter iter(&(nuc->TransitionList));
   TObject* obj;
   while(obj = iter.Next()) {
      if(!obj->InheritsFrom("TGRSITransition"))
         continue;
      TGRSITransition *tran = (TGRSITransition*)obj;

      engvec.push_back(static_cast<float>(tran->energy));
      if(engvec.size() == nfound)
         break;
   }

   if(nfound != engvec.size())
      return 0;

   Float_t *posPeaks = s->GetPositionX();
   Float_t *energies = &(engvec[0]);

   for(int x=0;x<nfound;x++) {
      printf("posPeaks[%i] = %f\t\tenrgies[%i] = %f\n",x,posPeaks[x],x,energies[x]);
   }

   TGraph *slopefit = new TGraph(nfound,posPeaks,energies ); 

   printf("Now fitting: Be patient\n");
   slopefit->Fit("pol1");
   slopefit->Draw("AC*");

   return slopefit;

}
Double_t beta2_for_5sigma(const Int_t fNPts, const Double_t fRangeMin, const Double_t fRangeMax, const Double_t fN_sig_100, const Double_t fN_bkg_100, const Double_t fSigma_N_bkg, const string& fTitle) 
{
 
 Double_t x[fNPts], y[fNPts];

 Double_t step = (fRangeMax - fRangeMin)/(fNPts-1);
   
 for (Int_t i = 0; i < fNPts; i++) {
 
  x[i] = fRangeMin + step*i;
  y[i] = ScP(x[i], fN_sig_100, fN_bkg_100, fSigma_N_bkg);
 }
 
 TCanvas *c_temp = new TCanvas("c_temp","",1120,800);
 c_temp->cd();

 string title = fTitle + ";#beta^{2};S_{cP}";

 TH2F *bg_temp = new TH2F("bg_temp",title.c_str(), 100, fRangeMin, fRangeMax, 100, 0.8*y[0], 1.2*y[fNPts-1]);
 bg_temp->SetStats(kFALSE);
 bg_temp->SetTitleOffset(1.,"X");
 bg_temp->SetTitleOffset(1.,"Y");
 bg_temp->Draw();
 
 TGraph *scP = new TGraph(fNPts, x, y);
 scP->SetMarkerSize(1.);
 scP->SetMarkerStyle(24);
 scP->SetMarkerColor(kRed);
 scP->Draw("P"); 
 scP->Fit("pol2");

 TF1 *fit = (TF1*)scP->GetFunction("pol2");
 Double_t beta2 = fit->GetX(5);
 Double_t N_sig = beta2*fN_sig_100;
 Double_t N_s_b = N_sig + fN_bkg_100;
 
 cout<<">> beta2 for 5 sigma discovery for "<<fTitle<<" = "<<beta2<<"\n";
 cout<<">> ** N_sig = "<<N_sig<<"\n";
 cout<<">> ** N_bkg = "<<fN_bkg_100<<"\n";
 cout<<">> ** N_s_b = "<<N_s_b<<"\n";
 
 if(fSigma_N_bkg != 0) c_temp->SaveAs((fTitle + "_significance_beta_sys.png").c_str());
 else c_temp->SaveAs((fTitle + "_significance_beta.png").c_str());

 delete scP;
 delete bg_temp;
 delete c_temp;
 
 return beta2;
}
Double_t beta2_for_exclusion(const Int_t fNPts, const Double_t fxsTh, const Double_t fRangeMin, const Double_t fRangeMax, const Double_t fSigma_L, const Double_t fS_eff, const Double_t fSigma_S_eff, const Double_t fN_bkg_100, const Double_t fSigma_N_bkg, const string& fTitle) 
{
 
 Double_t x[fNPts], y[fNPts];

 Double_t step = (fRangeMax - fRangeMin)/(fNPts-1);
   
 for (Int_t i = 0; i < fNPts; i++) {
 
  x[i] = fRangeMin + step*i;
  y[i] = CLA(100, 100*fSigma_L, fS_eff*x[i], fS_eff*x[i]*fSigma_S_eff, fN_bkg_100, fN_bkg_100*fSigma_N_bkg);
 }
 
 TCanvas *c_temp = new TCanvas("c_temp","",1120,800);
 c_temp->cd();

 string title = fTitle + ";#beta^{2};95% C.L. upper limit on #sigma [pb]";

 TH2F *bg_temp = new TH2F("bg_temp",title.c_str(), 100, fRangeMin, fRangeMax, 100, 0.8*y[fNPts-1], 1.2*y[0]);
 bg_temp->SetStats(kFALSE);
 bg_temp->SetTitleOffset(1.,"X");
 bg_temp->SetTitleOffset(1.,"Y");
 bg_temp->Draw();
 
 TF1 *f1 = new TF1("f1","[0]+[1]/pow(x,[2])",fRangeMin,fRangeMax);
 f1->SetParameters(0.,1.,1.);
 f1->SetParLimits(2, 0.45, 1.1);
 
 TGraph *xsection = new TGraph(fNPts, x, y);
 xsection->SetMarkerSize(1.);
 xsection->SetMarkerStyle(24);
 xsection->SetMarkerColor(kRed);
 xsection->Draw("P");
 xsection->Fit("f1");

 Double_t beta2 = f1->GetX(fxsTh);

 cout<<">> beta^2 for 95% CL exclusion of "<<fTitle<<" = "<<beta2<<"\n";
 
 if(fSigma_N_bkg != 0) c_temp->SaveAs((fTitle + "_exclusion_sys.png").c_str());
 else c_temp->SaveAs((fTitle + "_exclusion.png").c_str());
 
 delete xsection;
 delete f1;
 delete bg_temp;
 delete c_temp;
 
 return beta2;
}
Пример #8
0
    TF1* computeFunctionFit(TrialDataSet& eSimData)
    {
         TF1 * func = new TF1("fittingFunction", this->fittingFunction, -39, 200, 3);
         //func->SetParameters(eSimData.startingTime - subtractedTime, 1.0);

         // Convert digital readout values to floats
         float floatReadoutValues[7];
         for (int i = 0; i < 7; ++i){floatReadoutValues[i] = eSimData.digitalReadoutValues[i];}


         TGraph *gr = new TGraph(7, eSimData.measurementTimes, floatReadoutValues);

         gr->Fit(func, "QN");
         return func;
    }
Пример #9
0
void TrPdf::FitLogLog(double min, double max) {
  TGraph* FluxLogLogTmp = new TGraph(GetGraph()->GetN());
  FluxLogLogTmp->SetName("spectrumloglogtmp");
  FluxLogLogTmp->SetTitle("spectrumloglogtmp");
  for (int ii=0; ii<Graph->GetN(); ii++) {
    double a,b;
    GetGraph()->GetPoint(ii,a,b);
    FluxLogLogTmp->SetPoint(ii,log10(a),log10(b));
  }
  TF1* LinFitTmp = new TF1("linfittmp","[0]+[1]*x+[2]*pow(x,2.)+[3]*pow(x,3.)+[4]*pow(x,4.)+[5]*pow(x,5.)",-2.,5.); 
  FluxLogLogTmp->Fit(LinFitTmp,"EQR","",log10(min),log10(max));
  LogLog = new TF1(Form("LogLog_%s",GetName().Data()),
    "pow(10.,[0]+[1]*log10(x)+[2]*pow(log10(x),2.)+[3]*pow(log10(x),3.)+[4]*pow(log10(x),4.)+[5]*pow(log10(x),5.))",1.e-2,1.e5);
  for (int i=0; i<6; i++) LogLog->SetParameter(i,LinFitTmp->GetParameter(i));
  delete LinFitTmp;
  delete FluxLogLogTmp;
}
Пример #10
0
void GraphCrdcPads(int num=0,int CRDCNum=0){

  //This script will look at the Raw root trees
  //and plot a single crdc pad distribution 

  S800Event * event= new S800Event();

  rawtree->SetBranchAddress("s800event",&event);

  rawtree->GetEntry(num);

  // cout<<"Size of samples "<<event->GetS800()->GetCrdc(0)->GetSample().size()<<endl;
  // cout<<"Size of data "<<event->GetS800()->GetCrdc(0)->GetData().size()<<endl;
  // cout<<"Size of channels "<<event->GetS800()->GetCrdc(0)->GetChannels().size()<<endl;

  int size = event->GetS800()->GetCrdc(CRDCNum)->GetChannels().size();



  TString install =gSystem->Getenv("R00TLeInstall");
  
  TString calfile = install+"/prm/crdccalNone.dat";
  TString pedfile = install+"/prm/crdcpedestals.dat";
  
  S800Calibration calibration;//new S800Settings(install+"/prm/Raw2Cal.dat"));
  calibration.ReadCrdcCalibration(calfile,pedfile);


  //calibration.SetCrdc(event->GetS800()->GetCrdc(0)->GetChannels(),event->GetS800()->GetCrdc(0)->GetData(),0,0,0);

  calibration.CrdcCal(event->GetS800()->GetCrdc(CRDCNum)->GetChannels(),event->GetS800()->GetCrdc(CRDCNum)->GetData(),0);

  int size2=calibration.GetCRDCCal().size();
  TGraph * graph = new TGraph();
  for (int i=0;i<size2;i++){
    if (TMath::IsNaN(calibration.GetCRDCCal()[i])){
      graph->SetPoint(i,i,0);
    }else {
      graph->SetPoint(i,i,calibration.GetCRDCCal()[i]);
    }
  }
  graph->Fit("gaus");
  graph->Draw("A*");
  return;
}
Пример #11
0
/// used in display_beamprofile() : not working !
void getEllipseParameters(const float * x_data, const float * y_data, const unsigned int N, float& x_width, float& y_width, float& angle) {
	// In order to fit a good ellipse on the scattered plot :
	// 1) The TH2 is copied into a TGraph, to fit it with y(x) = ax => to retrieve the angle
	// 2) Rotation of the Graph to get the RMS in X and Y
	// 3) Creation of the final ellipse, with the good widths and angle

	TCanvas * ca0 = new TCanvas;
	ca0->Divide(2,1);
	ca0->cd(1);

	TGraph * draft = new TGraph(N,x_data,y_data);
	draft->Draw("AP");
	draft->Fit("pol1","Q");
	TF1 * pol1 = draft->GetFunction("pol1");
	pol1->Draw("same");

	// gets the angle [rad]
	angle = asin(1.) - atan(pol1->GetParameter(1));
	
	double x_datarot[N], y_datarot[N];
	for (unsigned int i=0; i<N; i++) {
		x_datarot[i]=  x_data[i]*cos(angle) - y_data[i]*sin(angle);
		y_datarot[i]=  x_data[i]*sin(angle) + y_data[i]*cos(angle);
	}

	ca0->cd(2);
	TGraph * draft2 = new TGraph(N,x_datarot,y_datarot);
	draft2->Draw("AP");
	x_width =  draft2->GetRMS(1); 
	y_width =  draft2->GetRMS(2);
	angle = 180-90*angle/asin(1.);
//	draft->Draw("AP");
	ca0->cd(1);
	TEllipse * ell = new TEllipse(draft->GetMean(1),draft2->GetMean(2),x_width*3,y_width*3);
	ell->SetTheta(angle);
	ell->Draw("same");

	//cout << "x = " << x_width << "\t y = " << y_width << "\t angle = " << angle << endl;

//	delete draft2;
//	delete draft;
//	delete ca0;
	return;
}
Пример #12
0
void rootFit(){

  TCanvas *c1 = new TCanvas("c1","",600,600);
  c1->Divide(1,2);
  TNtuple *T = new TNtuple("T","","x:y:z");
  T->ReadFile("histogramData.dat");
  T->Draw("y:x");

  Double_t *X = T->GetV1();
  Double_t *Y = T->GetV2();

  for(int loop = 0; loop < 120; loop++){
    cout << X[loop] << "  " << Y[loop] << endl;
  }

  c1->Clear();
  TGraph *graphT = new TGraph(120,Y,X);
  TGraph *graphB = new TGraph(120,Y,X);
  c1->cd(1);
  graphT->Draw("APL");
  graphT->Fit("gaus+pol2","RME");

}
Пример #13
0
void calc(TFile *file1, TFile *file2, const char* basename, int projnumb)
{

  TH1D *hp5_1 = (TH1D *)file1->Get(Form("%s_VMIN_SIPM1_meanHistSub_hproj_%d",basename,projnumb));
  TH1D *hp5_2 = (TH1D *)file2->Get(Form("%s_VMIN_SIPM2_meanHistSub_hproj_%d",basename,projnumb));

  if(hp5_1==NULL) {cout<<"cannot find hp5_1"<<endl; return;}
  if(hp5_2==NULL) {cout<<"cannot find hp5_2"<<endl; return;}

  int nbins = hp5_1->GetNbinsX();

  // ----------------------------------------------------------------------------
  // --- one of the preamps was broken, so we only had measurements from 1 SiPM
  // --- I made this fake data part to help in the code development while waiting
  // --- for new data with both SiPMs to be available
  // ----------------------------------------------------------------------------
  bool makefakedata = false;
  if(makefakedata)
    {
      for(int i=0; i<nbins; i++)
	{
	  hp5_2->SetBinContent(i+1,hp5_1->GetBinContent(nbins-i));
	}
    }

  double max1 = hp5_1->GetMaximum();
  double max2 = hp5_2->GetMaximum();

  hp5_1->GetXaxis()->SetTitle("Distance (cm)");
  hp5_2->GetXaxis()->SetTitle("Distance (cm)");
  hp5_1->GetYaxis()->SetTitle("Number of photoelectrons");
  hp5_2->GetYaxis()->SetTitle("Number of photoelectrons");

  if(max1>=max2)
    {
      // case 1
      hp5_1->Draw();
      hp5_2->Draw("same");
    }
  else
    {
      // case 2
      hp5_2->Draw();
      hp5_1->Draw("same");
    }

  hp5_1->SetLineColor(kBlue);
  hp5_2->SetLineColor(kRed);
  hp5_1->SetLineWidth(2);
  hp5_2->SetLineWidth(2);

  // legend coordinates may occasionally need to be relocated
  TLegend *leg = new TLegend(0.4,0.2,0.6,0.4);
  leg->AddEntry(hp5_1,"SiPM1","l");
  leg->AddEntry(hp5_2,"SiPM2","l");
  leg->SetFillStyle(0);
  leg->Draw();

  // generalize
  c1->Print(Form("Figures/ATOGETHER_%s_p%d.png",basename,projnumb));
  c1->Print(Form("Figures/ATOGETHER_%s_p%d.pdf",basename,projnumb));

  ofstream fout(Form("Data/Text/Asymmetry/%s_asymmetry_p%d.txt",basename,projnumb));
  TH1D *hp5_asymm = (TH1D *)hp5_1->Clone();
  double x[58];
  double y[58];
  double y1[58];
  double y2[58];
  TH1D *h1 = new TH1D("h1","",50,0,25);
  TH1D *h2 = new TH1D("h2","",50,0,25);
  for(int i=0; i<nbins; i++)
    {
      double A = hp5_1->GetBinContent(i+1);
      double B = hp5_2->GetBinContent(i+1);
      double content = (B-A)/(B+A);
      hp5_asymm->SetBinContent(i+1,content);
      hp5_asymm->SetBinError(i+1,0);
      // ---
      x[i] = hp5_1->GetBinCenter(i+1);
      y[i] = content;
      y1[i] = A;
      y2[i] = B;
      x[i] -= 2.0; // offset for off-panel part of scan, needs manual adjustment
      if(i>3&&i<54)
	{
	  // offset for off-panel, needs manual adjustment
	  h1->SetBinContent(i-3,A);
	  h2->SetBinContent(i-3,B);
	  h1->SetBinError(i-3,0);
	  h2->SetBinError(i-3,0);
	}
      // ---
      fout<<hp5_asymm->GetBinCenter(i+1)<<" "
	  <<hp5_asymm->GetBinContent(i+1)<<endl;
    }
  fout.close();

  hp5_asymm->SetMarkerColor(kBlack);
  hp5_asymm->SetMarkerStyle(kFullCircle);
  hp5_asymm->Draw("ex0p");
  hp5_asymm->GetYaxis()->SetTitle("Asymmetry of light yields");
  hp5_asymm->SetMinimum(-1);
  hp5_asymm->SetMaximum(1);
  TLine line(0.0,0.0,29.0,0.0);
  line.SetLineStyle(2);
  line.SetLineWidth(2);
  line.Draw();

  // generalize
  c1->Print(Form("Figures/ASYMMETRY_%s_p%d.png",basename,projnumb));
  c1->Print(Form("Figures/ASYMMETRY_%s_p%d.pdf",basename,projnumb));

  // ---

  h1->SetLineColor(kBlue);
  h2->SetLineColor(kRed);
  h1->SetLineWidth(2);
  h2->SetLineWidth(2);
  h1->SetMinimum(0);
  h2->SetMinimum(0);

  h1->GetXaxis()->SetTitle("Distance (cm)");
  h2->GetXaxis()->SetTitle("Distance (cm)");
  h1->GetYaxis()->SetTitle("Number of photoelectrons");
  h2->GetYaxis()->SetTitle("Number of photoelectrons");

  TGraph *tgy1 = new TGraph(58,x,y1);
  TGraph *tgy2 = new TGraph(58,x,y2);

  tgy1->SetLineColor(kBlue);
  tgy2->SetLineColor(kRed);
  tgy1->SetLineWidth(2);
  tgy2->SetLineWidth(2);
  tgy1->SetMinimum(0);
  tgy2->SetMinimum(0);

  tgy1->GetXaxis()->SetTitle("Distance (cm)");
  tgy2->GetXaxis()->SetTitle("Distance (cm)");
  tgy1->GetYaxis()->SetTitle("Number of photoelectrons");
  tgy2->GetYaxis()->SetTitle("Number of photoelectrons");

  double maxx = 0;
  if(max1>=max2)
    {
      // case 1
      maxx = max1;
      h1->Draw();
      h2->Draw("same");
    }
  else
    {
      // case 2
      maxx = max2;
      h2->Draw();
      h1->Draw("same");
    }

  TF1 *funx1 = new TF1("funx1","[0]+[1]*TMath::Exp(-x/[2])",0,25);
  funx1->SetLineColor(kBlue);
  funx1->SetParameter(0,5.0); // number of photoelectrons in core
  funx1->SetParameter(1,5.0); // number of photoelectrons in clad
  funx1->FixParameter(2,cld); // clad decay constant
  tgy1->Fit(funx1,"","",1,24); // need to use TGraph here, fitting h1 produces "Warning in <Fit>: Fit data is empty"
                               // I don't know why this happening, probably some dumb mistake I'm making
  TF1 *funx2 = new TF1("funx2","[0]+[1]*TMath::Exp((x-25)/[2])",0,25);
  funx2->SetLineColor(kRed);
  funx2->SetParameter(0,5.0); // number of photoelectrons in core
  funx2->SetParameter(1,5.0); // number of photoelectrons in clad
  funx2->FixParameter(2,cld); // clad decay constant
  tgy2->Fit(funx2,"","",1,24); // need to use TGraph here, fitting h2 produces "Warning in <Fit>: Fit data is empty"
                               // I don't know why this happening, probably some dumb mistake I'm making

  // tgy1->Draw("same"); // looks cool but distracting
  // tgy2->Draw("same"); // looks cool but distracting
  funx1->Draw("same");
  funx2->Draw("same");

  double numcore1 = funx1->GetParameter(0);
  double numclad1 = funx1->GetParameter(1);
  double numcore2 = funx2->GetParameter(0);
  double numclad2 = funx2->GetParameter(1);
  double Enumcore1 = funx1->GetParError(0);
  double Enumclad1 = funx1->GetParError(1);
  double Enumcore2 = funx2->GetParError(0);
  double Enumclad2 = funx2->GetParError(1);

  double fracore1 = (numcore1)/(numcore1+numclad1);
  double fracore2 = (numcore2)/(numcore2+numclad2);
  // ---
  double partB;
  partB = sqrt(Enumcore1**2+Enumclad2**2);
  double Efracore1 = fracore1*sqrt((Enumcore1/numcore1)**2+(partB/(numcore1+numclad1))**2);
  partB = sqrt(Enumcore2**2+Enumclad2**2);
  double Efracore2 = fracore2*sqrt((Enumcore2/numcore2)**2+(partB/(numcore2+numclad2))**2);

  TLatex *texAC1 = new TLatex(2,0.27*maxx,Form("f_{core} = %.3f #pm %.3f",fracore1,Efracore1));
  texAC1->SetTextColor(kBlue);
  texAC1->Draw();
  TLatex *texAC2 = new TLatex(15,0.27*maxx,Form("f_{core} = %.3f #pm %.3f",fracore2,Efracore2));
  texAC2->SetTextColor(kRed);
  texAC2->Draw();
  // ---
  TLatex *texAA1 = new TLatex(2,0.18*maxx,Form("N_{core} = %.3f #pm %.3f",numcore1,Enumcore1));
  texAA1->SetTextColor(kBlue);
  texAA1->Draw();
  TLatex *texAA2 = new TLatex(15,0.18*maxx,Form("N_{core} = %.3f #pm %.3f",numcore2,Enumcore2));
  texAA2->SetTextColor(kRed);
  texAA2->Draw();
  TLatex *texAB1 = new TLatex(2,0.1*maxx,Form("N_{clad} = %.3f #pm %.3f",numclad1,Enumclad1));
  texAB1->SetTextColor(kBlue);
  texAB1->Draw();
  TLatex *texAB2 = new TLatex(15,0.1*maxx,Form("N_{clad} = %.3f #pm %.3f",numclad2,Enumclad2));
  texAB2->SetTextColor(kRed);
  texAB2->Draw();

  // ---

  c1->Print(Form("Figures/FITATOGETHER_%s_p%d.png",basename,projnumb));
  c1->Print(Form("Figures/FITATOGETHER_%s_p%d.pdf",basename,projnumb));

  // ---

  // define a function to describe the data
  // this function defines and asymmetry B-A/A+B
  // it assumes the light yield has two components, core and cladding
  TF1 *fun = new TF1("fun","(([0]*TMath::Exp((x-25)/[1])+(1-[0])*TMath::Exp((x-25)/[2]))-([0]*TMath::Exp(-x/[1])+(1-[0])*TMath::Exp(-x/[2])))/(([0]*TMath::Exp(-x/[1])+(1-[0])*TMath::Exp(-x/[2]))+([0]*TMath::Exp((x-25)/[1])+(1-[0])*TMath::Exp((x-25)/[2])))",0,29);
  fun->SetParameter(0,0.5); // light fraction in fiber core
  fun->FixParameter(1,350); // decay constant in fiber core
  fun->FixParameter(2,cld); // decay constant in fiber cladding
  TF1 *fun2 = new TF1("fun2","[3]+(([0]*TMath::Exp((x-25)/[1])+(1-[0])*TMath::Exp((x-25)/[2]))-([0]*TMath::Exp(-x/[1])+(1-[0])*TMath::Exp(-x/[2])))/(([0]*TMath::Exp(-x/[1])+(1-[0])*TMath::Exp(-x/[2]))+([0]*TMath::Exp((x-25)/[1])+(1-[0])*TMath::Exp((x-25)/[2])))",0,29);
  fun2->SetParameter(0,0.5); // light fraction in fiber core
  fun2->FixParameter(1,350); // decay constant in fiber core
  fun2->FixParameter(2,cld); // decay constant in fiber cladding
  fun2->SetParameter(3,0.01);

  TGraph *tg = new TGraph(58,x,y);
  tg->SetMarkerStyle(kFullCircle);
  tg->Draw("ap");
  tg->GetYaxis()->SetTitle("Asymmetry of light yields");
  tg->GetXaxis()->SetTitle("Distance (cm)");
  tg->GetXaxis()->SetLimits(0,25);
  double scale = 0.4;
  tg->SetMinimum(-1*scale);
  tg->SetMaximum(1*scale);
  tg->Fit("fun2","","",0,25);
  TLine line2(0.0,0.0,25.0,0.0);
  line2.SetLineStyle(2);
  line2.SetLineWidth(2);
  line2.Draw();

  // get the fit parameters
  double frac = fun2->GetParameter(0);
  double core = fun2->GetParameter(1);
  double clad = fun2->GetParameter(2);
  double Efrac = fun2->GetParError(0);
  double off = fun2->GetParameter(3);
  double Eoff = fun2->GetParError(3);

  // use the fit parameters to put text boxes with fit information on the plt
  TLatex *tex1 = new TLatex(15,-0.30*scale,Form("f_{core} = %.3f #pm %.3f",frac,Efrac));
  tex1->SetTextColor(kGreen+2);
  tex1->Draw();
  TLatex *tex2 = new TLatex(15,-0.45*scale,Form("#lambda_{core} = %.1f (FIXED)",core));
  tex2->SetTextColor(kBlack);
  tex2->Draw();
  TLatex *tex3 = new TLatex(15,-0.60*scale,Form("#lambda_{clad} = %.1f (FIXED)",clad));
  tex3->SetTextColor(kBlack);
  tex3->Draw();
  TLatex *texX = new TLatex(15,-0.75*scale,Form("offset = %.3f #pm %.3f",off,Eoff));
  texX->SetTextColor(kGreen+2);
  texX->Draw();

  // generalize
  c1->Print(Form("Figures/FITASYMMETRY_%s_p%d.png",basename,projnumb));
  c1->Print(Form("Figures/FITASYMMETRY_%s_p%d.pdf",basename,projnumb));

  // ---
  frac1[projnumb] = fracore1;
  frac2[projnumb] = fracore2;
  fracAv[projnumb] = (fracore1+fracore2)/2.0;
  fracAs[projnumb] = frac;

  delete h1;
  delete h2;

}
Пример #14
0
void test()
{
//Illustrates TVirtualFitter::GetConfidenceIntervals
//This method computes confidence intervals for the fitted function
//Author: Anna Kreshuk

   TCanvas *myc = new TCanvas("myc",
      "Confidence intervals on the fitted function",1200, 500);
   myc->Divide(3,1);

/////1. A graph
   //Create and fill a graph
   Int_t ngr = 100;
   TGraph *gr = new TGraph(ngr);
   gr->SetName("GraphNoError");
   Double_t x, y;
   Int_t i;
   for (i=0; i<ngr; i++){
      x = gRandom->Uniform(-1, 1);
      y = -1 + 2*x + gRandom->Gaus(0, 1);
      gr->SetPoint(i, x, y);
   }
   //Create the fitting function
   TF1 *fpol = new TF1("fpol", "pol1", -1, 1);
   fpol->SetLineWidth(2);
   gr->Fit(fpol, "Q");

   //Create a TGraphErrors to hold the confidence intervals
   TGraphErrors *grint = new TGraphErrors(ngr);
   grint->SetTitle("Fitted line with .95 conf. band");
   for (i=0; i<ngr; i++)
      grint->SetPoint(i, gr->GetX()[i], 0);
   //Compute the confidence intervals at the x points of the created graph
   (TVirtualFitter::GetFitter())->GetConfidenceIntervals(grint);
   //Now the "grint" graph contains function values as its y-coordinates
   //and confidence intervals as the errors on these coordinates
   //Draw the graph, the function and the confidence intervals
   myc->cd(1);
   grint->SetLineColor(kRed);
   grint->Draw("ap");
   gr->SetMarkerStyle(5);
   gr->SetMarkerSize(0.7);
   gr->Draw("psame");

/////2. A histogram
   myc->cd(2);
   //Create, fill and fit a histogram
   Int_t nh=5000;
   TH1D *h = new TH1D("h",
      "Fitted gaussian with .95 conf.band", 100, -3, 3);
   h->FillRandom("gaus", nh);
   TF1 *f = new TF1("fgaus", "gaus", -3, 3);
   f->SetLineWidth(2);
   h->Fit(f, "Q");
   h->Draw();

   //Create a histogram to hold the confidence intervals
   TH1D *hint = new TH1D("hint",
      "Fitted gaussian with .95 conf.band", 100, -3, 3);
   (TVirtualFitter::GetFitter())->GetConfidenceIntervals(hint);
   //Now the "hint" histogram has the fitted function values as the
   //bin contents and the confidence intervals as bin errors
   hint->SetStats(kFALSE);
   hint->SetFillColor(2);
   hint->Draw("e3 same");

/////3. A 2d graph
   //Create and fill the graph
   Int_t ngr2 = 100;
   Double_t z, rnd, e=0.3;
   TGraph2D *gr2 = new TGraph2D(ngr2);
   gr2->SetName("Graph2DNoError");
   TF2  *f2 = new TF2("f2",
      "1000*(([0]*sin(x)/x)*([1]*sin(y)/y))+250",-6,6,-6,6);
   f2->SetParameters(1,1);
   for (i=0; i<ngr2; i++){
      f2->GetRandom2(x,y);
      // Generate a random number in [-e,e]
      rnd = 2*gRandom->Rndm()*e-e;
      z = f2->Eval(x,y)*(1+rnd);
      gr2->SetPoint(i,x,y,z);
   }
   //Create a graph with errors to store the intervals
   TGraph2DErrors *grint2 = new TGraph2DErrors(ngr2);
   for (i=0; i<ngr2; i++)
      grint2->SetPoint(i, gr2->GetX()[i], gr2->GetY()[i], 0);

   //Fit the graph
   f2->SetParameters(0.5,1.5);
   gr2->Fit(f2, "Q");
   //Compute the confidence intervals
   (TVirtualFitter::GetFitter())->GetConfidenceIntervals(grint2);
   //Now the "grint2" graph contains function values as z-coordinates
   //and confidence intervals as their errors
   //draw
   myc->cd(3);
   f2->SetNpx(30);
   f2->SetNpy(30);
   f2->SetFillColor(kBlue);
   f2->Draw("surf4");
   grint2->SetNpx(20);
   grint2->SetNpy(20);
   grint2->SetMarkerStyle(24);
   grint2->SetMarkerSize(0.7);
   grint2->SetMarkerColor(kRed);
   grint2->SetLineColor(kRed);
   grint2->Draw("E0 same");
   grint2->SetTitle("Fitted 2d function with .95 error bars");

   myc->cd();

}
Пример #15
0
PMTCalibration(){

   // Variable declarations
   // NOTE - Make sure the number of elements in Voltage is correct. If its not, this will
   // confuse the forloop.

   float  Voltage[19] = {1.432,1.434,1.436,1.438,1.440,1.442,1.444,1.446,1.448,1.450,1.452,1.454, 1.456, 1.458, 1.460, 1.462, 1.464, 1.466, 1.468}; // LED Voltages
   float  PedestalFitMin = -6e-12;                // Minimum for pedestal fitting range
   float  PedestalFitMax = 2e-8;                  // Maximum for pedestal fitting range
   float  SignalNorm = 100;                       // Normalization for signal fitting
   float  SignalMean = 5e-10;                     // Mean of signal distribution
   float  SignalWidth = 1e-10;                    // Width of signal distribution
   float  MaxADCforPlot = 7e-10;                     // Maximum of x-axis for linearity plot
   float  MaxNPEforPlot = 60;                   // Maximum of y-axis for linearity plot
   string IsPedestalFit;                          // String for user interface
   string IsFullADCFit;                           // String for user interface
   string IsPlotPretty;                           // String for user interface
   int    dummy;                                  // Dummy variable used in sprintf stuff
   char   filename[50];                           // Array of filenames
   char   plotname[50];                           // Array of ADC plot names
   // Ntuple for storing the derived quantities at each voltage
   TNtuple *ntuple = new TNtuple("ntuple","data for each voltage","V:mean:sigma:meanerr:sigmaerr");

   // Begin loop over all files/voltages

   for (unsigned int i=0; i<sizeof(Voltage)/sizeof(Voltage[0]); i++) {

      // To learn about sprintf:
      // http://www.cplusplus.com/reference/cstdio/sprintf/
      // To learn about "%.3f":
      // http://en.wikibooks.org/wiki/C++_Programming/Code/Standard_C_Library/Functions/printf

      dummy=sprintf(filename,"F3squarepmt_1300v_%.3fv00000.txt",Voltage[i]);
      dummy=sprintf(plotname,"F3squarepmt_1300v_%.3fv00000.pdf",Voltage[i]);
      cout<<"filename: "<<filename<<endl;

      // Put contents of text file into TGraph

      TGraph *OrignalADC = new TGraph(filename);
      OrignalADC->Draw("A*");

      // While-loop to continue iterating over the fit until the user approves it
      // To learn about cin and cout:
      // http://www.cplusplus.com/doc/tutorial/basic_io/

      IsPedestalFit = "N";
      while (IsPedestalFit != "Y") {

	 // Fit a gaussian over the pedestal only. Use fit output to shift ADC plot.
         // The 'gpad' lines are necessary so that the plot continues to display while waiting
	 // for user input (https://root.cern.ch/phpBB3/viewtopic.php?f=3&t=18852)

         PedestalFit = new TF1("h1","gaus",PedestalFitMin,PedestalFitMax);
         OrignalADC->Fit(PedestalFit,"R");
         OrignalADC->Draw("A*");
         gPad->Modified();
         gPad->Update();
         gSystem->ProcessEvents();
         cout << "Is the pedestal fit correctly?"<< endl;
         cout << "Return Y for yes and N for no."<< endl;
         cin >> IsPedestalFit;

	 // If pedestal fit is incorrect, change pedestal fit range and try again

         if (IsPedestalFit != "Y") {

            cout << "Enter the minimum fit range for the pedestal (ie -2e10)"<<endl;
            cin >> PedestalFitMin;
            cout << "Enter the minimum fit range for the pedestal (ie 2e10)"<<endl;
            cin >> PedestalFitMax;

         }

      }


      // Define a New TGraph with x-axis rescaled using the function below

      TGraph *ModifiedADC = rescaleaxis(OrignalADC,-1.0,-1.0*PedestalFit->GetParameter(1));

      // Use another while loop to assure that the pedestal plus signal fit is good

      IsFullADCFit = "N";
      while (IsFullADCFit != "Y") {

         // Fit with two gaussians. 0-2 are signal. 3-5 are pedestal. The 'FixParameter' keeps the pedestal gaussian fixed at 0.

         TF1 *FullADCFit = new TF1("FullADCFit","([0]*exp(-0.5*((x-[1])/[2])^2))+([3]*exp(-0.5*((x-[4])/[5])^2))",-1,1);
         FullADCFit->SetParameters(SignalNorm,SignalMean,SignalWidth,PedestalFit->GetParameter(0), 0.0, PedestalFit->GetParameter(2));
         FullADCFit->FixParameter(4,0);
         ModifiedADC->Fit(FullADCFit,"R");
         ModifiedADC->Draw("A*");
         gPad->Modified();
         gPad->Update();
         cout << "Is the full ADC distribution fit correctly?"<< endl;
         cout << "Return Y for yes and N for no."<< endl;
         cin >> IsFullADCFit;

         // If ADC isn't fit correctly, give the user a chance to change the inital values of the signal fit.

         if (IsFullADCFit != "Y") {

            cout << "Enter a new initial value for the signal normalization (ie 100)"<<endl;
            cin >> SignalNorm;
            cout << "Enter a new initial value for the signal mean (ie 5e10)"<<endl;
            cin >> SignalMean;
            cout << "Enter a new initial value for the standard deviation (ie 1e10)"<<endl;
            cin >> SignalWidth;

         }

      }
Пример #16
0
TF1 *GausBF::Bfit(TGraph *gr)
{
  TF1 *func = new TF1("func", FB(), -200, 200);
  gr->Fit("gaus", "q0");
  TF1 *fg0 = gr->GetFunction("gaus");

  Int_t ip = 3;
  for (Int_t i = 0; i < 3; i++) func->SetParameter(i, fg0->GetParameter(i));

  TGraph gd;
  TGraph gm;

  Double_t min = 0, max = 0;
  Double_t xmn = gr->GetY()[0];
  Double_t xmx = gr->GetY()[0];
  Double_t xb  = gr->GetX()[0];
  Double_t db  = 0;

  Double_t mmin = 0.002;

  for (Int_t i = 0; i < gr->GetN(); i++) {
    Double_t x = gr->GetX()[i];
    Double_t y = gr->GetY()[i];
    Double_t d = y-func->Eval(x);

    gd.SetPoint(i, x,  d);
    gm.SetPoint(i, x, -d);

    if (db*d < 0) {
      if ((d > 0 && min < -mmin) || (d < 0 && max > mmin)) {
	Double_t xm = (d > 0) ? xmn : xmx;
	Double_t w1 = x-xm;
	Double_t w2 = xm-xb;
	Double_t w  = (w1 > w2) ? w2 : w1;
	Double_t par[3];
	if (d < 0) {
	  gd.Fit("gaus", "q0", "", xm-w, xm+w);
	  TF1 *fg = gd.GetFunction("gaus");
	  for (Int_t j = 0; j < 3; j++) par[j] = fg->GetParameter(j);
	}
	else {
	  gm.Fit("gaus", "q0", "", xm-w, xm+w);
	  TF1 *fg = gm.GetFunction("gaus");
	  for (Int_t j = 0; j < 3; j++) par[j] = fg->GetParameter(j);
	  par[0] = -par[0];
	}

	for (Int_t j = 0; j < 3; j++) func->SetParameter(ip+j, par[j]);
	ip += 3;
      }
      xb = x;
      if (d < 0) min = 0;
      if (d > 0) max = 0;
    }
    db = d;

    if (d < min) { min = d; xmn = x; }
    if (d > max) { max = d; xmx = x; }
  }
  for (Int_t i = ip; i < Np; i++) func->FixParameter(i, (i%3 == 2) ? 1 : 0);

  gr->Fit(func, "q0");

  return func;
}
Пример #17
0
/** Make Va1 response
    @param n 
    @param B 
    @param dc 
    @param errors 
    @ingroup simple_script
*/
void 
VA1Response(Int_t n=4, Float_t B=6, Float_t dc=.01, Bool_t errors=kFALSE,
	    Bool_t doFit=kFALSE) 
{
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  gStyle->SetLabelFont(132, "xyz");
  gStyle->SetTitleFont(132, "xyz");
  gStyle->SetTitleSize(0.08, "y");
  gStyle->SetTitleOffset(0.5, "y");
  gStyle->SetTitleSize(0.06, "x");
  gStyle->SetTitleOffset(0.7, "x");

  TCanvas* c = new TCanvas("c", "c", 800, 500);
  c->SetFillColor(0);
  c->SetBorderMode(0);
  c->SetBorderSize(0);
  c->SetTopMargin(0.05);
  c->SetRightMargin(0.05);
  c->SetGridx();
  c->SetGridy();

  TF1* response = new TF1("response", "[0] * (1 - exp(-[1] * x))", 0, 1.4);
  response->SetParameters(1, B);
  response->SetParNames("A", "B");
  response->SetLineColor(2);
  
  TGraph* graph = 0;
  if (n >= 2) {
    if (errors) graph = new TGraphErrors(n);
    else        graph = new TGraph(n);
    for (Int_t i = 0; i < n; i++) {
      Float_t t = Float_t(i + 1) / n;
      Float_t q = gRandom->Gaus(response->Eval(t), dc);
      graph->SetPoint(i, t, q);
      if (errors) ((TGraphErrors*)graph)->SetPointError(i, 0, dc);
    }
  }

  response->Draw();
  response->GetHistogram()->GetYaxis()->SetRangeUser(0, 1.05);
  response->GetHistogram()->GetXaxis()->SetRangeUser(0, 1.1);
  response->GetHistogram()->GetXaxis()->SetNdivisions(6, kTRUE);
  response->GetHistogram()->GetYaxis()->SetNdivisions(10, kTRUE);
  response->GetHistogram()->SetXTitle("t");
  response->GetHistogram()->SetYTitle(Form("1-e^{-%3.1f t}", B));
  
  if (graph) {
    
    
    graph->Draw("P*");
    TString fitOpt("E");
    if (!errors) fitOpt.Append("W");

    if (doFit) {
      TF1* fit = new TF1("fit",  "[0] * (1 - exp(-[1] * x))",  0, 1);
      fit->SetParameters(.5, B/2);
      fit->SetParNames("A", "B");
      fit->SetLineColor(3);
      graph->Fit("fit", fitOpt.Data());
      graph->Fit("fit", fitOpt.Data());
      
      std::cout << "Chi^2/NDF = " << fit->GetChisquare() << "/" << fit->GetNDF()
		<< " = " << std::flush;
      if (fit->GetNDF() == 0) 
	std::cout << " undefined!" << std::endl;
      else
	std::cout << (fit->GetChisquare() / fit->GetNDF()) << std::endl;
      std::cout << "f(t) = " 
		<< fit->GetParameter(0) << "+/-" << fit->GetParError(0) 
		<< " * (1 - exp(" 
		<< fit->GetParameter(1) << "+/-" << fit->GetParError(1) 
		<< " * t))" << std::endl;
    }
  }

  c->Modified();
  c->Update();
  c->cd();
  c->SaveAs("va1_response.png");
}
Пример #18
0
//*****************************************************************************
void fitter::ComputeMomFromParabola(const Trajectory& traj, int nplanes, int firsthit, EVector& V){
  //*****************************************************************************

  //Some catchers for pointless returns.
  int fitcatch;
  //
  int nfit, sign;
  int fitRange[3];
  const int fitpoints = nplanes - firsthit;
  
  double xpos[fitpoints], ypos[fitpoints], zpos[fitpoints];
  double upos[fitpoints], vpos[fitpoints];

  int pos = 0;

  EVector currentpos = EVector(3,0);
  EVector currentB   = EVector(3,0);
  EVector z = EVector(3,0);
  z[2] = 1;
  double Bmean=0;
  for( int ipoint=firsthit; ipoint < nplanes; ipoint ++ ){
    xpos[pos] = traj.node(ipoint).measurement().position()[0];
    ypos[pos] = traj.node(ipoint).measurement().position()[1];
    zpos[pos] = traj.node(ipoint).measurement().position()[2]
      - traj.node(firsthit).measurement().position()[2];
    currentpos[0] = traj.node(ipoint).measurement().position()[0];
    currentpos[1] = traj.node(ipoint).measurement().position()[1];
    currentpos[2] = 0.;
    currentB = _geom.getBField(currentpos);
    upos[pos] = xpos[pos] > 0 ? asin(ypos[pos]/currentpos.norm())
      : -asin(ypos[pos]/currentpos.norm());
    vpos[pos] = dot(currentpos,crossprod(z,currentB))/currentB.norm();
    Bmean += currentB.norm();
    ++pos;
  }
  Bmean /= pos;
  Bmean /= tesla;
  
  if (fitpoints <= 15) { nfit = 1; fitRange[0] = fitpoints;}
  else if (fitpoints <= 40) { 
    nfit = 2;
    fitRange[0] = 15; fitRange[1] = (int)(0.7*fitpoints);
  }
  else if (fitpoints > 40) { 
    nfit = 3;
    fitRange[0] = 15; fitRange[1] = (int)(fitpoints/2); fitRange[2] = (int)(0.7*fitpoints);
  }
  for (int ifit = 0;ifit < nfit;ifit++) {
    TGraph *trajFitXZ = new TGraph(fitRange[ifit],zpos, xpos);
    TGraph *trajFitYZ = new TGraph(fitRange[ifit],zpos, ypos);
    TGraph *trajFitUZ = new TGraph(fitRange[ifit],zpos, upos);
    TGraph *trajFitVZ = new TGraph(fitRange[ifit],zpos, vpos);
    
    TF1 *func = new TF1("fit",fitf2,-3,3,3);
    func->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func->SetParNames("a", "b", "c", "d", "e");
    
    TF1 *func2 = new TF1("fit2",fitf2,-3,3,3);
    func2->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func2->SetParNames("f", "g", "h", "i", "j");

    TF1 *func3 = new TF1("fit3",fitf2,-3,3,3);
    func->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func->SetParNames("a1", "b1", "c1", "d1", "e1");
    
    TF1 *func4 = new TF1("fit4",fitf2,-3,3,3);
    func2->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func2->SetParNames("f1", "g1", "h1", "i1", "j1");

    fitcatch = trajFitXZ->Fit("fit", "QN");
    fitcatch = trajFitYZ->Fit("fit2", "QN");
    fitcatch = trajFitUZ->Fit("fit3", "QN");
    fitcatch = trajFitVZ->Fit("fit4", "QN");
    
    double b = func->GetParameter(1);
    double c = func->GetParameter(2);
    double g = func2->GetParameter(1);
    /*double f = func2->GetParameter(0);
      double a = func->GetParameter(0);
      double h = func2->GetParameter(2);  
      double a1 = func3->GetParameter(0);
      double b1 = func3->GetParameter(1);
      double c1 = func3->GetParameter(2);  
      double f1 = func4->GetParameter(0);*////
    double g1 = func4->GetParameter(1);
    double h1 = func4->GetParameter(2);  
    
    if (ifit == 0) {

      V[4] = g;   //func2->GetParameter(1);
      V[3] = b;

      if (h1!=0) {
	V[5] = 1./(-0.3*Bmean*pow((1+g1*g1),3./2.)/
		   (2*h1)*0.01);
	V[5] /= GeV;
	sign = (int)( V[5]/fabs( V[5] ));
      } else V[5] = 0;
    } else {
      if ((int)(-c/fabs(c)) == sign) {
	V[4] = g;
	V[3] = b;
	V[5] = 1/(-0.3*Bmean*pow((1+g1*g1),3./2.)/(2*h1)*0.01);
	V[5] /= GeV;
      } else break;
    }
    
    delete trajFitXZ;
    delete trajFitYZ;
    delete trajFitUZ;
    delete trajFitVZ;
  
    delete func;
    delete func2;
    delete func3;
    delete func4;
  }
  
  //std::cout<<"Momentum guess from polynomial fit: p/q = "<<1./V[5]<<std::endl;
}
void view_SMEvents_3D_from_Hits() {
	/*** Displays an 3D occupancy plot for each SM Event. (stop mode event)

	Can choose which SM event to start at. (find "CHOOSE THIS" in this script)
	Input file must be a Hits file (_interpreted_Hits.root file).
	***/
	gROOT->Reset();

	// Setting up file, treereader, histogram
	TFile *f = new TFile("/home/pixel/pybar/tags/2.0.2_new/pyBAR-master/pybar/module_202_new/101_module_202_new_stop_mode_ext_trigger_scan_interpreted_Hits.root");


	if (!f) { // if we cannot open the file, print an error message and return immediately
		cout << "Error: cannot open the root file!\n";
		//return;
	}

	TTreeReader *reader = new TTreeReader("Table", f);

	TTreeReaderValue<UInt_t> h5_file_num(*reader, "h5_file_num");
	TTreeReaderValue<Long64_t> event_number(*reader, "event_number");
	TTreeReaderValue<UChar_t> tot(*reader, "tot");
	TTreeReaderValue<UChar_t> relative_BCID(*reader, "relative_BCID");
	TTreeReaderValue<Long64_t> SM_event_num(*reader, "SM_event_num");
	TTreeReaderValue<Double_t> x(*reader, "x");
	TTreeReaderValue<Double_t> y(*reader, "y");
	TTreeReaderValue<Double_t> z(*reader, "z");

	// Initialize the canvas and graph
	TCanvas *c1 = new TCanvas("c1","3D Occupancy for Specified SM Event", 1000, 10, 900, 550);
	c1->SetRightMargin(0.25);
	TGraph2D *graph = new TGraph2D();

	// Variables used to loop the main loop
	bool endOfReader = false; // if reached end of the reader
	bool quit = false; // if pressed q
	int smEventNum = 1; // the current SM-event CHOOSE THIS to start at desired SM event number
	
	// Main Loop (loops for every smEventNum)
	while (!endOfReader && !quit) {
		// Variables used in this main loop
		int startEntryNum = 0;
		int endEntryNum = 0;
		string histTitle = "3D Occupancy for SM Event ";
		string inString = "";
		bool fitFailed = false; // true if the 3D fit failed
		bool lastEvent = false;

		// Declaring some important output values for the current graph and/or line fit
		int numEntries = 0;
		double sumSquares = 0;

		// Get startEntryNum and endEntryNum
		startEntryNum = getEntryNumWithSMEventNum(reader, smEventNum);
		endEntryNum = getEntryNumWithSMEventNum(reader, smEventNum + 1);

		if (startEntryNum == -2) { // can't find the smEventNum
			cout << "Error: There should not be any SM event numbers that are missing." << "\n";
		} else if (startEntryNum == -3) { 
			endOfReader = true;
			break;
		} else if (endEntryNum == -3) { // assuming no SM event nums are skipped
			endEntryNum = reader->GetEntries(false);
			lastEvent = true;
		}

		// Fill TGraph with points and set title and axes
		graph = new TGraph2D(); // create a new TGraph to refresh

		reader->SetEntry(startEntryNum);
		for (int i = 0; i < endEntryNum - startEntryNum; i++) {
			graph->SetPoint(i, (*x - 0.001), (*y + 0.001), (*z - 0.001));
			endOfReader = !(reader->Next());
		}

		histTitle.append(to_string(smEventNum));
		graph->SetTitle(histTitle.c_str());
		graph->GetXaxis()->SetTitle("x (mm)");
		graph->GetYaxis()->SetTitle("y (mm)");
		graph->GetZaxis()->SetTitle("z (mm)");

		graph->GetXaxis()->SetLimits(0, 20); // ROOT is buggy, x and y use setlimits()
		graph->GetYaxis()->SetLimits(-16.8, 0); // but z uses setrangeuser()
		graph->GetZaxis()->SetRangeUser(0, 40.96);
		c1->SetTitle(histTitle.c_str());

		// 3D Fit, display results, draw graph and line fit, only accept "good" events, get input
		if (!endOfReader || lastEvent) {
			// Display some results
			numEntries = graph->GetN();
			cout << "Current SM Event Number: " << smEventNum << "\n";
			cout << "Number of entries:       " << numEntries << "\n";

			// Starting the fit. First, get decent starting parameters for the fit - do two 2D fits (one for x vs z, one for y vs z)
			TGraph *graphZX = new TGraph();
			TGraph *graphZY = new TGraph();
			reader->SetEntry(startEntryNum);
			for (int i = 0; i < endEntryNum - startEntryNum; i++) {
				graphZX->SetPoint(i, (*z - 0.001), (*x + 0.001));
				graphZY->SetPoint(i, (*z - 0.001), (*y + 0.001));
				reader->Next();
			}
			TFitResultPtr fitZX = graphZX->Fit("pol1", "WQS"); // w for ignore error of each pt, q for quiet (suppress results output), s for return a tfitresultptr
			TFitResultPtr fitZY = graphZY->Fit("pol1", "WQS");
			Double_t param0 = fitZX->GetParams()[0];
			Double_t param1 = fitZX->GetParams()[1];
			Double_t param2 = fitZY->GetParams()[0];
			Double_t param3 = fitZY->GetParams()[1];

			// // Draw the lines for the two 2D fits
			// int n = 2;
			// TPolyLine3D *lineZX = new TPolyLine3D(n);
			// TPolyLine3D *lineZY = new TPolyLine3D(n);
			// lineZX->SetPoint(0, param0, 0, 0);
			// lineZX->SetPoint(1, param0 + param1 * 40.96, 0, 40.96);
			// lineZX->SetLineColor(kBlue);
			// lineZX->Draw("same");
			// lineZY->SetPoint(0, 0, param2, 0);
			// lineZY->SetPoint(1, 0, param2 + param3 * 40.96, 40.96);
			// lineZY->SetLineColor(kGreen);
			// lineZY->Draw("same");


			// 3D FITTING CODE (based on line3Dfit.C), draw graph and line fit
			ROOT::Fit::Fitter  fitter;
		   	SumDistance2 sdist(graph);
#ifdef __CINT__
		   	ROOT::Math::Functor fcn(&sdist,4,"SumDistance2");
#else
		   	ROOT::Math::Functor fcn(sdist,4);
#endif
			// set the function and the initial parameter values
			double pStart[4] = {param0,param1,param2,param3};
			fitter.SetFCN(fcn,pStart);
			// set step sizes different than default ones (0.3 times parameter values)
			for (int i = 0; i < 4; ++i) fitter.Config().ParSettings(i).SetStepSize(0.01);

			bool ok = fitter.FitFCN();
			if (!ok) {
			  Error("line3Dfit","Line3D Fit failed");
			  fitFailed = true;
			} else {
				const ROOT::Fit::FitResult & result = fitter.Result();
				const double * fitParams = result.GetParams();

				sumSquares = result.MinFcnValue();
				std::cout << "Sum of distance squares:  " << sumSquares << std::endl;
				std::cout << "Sum of distance squares divided by numEntries: " << sumSquares/numEntries << std::endl;
				std::cout << "Theta : " << TMath::ATan(sqrt(pow(fitParams[1], 2) + pow(fitParams[3], 2))) << std::endl;
				// result.Print(std::cout); // (un)suppress results output

				// Draw the graph
				graph->SetMarkerStyle(8);
				graph->SetMarkerSize(0.5);
				graph->Draw("pcol");

				// Draw the fitted line
				int n = 1000;
				double t0 = 0; // t is the z coordinate
				double dt = 40.96;
				TPolyLine3D *l = new TPolyLine3D(n);
				for (int i = 0; i <n;++i) {
				  double t = t0+ dt*i/n;
				  double x,y,z;
				  line(t,fitParams,x,y,z);
				  l->SetPoint(i,x,y,z);
				}
				l->SetLineColor(kRed);
				l->Draw("same");

				// Access fit params and minfcnvalue
				// cout << "FIT1: " << fitParams[1] << "\n";
				// cout << "FIT2: " << result.MinFcnValue() << "\n";
			}

			// Criteria to be a good event (if not good entry, then don't show)
			bool isGoodEvent = false;

				// the following block of code finds the mean X, Y ans Z values
				double meanX = 0;
				double meanY = 0;
				double meanZ = 0;
				reader->SetEntry(startEntryNum);
				for (int i = 0; i < endEntryNum - startEntryNum; i++) {
					meanX += graph->GetX()[i];
					meanY += graph->GetY()[i];
					meanZ += graph->GetZ()[i];
					reader->Next();
				}
				meanX /= endEntryNum - startEntryNum;
				meanY /= endEntryNum - startEntryNum;
				meanZ /= endEntryNum - startEntryNum;

				// the following code block calculates the fraction of the hits in the smEvent that are inside a sphere, centered at the mean XYZ, of radius 'radius' (larger fraction means the track is less like a long streak and more like a dense blob)
				double radius = 1; // length in mm 
				double fractionInsideSphere = 0;
				reader->SetEntry(startEntryNum);
				for (int i = 0; i < endEntryNum - startEntryNum; i++) {
					double distanceFromMeanXYZ = sqrt(pow(graph->GetX()[i] - meanX, 2) + pow(graph->GetY()[i] - meanY, 2) + pow(graph->GetZ()[i] - meanZ, 2));
					if (distanceFromMeanXYZ <= 2) {
						fractionInsideSphere += 1;
					}
					reader->Next();
				}
				fractionInsideSphere /= endEntryNum - startEntryNum;

				cout << "fraction inside sphere: " << fractionInsideSphere << "\n";

			// if (numEntries >= 50 
			// 	&& sumSquares/numEntries < 2.0 
			// 	&& fractionInsideSphere < 0.8) {

			// 	isGoodEvent = true;
			// }

			isGoodEvent = true;

			if (isGoodEvent) { // won't show drawings or ask for input unless its a good event
				c1->Update(); // show all the drawings
				// handle input
				bool inStringValid = false;
	            do {
		            cout << "<Enter>: next event; 'b': previous SM event; [number]: specific SM event number; 'q': quit.\n";
		            getline(cin, inString);

		            // Handles behavior according to input
		            if (inString.empty()) { // <Enter>
		            	// leave things be
						inStringValid = true;
		            } else if (inString.compare("b") == 0) {
						smEventNum -= 2; // because it gets incremented once at the end of this do while loop
						inStringValid = true;
					} else if (inString.compare("q") == 0 || inString.compare(".q") == 0) {
						quit = true;
						inStringValid = true;
					} else if (canConvertStringToPosInt(inString)) {
						smEventNum = convertStringToPosInt(inString) - 1; // -1 because it gets incremented once at the end of this do while loop
						inStringValid = true;
					} // else, leave inStringValid as false, so that it asks for input again
				} while (!inStringValid);
			} else {
				cout << "\n";
			}

		}
		smEventNum++;
	}

	cout << "Exiting program.\n";
}
Пример #20
0
void dumpProfile() {
  
 std::string fileName_ = "Profile_SM10.root";
 TFile *shapeFile_ = TFile::Open(fileName_.c_str(),"old");
 TProfile* PROF_704 = (TProfile*) shapeFile_->Get("SHAPE_XTAL_704");

 ofstream out;
 out.open("dat.txt");

 int nBinsHisto_ = 250;
 std::vector<double> shapeArray(nBinsHisto_,0.0);

 double max = -999;
 int imax = 0;
 for(int ibin=0; ibin < nBinsHisto_; ++ibin) 
   {
     out << "shapeArray[" << ibin << "] = " << PROF_704->GetBinContent(ibin+1) << " ; \n";
     shapeArray[ibin] = PROF_704->GetBinContent(ibin);
     std::cout << "Original shape, ns = " << ibin << " shape = " << shapeArray[ibin] << std::endl;
     if ( shapeArray[ibin] > max ) {
       max = shapeArray[ibin];
       imax = ibin;
     }

   }//loop

 out.close();

 double xMinHisto_ = -1.;
 double xMaxHisto_ = 9.;
 double binw = (xMaxHisto_ - xMinHisto_)/(shapeArray.size());
 int nbins = shapeArray.size()/10;

 float low =  xMinHisto_+(double)(imax-nbins/2+0.5)*binw;
 float up = xMinHisto_+(double)(imax+nbins/2+0.5)*binw;
 
 double* x = new double[nbins];
 double* y = new double[nbins];
 for (int i = 0; i < nbins; i++) {
   x[i] = xMinHisto_ + (double)(imax - nbins/2 + i + 0.5)*binw;
   y[i] = shapeArray[imax - nbins/2 + i];
   std::cout << " x,y = " << x[i] << " " << y[i] << " " << (double)(imax - nbins/2 + i + 0.5) << std::endl;
 }
 TGraph* graph = new TGraph(nbins, x, y);
 graph->Fit("pol3", "V");//"Q 0");
 TF1* fFit = graph->GetFunction("pol3");
 double tMax = fFit->GetMaximumX();

 std:;cout << "Maxiumum = " << tMax << std::endl;

 gStyle->SetOptFit(1111);

 TCanvas *MyC = new TCanvas("MyC","Test canvas",1); 
 MyC->Divide(2,1); 
 MyC->cd(1); 
 PROF_704->Draw(); 
 MyC->cd(2); 
 fFit->Draw(); 
 MyC->SaveAs("PROF_704.jpg");
 
}
Пример #21
0
int RAAweighting()
{
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0000);
  gStyle->SetEndErrorSize(0);
  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);

  ifstream getdata("theoryRAA/Magdalena.dat");
  if(!getdata.is_open())
    {
      cout<<"  ERROR: Opening the file fails"<<endl;
      return 1;
    }
  Int_t nbin=0;
  while(!getdata.eof())
    {
      getdata>>fpt[nbin]>>fRAA[nbin];
      cout<<fpt[nbin]<<" "<<fRAA[nbin]<<endl;
      nbin++;
    }
  TGraph* gRAA = new TGraph(nbin,fpt,fRAA);
  gRAA->SetMarkerSize(0.8);
  gRAA->SetMarkerStyle(20);
  gRAA->SetMarkerColor(kBlack);

  TCanvas* cRAA = new TCanvas("cRAA","",600,600);
  TH2F* hempty = new TH2F("hempty","",20,0.,55.,10.,0.3,0.8);  
  hempty->GetXaxis()->SetTitle("B^{+} p_{T} (GeV/c)");
  hempty->GetYaxis()->SetTitle("R_{AA}");
  hempty->GetXaxis()->CenterTitle();
  hempty->GetYaxis()->CenterTitle();
  hempty->GetXaxis()->SetTitleOffset(1.3);
  hempty->GetYaxis()->SetTitleOffset(1.8);
  hempty->GetXaxis()->SetTitleSize(0.045);
  hempty->GetYaxis()->SetTitleSize(0.045);
  hempty->GetXaxis()->SetTitleFont(42);
  hempty->GetYaxis()->SetTitleFont(42);
  hempty->GetXaxis()->SetLabelFont(42);
  hempty->GetYaxis()->SetLabelFont(42);
  hempty->GetXaxis()->SetLabelSize(0.04);
  hempty->GetYaxis()->SetLabelSize(0.04);
  hempty->Draw();
  gRAA->Draw("samep");
  TF1* fRAA = new TF1("fRAA","exp([0]+[1]*x+[2]*x*x+[3]*x*x*x)+[4]");
  fRAA->SetLineWidth(2);
  gRAA->Fit("fRAA","","",4.8,50.5);
  gRAA->Fit("fRAA","","",4.8,50.5);

  cout<<endl;
  cout<<"  exp("<<fRAA->GetParameter(0)<<"+"<<fRAA->GetParameter(1)<<"*x+"<<fRAA->GetParameter(2)<<"*x*x+"<<fRAA->GetParameter(3)<<"*x*x*x)+"<<fRAA->GetParameter(4)<<endl;
  cout<<endl;

  TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} #bf{#it{Preliminary}}");
  texCms->SetNDC();
  texCms->SetTextAlign(12);
  texCms->SetTextSize(0.04);
  texCms->SetTextFont(42);
  texCms->Draw();

  TLatex* texCol = new TLatex(0.96,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV","PbPb"));
  texCol->SetNDC();
  texCol->SetTextAlign(32);
  texCol->SetTextSize(0.04);
  texCol->SetTextFont(42);
  texCol->Draw();

  TLatex* texTheory = new TLatex(0.55,0.80, "Theory");
  texTheory->SetNDC();
  texTheory->SetTextAlign(12);
  texTheory->SetTextSize(0.04);
  texTheory->SetTextFont(42);
  texTheory->Draw();

  TLatex* texArxiv = new TLatex(0.55,0.75, "arXiv:1601.07852");
  texArxiv->SetNDC();
  texArxiv->SetTextAlign(12);
  texArxiv->SetTextSize(0.04);
  texArxiv->SetTextFont(42);
  texArxiv->Draw();

  TString tper = "%";
  TLatex* texCent = new TLatex(0.55,0.70, Form("Cent. 0-10%s",tper.Data()));
  texCent->SetNDC();
  texCent->SetTextAlign(12);
  texCent->SetTextSize(0.04);
  texCent->SetTextFont(42);
  texCent->Draw();

  cRAA->SaveAs("plots/RAAweighting.pdf");

  return 0;
}
Пример #22
0
void L1PrescalesSimulator::run(int nevs) {

	cout << "Start..." << endl;

	lumiSectTimeNs_ = 23.31;

	l_ = new TLegend(0.6, 0.7, 0.85, 0.9);

	Hbits_ = new TH1D("Hbits","",192,0.,192.);
	Hbits2_ = new TH1D("Hbits2","",192,0.,192.);

	gStyle->SetOptTitle(kFALSE);
	Hbits_->SetTitle("");
	Hbits_->GetXaxis()->SetTitle("Bit");
	Hbits2_->SetTitle("");
	Hbits2_->GetXaxis()->SetTitle("Bit");

	// clear buffers
	lumiSec2Lumi_.clear();
	lumiSec2rate_.clear();
	lumiSec2ratePrescaled_.clear();
	rateVecs_.clear();
	bit2prescale_.clear();
	bxMultiplicatorVec_.clear();
	lumiVec_.ResizeTo(0);
	bitMaskVec_.clear();

	cout << "Open config file: " << tb_.getMacroDir()
			<< "conf/PrescalesSimulator.conf" << endl;

	tb_.readConfigFile(tb_.getMacroDir() + "conf/PrescalesSimulator.conf",
			parameterMap_);

	// fill parameters
	numberOfBunches_ = toolbox::convertFromString<int>(parameterMap_["nOfBunches"]);
	commonPrescale_ = toolbox::convertFromString<int>(parameterMap_["commonPrescale"]);
	xMin_ = toolbox::convertFromString<float>(parameterMap_["xMin"]);
	xMax_ = toolbox::convertFromString<float>(parameterMap_["xMax"]);
	xFitMin_ = toolbox::convertFromString<float>(parameterMap_["xFitMin"]);
	xFitMax_ = toolbox::convertFromString<float>(parameterMap_["xFitMax"]);
	yMax_ = toolbox::convertFromString<int>(parameterMap_["yMax"]);

	int tmp = 1;

	std::map<string, string>::iterator itr;

	do {
		ostringstream oss;

		oss << tmp;

		itr = parameterMap_.find(oss.str());

		if (itr != parameterMap_.end())

			bxMultiplicatorVec_.push_back(toolbox::convertFromString<float>(itr->second));

		tmp++;

	} while (itr != parameterMap_.end());

	tmp = 1;

	tb_.readConfigFile(tb_.getMacroDir() + "conf/bitmasks.dat", parameterMap_);

	cout << "Bit masks: " << endl;

	do {
		ostringstream oss;

		oss << "m" << tmp;

		itr = parameterMap_.find(oss.str());

		if (itr != parameterMap_.end()) {
			cout << (itr->second) << endl;

			bitMaskVec_.push_back(toolbox::convertFromString<ULong64_t>(itr->second, 16));

		}

		tmp++;

	} while (itr != parameterMap_.end());

	// original luminosity and prescaled luminosity + bx multiplicator
	nOfPlots_ = 2 + bxMultiplicatorVec_.size();

	if (nevs) {

		hreset();

		getPrescales();

		getLuminosities();

		loop(bit2prescale_);

	}


	TCanvas* c2 = new TCanvas("c2", "", 900, 700);

	c2->GetEvent();

	Hbits_->Draw();
	Hbits2_->SetLineColor(2);
	Hbits2_->Draw("same");

	// draw the graphs  	

	TCanvas* c1 = new TCanvas("c1", "", 900, 700);
	c1->SetGrid(1, 1);

	TGraph* g = new TGraph(lumiVec_, rateVecs_[0]);

	g->GetXaxis()->SetLimits(xMin_, xMax_);

	g->GetXaxis()->SetTitle("Luminosity per bunch [10^{30} Hz/cm^{2}]");
	g->GetYaxis()->SetTitle("Rate [Hz]");

	g->Fit("pol2", "", "", xFitMin_, xFitMax_);

	g->SetMaximum(yMax_);

	g->Draw("A*");

	gStyle->SetOptTitle(kFALSE);
	g->SetTitle();

	ostringstream buf, buf2;
	buf << numberOfBunches_ << " (original rate)";
	buf2 << numberOfBunches_ << "b";

	l_->AddEntry(g, tb_.toCStr(buf), "l");

	TGraph* g2 = new TGraph(lumiVec_, rateVecs_[1]);

	g2->SetMarkerStyle(21);
	g2->SetLineColor(2);

	g2->Fit("pol2", "", "", xFitMin_, xFitMax_);

	TF1* fitFkt = g2->GetFunction("pol2");
	fitFkt->SetLineColor(2);

	l_->AddEntry(g2, tb_.toCStr(buf2), "l");

	g2->Draw("*");

	addGraphsForSimulatedNOfBx();

	l_->Draw();


}
Пример #23
0
void Calibrate()
{


  TCanvas *mycan1 = (TCanvas*)gROOT->FindObject("mycan1");
  if(!mycan1)
    {
      mycan1 = new TCanvas("mycan1","",1200,1000);
      mycan1->Divide(4,4,0.0000001,0.0000001);
    }

  float energy[2][32][5] = {0.};
  float peak[2][32][5] = {0.};



  ifstream file("SiCalibPoints.txt");
  if(!file.is_open())
    {
      cout << "No Si Calib Data" << endl;
      return;
    }

  ofstream out("SiRecalib.cal");

  int  itele = -1;
  int istrip = -1;

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

      file >> itele >> istrip;
      itele = itele-6;
      file >>energy[itele][istrip][0];
      file >> energy[itele][istrip][1] >> energy[itele][istrip][2];
      file >> energy[itele][istrip][3] >> energy[itele][istrip][4];
      file >> peak[itele][istrip][0] >> peak[itele][istrip][1];
      file >> peak[itele][istrip][2] >> peak[itele][istrip][3];
      file >> peak[itele][istrip][4];

    }

  float slope = 0.;
  float inter = 0.;
  for(int i = 0;i<16;i++)
    {
      mycan1->cd(i+1);
      TGraph *mygraph = new TGraph(5,peak[0][i],energy[0][i]);
      mygraph->SetMarkerStyle(20);
      mygraph->Draw("AP");

      TF1 *fit = new TF1("fit","pol1",0,500);
      mygraph->Fit("fit","RQ");

      slope = fit->GetParameter(1);
      inter = fit->GetParameter(0);
      cout << istrip <<" Slope = " << slope;
      cout << " inter = " << inter << endl;
      out << 0 << " " << i << " " << slope << " " << inter << endl;

    }

  TCanvas *mycan2 = (TCanvas*)gROOT->FindObject("mycan2");
  if(!mycan2)
    {
      mycan2 = new TCanvas("mycan2","",1200,1000);
      mycan2->Divide(4,4,0.0000001,0.0000001);
    }
  for(int i = 0;i<16;i++)
    {
      int istrip = i+16;
      mycan2->cd(i+1);
      TGraph *mygraph = new TGraph(5,peak[0][istrip],energy[0][istrip]);
      mygraph->SetTitle(Form("Strip %i",istrip));
      mygraph->SetMarkerStyle(20);
      mygraph->Draw("AP");

      TF1 *fit = new TF1("fit","pol1",0,500);
      mygraph->Fit("fit","RQ");

      cout << istrip << " Slope = " << fit->GetParameter(1);
      cout << " inter = " << fit->GetParameter(0) << endl;
      slope = fit->GetParameter(1);
      inter = fit->GetParameter(0);
      out << 0 << " " << istrip << " " << slope << " " << inter << endl;

    }
  TCanvas *mycan3 = (TCanvas*)gROOT->FindObject("mycan3");
  if(!mycan3)
    {
      mycan3 = new TCanvas("mycan3","",1200,1000);
      mycan3->Divide(4,4,0.0000001,0.0000001);
    }
  for(int i = 0;i<16;i++)
    {
      int istrip = i;
      mycan3->cd(i+1);
      TGraph *mygraph = new TGraph(5,peak[1][istrip],energy[1][istrip]);
      mygraph->SetTitle(Form("Strip %i",istrip));
      mygraph->SetMarkerStyle(20);
      mygraph->Draw("AP");

      TF1 *fit = new TF1("fit","pol1",0,500);
      mygraph->Fit("fit","RQ");

      cout << istrip << " Slope = " << fit->GetParameter(1);
      cout << " inter = " << fit->GetParameter(0) << endl;

      slope = fit->GetParameter(1);
      inter = fit->GetParameter(0);
      out << 1 << " " << istrip << " " << slope << " " << inter << endl;


    }
  TCanvas *mycan4 = (TCanvas*)gROOT->FindObject("mycan4");
  if(!mycan4)
    {
      mycan4 = new TCanvas("mycan4","",1200,1000);
      mycan4->Divide(4,4,0.0000001,0.0000001);
    }
  for(int i = 0;i<16;i++)
    {
      int istrip = i+16;
      mycan4->cd(i+1);
      TGraph *mygraph = new TGraph(5,peak[1][istrip],energy[1][istrip]);
      mygraph->SetTitle(Form("Strip %i",istrip));
      mygraph->SetMarkerStyle(20);
      mygraph->Draw("AP");

      TF1 *fit = new TF1("fit","pol1",0,500);
      mygraph->Fit("fit","RQ");

      cout << istrip << " Slope = " << fit->GetParameter(1);
      cout << " inter = " << fit->GetParameter(0) << endl;

      slope = fit->GetParameter(1);
      inter = fit->GetParameter(0);
      out << 1 << " " << istrip << " " << slope << " " << inter << endl;


    }


  return;
}
Пример #24
0
void CV(const char* fileName, const char* type, double A, double v1, double v2, double v3, double v4, double &vdepl, double &evdepl, double &neff, double &eneff, double &w, double &ew, bool savePlots=false) {

  TString simsstring("SIMU");
  TString datastring("DATA");
  int NMAX = 1001;
  if ( ! (simsstring.EqualTo(type) || datastring.EqualTo(type) ) ) {
    std::cerr << "type must be either SIMU or DATA, not -> " << type << "\n";
    exit(2);
  }
  double *C = new double[NMAX];
  double *V = new double[NMAX];
  double *logC = new double[NMAX];
  double *logV = new double[NMAX];
  double *C2 = new double[NMAX];
  double c,v;
  int i = 0;
  std::ifstream file;
  file.open(fileName);
  if ( !file.good() ) {
    std::cerr << "Problems opening file " << fileName << "\n";
    std::cerr << "rdstate =             " << file.rdstate() << "\n";
    exit(3);
  }

  while(1) {
    file >> v >> c;
    if (file.eof()) break;
    if (! (c>0) ) continue; 
    c=fabs(c);
    v=fabs(v);
    C[i]=c;
    V[i]=v;
    logC[i]=TMath::Log10(c);
    logV[i]=TMath::Log10(v);
    C2[i]=1./c/c;
    i++;
    if ( i > NMAX ) {
      std::cerr << "Too many lines: " << i << "\n";
      std::cerr << "Maximum is :    " << NMAX << "\n";
      exit(4);
    }

  } 

  TGraph* grCV = new TGraph(i,V,C);
  grCV->SetName("grCV");
  grCV->SetTitle("");
  TCanvas *c1 = new TCanvas("c1","",2000,1000);
  c1->cd();
  grCV->SetMarkerColor(kBlue);
  grCV->SetMarkerStyle(24);
  grCV->SetMarkerSize(1.2);
  grCV->SetLineColor(kBlue);
  grCV->Draw("AP");
  grCV->GetYaxis()->SetTitle("C [F]");
  grCV->GetXaxis()->SetTitle("V_{bias} [V]");
  c1->SetTicks(1);
  c1->SetGrid(1,1);

  TCanvas *c2 = new TCanvas("c2","",2000,1000);
  c2->cd();
  TGraph* grlogClogV = new TGraph(i,logV,logC);
  grlogClogV->SetName("grlogClogV");
  grlogClogV->SetTitle("");
  grlogClogV->SetMarkerColor(kBlack);
  grlogClogV->SetMarkerStyle(24);
  grlogClogV->SetMarkerSize(1.2);
  grlogClogV->SetLineColor(kBlack);
  grlogClogV->Draw("AP");
  grlogClogV->GetYaxis()->SetTitle("log_{10}(C/F)");
  grlogClogV->GetXaxis()->SetTitle("log_{10}(V_{bias}/V)");
  c2->SetTicks(1);
  c2->SetGrid(1,1);

  double logv1 = TMath::Log10(v1);
  double logv2 = TMath::Log10(v2);
  double logv3 = TMath::Log10(v3);
  double logv4 = TMath::Log10(v4);

  TF1 *loglin1 = new TF1("loglin1","[0]+[1]*x",logv1,logv2);
  TF1 *loglin2 = new TF1("loglin2","[0]+[1]*x",logv3,logv4);
  loglin1->SetLineColor(kRed);
  loglin2->SetLineColor(kBlue);
  grlogClogV->Fit("loglin1","R","",logv1,logv2);
  grlogClogV->Fit("loglin2","R+","",logv3,logv4);

  double logq1 = loglin1->GetParameter(0);
  double logq2 = loglin2->GetParameter(0);
  double logm1 = loglin1->GetParameter(1);
  double logm2 = loglin2->GetParameter(1);

  double elogq1 = loglin1->GetParError(0);
  double elogq2 = loglin2->GetParError(0);
  double elogm1 = loglin1->GetParError(1);
  double elogm2 = loglin2->GetParError(1);

  assert((logm1-logm2)!=0);
  double logvdep = (logq1-logq2)/(logm2-logm1);
  vdepl = TMath::Power(10.,logvdep);
  double Deltam = sqrt(TMath::Power(elogm1,2.)+TMath::Power(elogm2,2.));
  double Deltaq = sqrt(TMath::Power(elogq1,2.)+TMath::Power(elogq2,2.));

  evdepl = sqrt(TMath::Power(Deltaq,2.)/TMath::Power((logm2-logm1),2.) + TMath::Power(Deltam,2.)*TMath::Power((logq1-logq2),2.)/TMath::Power((logm2-logm1),2.));

  evdepl = TMath::Power(10.,evdepl);

  TF1 *flog1 = new TF1("flog1","[0]+[1]*x",logv1*0.8,logv2*1.2);
  TF1 *flog2 = new TF1("flog2","[0]+[1]*x",logv3*0.8,logv4*1.2);
  flog1->SetParameters(logq1,logm1);
  flog2->SetParameters(logq2,logm2);
  flog1->SetLineStyle(7);
  flog1->SetLineColor(loglin1->GetLineColor());
  flog2->SetLineStyle(kDashed);
  flog2->SetLineColor(loglin2->GetLineColor());
  grlogClogV->Draw("AP");
  flog1->Draw("same");
  flog2->Draw("same");
  loglin1->Draw("same");
  loglin2->Draw("same");


  TCanvas *c3 = new TCanvas("c3","",2000,1000);
  c3->cd();
  TGraph *grC2V = new TGraph(i,V,C2);
  grC2V->SetName("grC2V");
  grC2V->SetTitle("");
  grC2V->SetMarkerColor(kBlue);
  grC2V->SetMarkerStyle(24);
  grC2V->SetMarkerSize(1.2);
  grC2V->SetLineColor(kBlue);
  grC2V->Draw("AP");
  grC2V->GetYaxis()->SetTitle("C^{-2} [F^{-2}]");
  grC2V->GetXaxis()->SetTitle("V_{bias} [V]");
  c3->SetTicks(1);
  c3->SetGrid(1,1);

  grC2V->Fit("pol1","R","",v1,v2);
  TF1 *lin = (TF1*)gROOT->GetFunction("pol1");
  lin->SetLineColor(kRed);

  double C2der = lin->GetParameter(1);
  double eC2der = lin->GetParError(1);

  neff = 2./A/A/q0/eR/e0/C2der;
  eneff = 2./A/A/q0/eR/e0/C2der/C2der*eC2der;

  w = TMath::Power(2.*eR*e0*vdepl/q0/neff,0.5);

  double ewA = 2*eR*e0/q0;
  ewA = TMath::Power(ewA,0.5);

  double ewNeff = 0.5*ewA*TMath::Power(vdepl,0.5)*TMath::Power(neff,-1.5)*eneff;
  double ewV = 0.5*ewA*TMath::Power(vdepl,-0.5)*TMath::Power(neff,-0.5)*evdepl;

  ew = TMath::Sqrt(ewNeff*ewNeff+ewV*ewV);

  std::cout << "v1 = " << v1 << " V\n"; 
  std::cout << "v2 = " << v2 << " V\n"; 
  std::cout << "v3 = " << v3 << " V\n"; 
  std::cout << "v4 = " << v4 << " V\n"; 

  std::cout << "vdepl = " << vdepl << " V \n";
  std::cout << "evdepl = " << evdepl << " V \n";

  std::cout << "neff = " << neff << " 1./cm^3\n";
  std::cout << "eneff = " << eneff << " 1./cm^3\n";
  std::cout << "w = " << w*1e+4 << " um\n";
  std::cout << "ew = " << ew*1e+4 << " um\n";

  file.close();

  if ( savePlots == true ) {
    std::cout << "I will save plots\n";
    TString saveFile(fileName);
    TString cvFile = saveFile;
    cvFile.ReplaceAll(".dat","_CV.png");
    TString c2vFile = saveFile;
    c2vFile.ReplaceAll(".dat","_C2V.png");
    TString logclogvFile = saveFile;
    logclogvFile.ReplaceAll(".dat","_logClogV.png");
    c1->Draw();
    c1->SaveAs(cvFile.Data());
    c2->Draw();
    c2->SaveAs(logclogvFile.Data());
    c3->Draw();
    c3->SaveAs(c2vFile.Data());
  }

} 
Пример #25
0
/*============================================================================*/
void gaus2peakfit(Char_t *s, Float_t x1, Float_t x2, Float_t x3, Float_t x4)
{
  Double_t par[8],epar[8],x[2],y[2];
  TH1 *hist;
  hist = (TH1 *) gROOT->FindObject(s);
  TCanvas *c1=(TCanvas*) gROOT->FindObject("c1");
  if(c1==NULL)setcanvas(1);
  c1->Clear();
  hist->SetAxisRange(x1-30,x4+30);
  hist->Draw();

  //--**-- Linear background estimation --**--//
  x[0] = x1;
  x[1] = x4;
  Int_t bin1 = hist->FindBin(x1);
  y[0] = hist->GetBinContent(bin1);
  Int_t bin2 = hist->FindBin(x4);
  y[1] = hist->GetBinContent(bin2);
  TGraph *g = new TGraph(2,x,y);
  TF1 *fpol1 = new TF1("POL1","pol1",x1,x4);
  g->Fit(fpol1,"RQN");
  par[6]=fpol1->GetParameter(0);
  par[7]=fpol1->GetParameter(1);

  //--**-- Two Gaussian Peak estimation without background --**--//
  fgaus1 = new TF1("m1","gaus",x1,x2);
  fgaus2 = new TF1("m2","gaus",x3,x4);
  hist->Fit(fgaus1,"R+QN");
  hist->Fit(fgaus2,"R+QN");
  fgaus1->GetParameters(&par[0]);
  fgaus2->GetParameters(&par[3]);

  //--**-- Final Peak Fit with Background --**--//
  func = new TF1("m","gaus(0)+gaus(3)+pol1(6)",x1,x4);
  func->SetParameters(par);

  
  hist->Fit(func,"R+QN");
  func->SetLineWidth(0.5);
  func->SetLineStyle(1);
  func->SetLineColor(4);
  func->SetFillColor(4);
  func->Draw("same");
  func->GetParameters(par);
  epar[0]=func->GetParError(0);
  epar[1]=func->GetParError(1);
  epar[2]=func->GetParError(2);
  epar[3]=func->GetParError(3);
  epar[4]=func->GetParError(4);
  epar[5]=func->GetParError(5);
 
  Double_t fwhm1 = par[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm1 = epar[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N10 = par[0]*(TMath::Sqrt(TMath::TwoPi())*par[2]);
  Double_t r10 = epar[0]/par[0];
  Double_t r12 = epar[2]/par[2];
  Double_t eN10= N10*TMath::Sqrt(r10*r10+r12*r12);

  Double_t fwhm2 = par[5]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm2 = epar[5]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N20 = par[3]*(TMath::Sqrt(TMath::TwoPi())*par[5]);
  Double_t r20 = epar[3]/par[3];
  Double_t r22 = epar[5]/par[5];
  Double_t eN20= N20*TMath::Sqrt(r20*r20+r22*r22);

  //printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
  //        par[1],epar[1],fwhm1,efwhm1,N10,eN10);
  //printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
  //        par[4],epar[4],fwhm2,efwhm2,N20,eN20);
  printf("%11.4f %11.4f %11.0f %11.0f\n",
          par[1],epar[1],N10,eN10);
  printf("%11.4f %11.4f %11.0f %11.0f\n",
          par[4],epar[4],N20,eN20);
}
Пример #26
0
void WaveformAna3Tcell::analyze3TCellWaveform(bool &hit, float &stepSize, float &timeConstant, float &hitDetectionTime, float &offset, float &slope, float &chi2)
{
  if(!_wave)
    return;
  // filter data
  if (!_wave->isFiltered())
    _wave->applyLowPassFilter(_avgBufLen);
 
  // check for hit
  _hit = checkForHit(_cutSimpleThreshold);
  int hitStartTime = 0;
  if(_hit){
    hitStartTime = getHitStartTime(_cutTime, _cutTimeThreshold);
  
    if(!_hit && (hitStartTime == 0))
    { //no hit, go out!
      return;
    } 
    else
    {
  
    stepSize = 0;
    timeConstant = 0;
    
    // cout << "\tDetected " << hitCnt << " hits" << endl;
    stepSize = 0.04;
    timeConstant = hitStartTime;
    //showWaveform(_waveOrig);
    
    //Fit parameters:
    double par[5];
    par[0]= _wave->getAmpl()[hitStartTime];				  //Offset of linear w/o hit	--> Charge collected by leakage current
    par[1]= -0.000001;                              //(_wave->getAmpl()[_avgBufLen*10] - _wave->getAmpl()[hitStartTime])/(double)(_wave->getTime()[hitStartTime]-_wave->getTime()[_avgBufLen*10]);	//Slope	without hit		--> Leakage current
    par[2]= 100.0;																  //Time Constant of exp	--> Charge collection time
    par[3]= (double)_wave->getTime()[hitStartTime];	//Start time of step		--> Time of particle detection
    par[4]= abs(_wave->getAmpl()[_wave->getSize() - _avgBufLen*10] - _wave->getAmpl()[hitStartTime]);								//Step Amplitude 		--> Collected charge 
    //cout << "Parameters: " << par[0] << ", " << par[1] << ", " << par[2] << ", " << par[3] << ", " << par[4] << endl;

    //due to possible resets, fit range needs to be defined dynamically outside reset range
    double min = _wave->getTime()[_avgBufLen*10];
    double max = _wave->getTime()[_wave->getSize()-_avgBufLen*5];
    if (hitStartTime > _resetEnd){
      min = _wave->getTime()[_resetEnd];
      max = _wave->getTime()[_wave->getSize()-_avgBufLen*5];
    }
    else if ((hitStartTime < _resetStart) && (_resetStart > 0)){
      min = _wave->getTime()[_avgBufLen*10];
      max = _wave->getTime()[_resetStart];
    }

    //Initiate function
    TF1 *expStep = new TF1("expStep", this, &WaveformAna3Tcell::expstep, min, max, 5, "WaveformAna3Tcell", "expstep");

    expStep->SetParameter(0, par[0]);
    expStep->SetParameter(1, par[1]);
    expStep->SetParameter(2, par[2]);
    expStep->SetParameter(3, par[3]);
    expStep->SetParameter(4, par[4]);
    
    //showWaveform(_wave, expStep);
    TGraph *wavegraph = new TGraph(_wave->getSize(), _wave->getTime(), _wave->getAmpl());
    TFitResultPtr ptr = wavegraph->Fit("expStep", "SQ", "", min, max);

    
      
    if (_showPulse)
      showWaveform(_wave, expStep);
      
    //Check and assign invalid, if needed. Need to define invalid conditions
    if((ptr->Chi2() > _cutChi2) || (expStep->GetParameter(3) < _cutMinHitDetectionTime) || (expStep->GetParameter(3) > _cutMaxHitDetectionTime))
      _isInvalid = true;

    //fill the results into the given parameters
    offset = expStep->GetParameter(0);
    slope = expStep->GetParameter(1);
    timeConstant = expStep->GetParameter(2);
    hitDetectionTime = expStep->GetParameter(3);
    stepSize = expStep->GetParameter(4);
    chi2 = ptr->Chi2();
    hit = _hit;
    
    //For online histogram of amplitude
    _stepAmplitude = expStep->GetParameter(4);
    
    if(expStep) delete expStep;
    if(wavegraph) delete wavegraph;
  }
  }
}
Пример #27
0
TF1* calibration_plot(float displacement = 0., int color = 1, char el_name[50] = "\"MQM.9R5.B1\"", string file  = "data/lpair_mumu_2gev.root") {

	vector<float> rec_e;
	vector<float> x_rp;

	H_BeamLine* beam1 = new H_BeamLine( 1,500);
	beam1->fill("data/LHCB1IR5_v6.500.tfs");
	H_RomanPot* rp = new H_RomanPot("RP",420.,3500.);
	beam1->add(rp);
	beam1->alignElement(el_name,displacement,0);

	
	// reading yanwen file
	TF1 * fake = new TF1("fake","1",0,1); // in case of trouble
	TFile* calfile = new TFile(file.c_str());
		if(calfile->IsZombie()) {cout << "Can not open the file : " << file << endl; return fake;}
	TTree* caltree = (TTree*) calfile->Get("h101");
		if(!caltree) {cout << "Can not open the tree.\n"; return fake;}
	delete fake; // forget about it
	

	float phep[4][5];
	caltree->SetBranchAddress("Phep",phep);
	/* phep[0] & phep[3] = protons
	 * phep[1] & phep[2] = muons */

	TLorentzVector mu1, mu2, cms;
	float m_mumu, pz_mumu;
	float gammae_1_central, gammae_2_central;
	float rho;
	int nentries = caltree->GetEntriesFast();
	for (int jentry=0; jentry<nentries;jentry++) {
		caltree->GetEntry(jentry);
		mu1.SetXYZM(phep[1][0],phep[1][1],phep[1][2],0);
		mu2.SetXYZM(phep[2][0],phep[2][1],phep[2][2],0);
		cms = mu1;
		cms += mu2;
		m_mumu = cms.M();
		pz_mumu = cms.Pz();
		rho = sqrt(m_mumu*m_mumu + pz_mumu*pz_mumu);
		gammae_1_central = (  pz_mumu + rho)/2.;
		gammae_2_central = ( -pz_mumu + rho)/2.;

		H_BeamParticle p1;
		p1.smearPos();
		p1.smearAng();
		p1.setE(phep[0][3]);
		p1.computePath(beam1,1);
		if(p1.stopped(beam1)) {
			if(p1.getStoppingElement()->getName()>="RP") {
				p1.propagate(420);
				rec_e.push_back(gammae_1_central);
				x_rp.push_back(p1.getX()/1000.);
			}
		}
	}
	const int npoints = rec_e.size();
	float rece[npoints];
	float xrp[npoints];
	for(int i = 0; i < npoints; i++) {
		rece[i] = rec_e[i];
		xrp[i]  = x_rp[i];
	}
	TGraph* correl = new TGraph(npoints,xrp,rece);
	char title[100];
	sprintf(title,"Calibration of roman pots from central objects variables - %d events",npoints);
	correl->SetTitle(title);
	correl->SetMarkerColor(color);

	correl->Draw("ap");

	sort(x_rp.begin(),x_rp.end());
	TF1* fit1 = new TF1("fit1","[0] + [1] * x + [2] * x * x",x_rp[0],x_rp[npoints-1]);
	correl->Fit("fit1","Q");
//	correl->GetYaxis()->SetTitle("Photon energy from central state (GeV)");
//	correl->GetXaxis()->SetTitle("X position of proton at RP (mm)");

	TCanvas * raoul = new TCanvas();
	correl->Draw("ap");
	return fit1;
}
Пример #28
0
//*****************************************************************************
void fitter::ComputeMomFromRange(const Trajectory& traj, int nplanes, int firsthit, EVector& V){
  //*****************************************************************************

  //Some catchers for pointless returns.
  int fitcatch;
  //
  /// int nfit;
  /// int fitRange[3];
  const int fitpoints = nplanes - firsthit;
  ///double meanchange = 0;
  double xpos[fitpoints], ypos[fitpoints], zpos[fitpoints];
  double upos[fitpoints];/// wpos[fitpoints];
  std::vector<EVector> dr;
  std::vector<EVector> B;
  bool isContained = true, cuspfound = false;



  double Xmax = _geom.getPlaneX() - 1*cm;
  double Ymax = _geom.getPlaneY() - 1*cm;
  /// double Zmax = _geom.getPlaneZ() - 1*cm;
  //double dx[fitpoints-1], dy[fitpoints-1], dz[fitpoints-1];
  // double ax[fitpoints-2], ay[fitpoints-2], az[fitpoints-2];
  // double bx[fitpoints-2], by[fitpoints-2], bz[fitpoints-2];
  
  

  ///double ds0=0, ds1=0;
  double Bmean=0;
  double pathlength=0;
  int Npts=0;
  ///double initR = 0;
  double sumDR = 0;
  int minindex = nplanes - firsthit;
  ///double minR = 999999.9999;
  double pdR = 0.0;
  
  
  
  EVector Z = EVector(3,0); Z[2] = 1;
  for (int ipoint=firsthit;ipoint < nplanes;ipoint++){
    
    xpos[ipoint-firsthit] = traj.node(ipoint).measurement().position()[0];
    ypos[ipoint-firsthit] = traj.node(ipoint).measurement().position()[1];
    zpos[ipoint-firsthit] = traj.node(ipoint).measurement().position()[2]
      - traj.node(firsthit).measurement().position()[2];
    if(fabs(xpos[ipoint-firsthit]) > Xmax || fabs(ypos[ipoint-firsthit]) > Ymax)
      isContained = false;
    else if(fabs(ypos[ipoint-firsthit]) > 
	    (1 + tan(atan(1.)/2.)) * Xmax - fabs(xpos[ipoint-firsthit])) 
      isContained = false;
    EVector pos0 = EVector(3,0);
    pos0[0] = xpos[ipoint-firsthit];
    pos0[1] = ypos[ipoint-firsthit];
    pos0[2] = zpos[ipoint-firsthit];
    EVector B0 = _geom.getBField(pos0);
    B.push_back(B0);
    Bmean += B0.norm();
    upos[ipoint-firsthit] = // sqrt(pos0[0]*pos0[0] + pos0[1]*pos0[1]);
      dot(pos0,crossprod(Z, B0))/crossprod(Z, B0).norm();
    //if(!cuspfound)
    //  if(ipoint == firsthit) initR = upos[ipoint-firsthit];
    //  else {
    //sumDR += initR - upos[ipoint-firsthit];
    //initR = upos[ipoint - firsthit];
    //  }
    Npts++;
    if ( ipoint > firsthit){
      EVector drtemp = EVector(3,0);
      drtemp[0] = xpos[ipoint-firsthit] - xpos[ipoint-firsthit-1];
      drtemp[1] = ypos[ipoint-firsthit] - ypos[ipoint-firsthit-1];
      drtemp[2] = zpos[ipoint-firsthit] - zpos[ipoint-firsthit-1];
      dr.push_back(drtemp);      
      pathlength +=  drtemp.norm();
      if ( ipoint > firsthit + 1 ) {
	int k = ipoint-firsthit-1;
	EVector dr0 = dr[k-1];
	EVector dr1 = dr[k];
	EVector ddr = dr1 + dr0;
	EVector Ddr = dr1 - dr0;
	EVector pos = EVector(3,0);
	pos[0] = xpos[k-1]; pos[1] = ypos[k-1]; pos[2] = zpos[k-1]; 
	EVector B = _geom.getBField(pos);
	double dR = dot(ddr, crossprod(Z, B0))/ (crossprod(Z,B0).norm());
	double DR = dot(Ddr, crossprod(Z, B0))/ (crossprod(Z,B0).norm());
	if(pdR != 0.0){
	  if(!cuspfound && DR/fabs(DR) == pdR/fabs(pdR)){
	    // sumDR += fabs(dR) > 0.0 ? dR/fabs(dR):0.0;
	    sumDR += dR;
	    // pdR = dR;
	    pdR = dR;
	  }
	  else if(dR/fabs(dR) != pdR/fabs(pdR)){
	    // cuspfound = true;
	    minindex = ipoint - firsthit - 1;
	    pdR = dR;
	    // std::cout<<"At cusp, sumDR = "<<sumDR<<std::endl;
	  }
	}
	else if(!cuspfound && fabs(dR) > 0){
	  // sumDR += fabs(DR) > 0.0 ? DR/fabs(DR) : 0.0;
	  sumDR += dR;
	  pdR = dR;
	}
	/*
	  if(pdR != 0){
	  if(minR < upos[ipoint - firsthit - 1] &&
	  (xpos[ipoint-firsthit]/fabs(xpos[ipoint-firsthit]) != 
	  xpos[ipoint-firsthit-1]/fabs(xpos[ipoint-firsthit-1])) ||
	  (ypos[ipoint-firsthit]/fabs(ypos[ipoint-firsthit]) != 
	  ypos[ipoint-firsthit-1]/fabs(ypos[ipoint-firsthit-1]))
	  && !cuspfound){
	  minR = upos[ipoint - firsthit - 1];
	  minindex = ipoint - firsthit - 1;
	  cuspfound = true;
	  }
	  }*/
      }
    }
  }
  Bmean /=Npts;
  
  double wFe = _geom.get_Fe_prop();
  double p = (wFe*(0.017143*GeV/cm * pathlength - 1.73144*GeV)
	      + (1- wFe)*(0.00277013*GeV/cm * pathlength + 1.095511*GeV));
  double meansign = 1;
  if(sumDR != 0) {
    //std::cout<<"sumDR = "<<sumDR<<std::endl;
    meansign = sumDR/fabs(sumDR);
  }
  
  ///double planesep  = fabs(zpos[1] - zpos[0]);



  // Assume that the magnetic field does not change very much over 1 metre
  // (terrible assumption by the way)
  const int sample = minindex < 20 ? (const int)minindex: 20;
  
  int pi3=0, pi4=0;
  while(dr.at(pi3)[2] == 0.0) pi3++;
  while(dr.at(pi4)[2] == 0.0) pi4++;
  V[3] = dr.at(pi3)[0]/dr.at(pi3)[2];
  V[4] = dr.at(pi4)[1]/dr.at(pi4)[2];
  if(isContained && p != 0)
    V[5] = meansign/fabs(p);
  else{


    // meansign = 0;
    // Consider a fit to a subset of points at the begining of the track
    //for(int j=0; j<fitpoints-2; j++){
    TGraph* localcurveUW = new TGraph(sample, zpos, upos);
    TF1 *func = new TF1("fit",fitf2,-30,30,4);
    func->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func->SetParNames("a", "b", "c", "d", "e");
    fitcatch = localcurveUW->Fit("fit", "QN");
    double b = func->GetParameter(1);
    double c = func->GetParameter(2);
    
    p = 300.0 * B[1].norm() * pow(1. + b*b,3./2.) /2./c;
    //double wt = TMath::Gaus(fabs(pt), p, 0.25*p, true);
    // std::cout<<pt<<std::endl;
    // meansign += wt * pt/fabs(pt);
    
    delete localcurveUW;      
    delete func;
    if(p!=0){
      meansign = p/fabs(p);
      V[5] = 1./p;
    }
  
  }
  int sign = 1;
  if(meansign==meansign){
    if(meansign!=0)
      sign = int(meansign/fabs(meansign));
    else
      sign = 0;
  }
  else
    sign = 1;




  // std::cout<<"Pathlength is "<<pathlength // <<" or "<<pathlength0
  //	   <<" with charge "<<meansign<<std::endl;
  
  _initialqP = V[5];
  // _m.message("_initialqP ="<<_initialqP,bhep::VERBOSE);
  
}
void FindConstant::drawChi2AndFitPol2(const std::vector<double>& res, const std::vector<double>& chi2)
{
  TCanvas* c1 = new TCanvas();
  std::stringstream streamForEResExtraction;
  streamForEResExtraction << scintillatorID << "_beta_" << energyResolution;

  std::vector<double> Chi2ToFit, ResToFit;
  for (size_t i = 0; i < chi2.size(); i++) {
    if (chi2[i] < bestChi2 + 50.0) {
      std::cout << chi2[i] << std::endl;
      Chi2ToFit.push_back( chi2[i] );
      ResToFit.push_back( res[i] );
    }
  }

  TMultiGraph* m = new TMultiGraph();

  TGraph* gr = new TGraph(Chi2ToFit.size(), &ResToFit[0], &Chi2ToFit[0]);
  gr->SetTitle("Chi2 vs #beta");
  gr->GetXaxis()->SetTitle("#beta (#sqrt{keV})");
  gr->GetYaxis()->SetTitle("Chi2 for best fit");
  gr->SetLineColor(2);
  gr->SetLineWidth(4);
  gr->SetMarkerColor(4);
  gr->SetMarkerStyle(21);
  gr->Draw("AP");
  gStyle->SetOptFit(1);

  quadraticFit = new TF1("quadraticFit", "[0]* (x - [1])**2 + [2]", ResToFit[0], ResToFit[ ResToFit.size() - 1 ] );
  quadraticFit->SetParName(0, "a");
  quadraticFit->SetParName(1, "x_min");
  quadraticFit->SetParName(2, "y_min");
  quadraticFit->SetParameter(1, energyResolution);
  quadraticFit->SetParameter(2, bestChi2);
  gr->Fit(quadraticFit, "R");
  quadraticFit->Draw("same");
  std::stringstream buf;
  buf << sourcePosition;
  c1->SaveAs( ("FitResults" + filePath + buf.str() + "/Chi2Plot_strip_fitRegion_" + streamForEResExtraction.str() + expHistoTitle + ".png") );

  m->Add(gr);

  energyResolution = quadraticFit->GetParameter(1);

  TGraph* grFull = new TGraph(chi2.size(), &res[0], &chi2[0]);
  grFull->SetTitle("Chi2 vs #beta");
  grFull->GetXaxis()->SetTitle("#beta (#sqrt{keV})");
  grFull->GetYaxis()->SetTitle("Chi2 for best fit");
  grFull->SetLineColor(2);
  grFull->SetLineWidth(4);
  grFull->SetMarkerColor(4);
  grFull->SetMarkerStyle(21);

  m->Add(grFull);

  m->Draw("AP");

  c1->SaveAs( ("FitResults" + filePath + buf.str() + "/Chi2Plot_strip_" + streamForEResExtraction.str() + expHistoTitle + ".png") );

  delete gr;
  delete c1;
}
Пример #30
0
int AngOptimize()
{
  ifstream infile("angSNR.dat");
  ofstream outfile("OptAng.dat",ios::app);

  istringstream iss;
  char line[1000];

  cout<<"aaaaaaaa"<<endl;
  const int nene=21;
  const int nep = 28;
  double epn[nene][nep];
  double sigN[nene][nep];
  double bckN[nene][nep];
  double snr[nene][nep];
  int iene=-1;
  int iep=-1;
  double enes[nene];
  double opteps[nene];
  char title[nene][1000];

  TF1 *fit = new TF1("fit","[0]*(x-[2])+[1]/(x-[2])+[3]",178,179.6);
  fit->SetParameter(0,1.5);
  fit->SetParameter(1,1);
  fit->SetParameter(2,180);
  fit->SetParLimits(2,180,180)
  fit->SetParameter(3,40);

  bool start=0;
  if (!infile.is_open()) return -1;
  while (!infile.eof()){
    //cout<<"b"<<endl;
    infile.getline(line,1000);
	if (line[0]!='K') 
	{
	  if (!start) continue;
	  if (line[0]=='#' || line[0]==' ') continue;
	}
	else {
	  iep=-1; start=1;
	  iene++;
	  if (iene>=21) break;
	  string tit;
	  iss.clear();
	  iss.str(line);
          iss >> tit;
	  std::cout<<tit<<endl;
	  sprintf(title[iene],"%s",tit.c_str());
	  continue;
	}
	iep++;
	//cout<<line<<endl;
	iss.clear();
	iss.str(line);
	double ratio,signal,background;
	iss >> ratio >> signal >> background; // 3 sigma
	//iss >> signal >> background; // 5 sigma

	epn[iene][iep] = ratio;
	sigN[iene][iep] = signal;
	bckN[iene][iep] = background;
	
	if (sigN[iene][iep]==0) snr[iene][iep] = 0;
	else snr[iene][iep] = sigN[iene][iep]/sqrt(sigN[iene][iep]+bckN[iene][iep]);
	//cout<< epn[iene][i]<<sigN[iene][i]<<bckN[iene][i]<<endl;
  }

  for (iene=0;iene<nene;iene++){
	TGraph *graph = new TGraph(nep,epn[iene],snr[iene]);
	graph->SetTitle(title[iene]);
	graph->SetMarkerStyle(25);
	graph->GetYaxis()->SetTitle("S/#sqrt{S+N}");
	graph->GetXaxis()->SetTitle("#theta");
	TCanvas *ca1 = new TCanvas(title[iene], title[iene]);
	graph->Draw("AP");
	//graph->Fit("pol4","","",178,179.9);
////////TF1 *fpol2 = graph->GetFunction("pol2");
////////fit->SetParameter(0,fpol2->GetParameter(0));
////////fit->SetParameter(1,fpol2->GetParameter(1));
////////fit->SetParameter(2,fpol2->GetParameter(2));
	//graph->Fit(fit,"","",178,179.6);
	graph->Fit(fit,"","",172.0+iene*6.0/21.0,179.9);
	double optep = fit->GetMaximumX(176,179.6);
	outfile<<"Optmized theta at "<< title[iene] << " is "<<optep<<std::endl;
	enes[iene] = atof(&title[iene][3])/10000.;
	opteps[iene] = optep;
	char ofname[1000];
	sprintf(ofname,"output/Angopt_%s.pdf",title[iene]);
	ca1->Print(ofname);
  } 
  TGraph* gep = new TGraph(iene,enes,opteps);
  gep->SetTitle("Optimized #theta");
  gep->SetMarkerStyle(25);
  gep->GetYaxis()->SetTitle("S/#sqrt{S+N}");
  gep->GetXaxis()->SetTitle("#theta");
  TCanvas *ca1 = new TCanvas("gep","Optimized #theta");
  gep->Draw("AP");
  gep->Fit("pol1");
  ca1->Print("output/Angopt.pdf");
  double c0 = gep->GetFunction("pol1")->GetParameter(0);
  double c1 = gep->GetFunction("pol1")->GetParameter(1);
  //double c2 = gep->GetFunction("pol2")->GetParameter(2);
  outfile << "Theta = "<< c0 << " + " << c1 << "*x + "  <<std::endl;
  std::cout << "Theta = "<< c0 << " + " << c1 << "*x + "<<std::endl;
  return 0;
}