Esempio n. 1
0
Double_t dExpFunc(const TF1 *fcn, const Double_t x, const TFitResultPtr fs) {
  Double_t df[3];
  Double_t a = fcn->GetParameter(0);
  Double_t b = fcn->GetParameter(1);
  Double_t c = fcn->GetParameter(2);

  TF1 *deriv_par0 = new TF1("dfdp0",df_dParExp,130,1500,4);
  deriv_par0->SetParameters(0,a,b,c); // This will set the derivative for the first parameter.
  TF1 *deriv_par1 = new TF1("dfdp1",df_dParExp,130,1500,4);
  deriv_par1->SetParameters(1,a,b,c); // This will set the derivative for the second parameter
  TF1 *deriv_par2 = new TF1("dfdp2",df_dParExp,130,1500,4);
  deriv_par2->SetParameters(2,a,b,c); // This will set the derivative for the 3rd parameter
  df[0] = deriv_par0->Eval(x);
  df[1] = deriv_par1->Eval(x);
  df[2] = deriv_par2->Eval(x);
  Double_t err2=0;
  for(Int_t i=0; i<3; i++) {
    err2 += df[i]*df[i]*(fs->GetCovarianceMatrix()[i][i]);
    for(Int_t j=i+1; j<3; j++) {
      err2 += 2.0*df[i]*df[j]*(fs->GetCovarianceMatrix()[i][j]);
    }
  }
  assert(err2>=0);
  return sqrt(err2);
}
Esempio n. 2
0
std::pair<double,double> CalibTree::fitMean(TH1D* hist, int mode) {
  std::pair<double,double> results = std::pair<double,double>(1,0);
  if (hist != 0) {
    double mean = hist->GetMean(), rms = hist->GetRMS();
    double LowEdge(0.7), HighEdge(1.3);
    char   option[20];
    if (mode == 1) {
      LowEdge  = mean - 1.5*rms;
      HighEdge = mean + 1.5*rms;
      int nbin = hist->GetNbinsX();
      if (LowEdge < hist->GetBinLowEdge(1)) LowEdge = hist->GetBinLowEdge(1);
      if (HighEdge > hist->GetBinLowEdge(nbin)+hist->GetBinWidth(nbin))
	HighEdge = hist->GetBinLowEdge(nbin)+hist->GetBinWidth(nbin);
    }
    if (hist->GetEntries() > 100) sprintf (option, "+QRLS");
    else                          sprintf (option, "+QRWLS");
    double value(mean);
    double error = rms/sqrt(hist->GetEntries());
    if (hist->GetEntries() > 20) {
      TFitResultPtr Fit = hist->Fit("gaus",option,"",LowEdge,HighEdge);
      value    = Fit->Value(1);
      error    = Fit->FitResult::Error(1); 
      /*
      LowEdge  = value - 1.5*error;
      HighEdge = value + 1.5*error;
      value    = Fit->Value(1);
      error    = Fit->FitResult::Error(1); 
      Fit = hist->Fit("gaus",option,"",LowEdge,HighEdge);
      */
    }
    results =  std::pair<double,double>(value,error);
  }
  return results;
}
Esempio n. 3
0
Double_t dpol1Func(const TF1 *fcn, const Double_t x, const TFitResultPtr fs) {
  Double_t df[2];
  Double_t a = fcn->GetParameter(0);
  Double_t b = fcn->GetParameter(1);
  
  df[0] = 1;
  df[1] = x;
  Double_t err2 = df[0]*df[0]*(fs->GetCovarianceMatrix()[0][0])
                  + df[1]*df[1]*(fs->GetCovarianceMatrix()[1][1])
		  + 2.0*df[0]*df[1]*(fs->GetCovarianceMatrix()[0][1]);
  assert(err2>=0);
  return sqrt(err2);
}
Esempio n. 4
0
void CalibTree::fitPol0(TH1D* hist, bool debug) {

  hist->GetXaxis()->SetTitle("i#eta");
  hist->GetYaxis()->SetTitle("<E_{HCAL}/(p-E_{ECAL})>");
  hist->GetYaxis()->SetRangeUser(0.4,1.6);
  TFitResultPtr Fit = hist->Fit("pol0","+QRWLS");
  if (debug) {
    std::cout << "Fit to Pol0 to " << hist->GetTitle() << ": " 
	      << Fit->Value(0) << " +- " << Fit->FitResult::Error(0)
	      << std::endl;
  }
  hist->Write();
}
Esempio n. 5
0
TGraphErrors* ExtractCalCurve(vector<calData>& FitPositions, vector<Float_t>& Energies)
//void ExtractCalCurve(vector<Float_t>& FitPositions, vector<Float_t>& Energies)
{
    //TF1* calFit = new TF1("calFit","[0]*x + [1]",0,800E3);
    TGraphErrors* calCurve = new TGraphErrors(Energies.size());
    
    //Get highest energy peak and estimate [0]
    std::vector<calData>::iterator pit;
    std::vector<Float_t>::iterator eit;
    
    pit = max_element(FitPositions.begin(),FitPositions.end(),CompareByadc);
    eit = max_element(Energies.begin(),Energies.end());
    
    //Extrapolate coefficient and place first point
    int currPoint = 1;
    calCurve->SetPoint(currPoint,(*pit).fadc,*eit);
    calCurve->SetPointError(currPoint,(*pit).efadc,0.0);
    TFitResultPtr r = calCurve->Fit("pol1","SQ");   
    Float_t a = r->Parameter(1);

    Float_t CurrentPeak = 0.0;
    Float_t CurrentEnergy = 0.0;
    Float_t CurrentEnergyEst = 0.0;
    // Loop through found peaks and locate closest estimated energy
    // Assume fitted peaks are already ordered from lowest to highest
    for(std::vector<calData>::iterator i = --(FitPositions.end()); i!=FitPositions.begin(); --i)
    {
        currPoint++;
        CurrentPeak = (*i).fadc;
        CurrentEnergyEst = CurrentPeak*a;
        Float_t CurrentDelta = 800E3;
        for(std::vector<Float_t>::iterator j = Energies.begin(); j!=Energies.end(); j++)
	{
		if( abs(*j - CurrentEnergyEst) < CurrentDelta)
		{
			CurrentDelta = abs(*j - CurrentEnergyEst);
                        CurrentEnergy = *j;
		}
	} 
	
	calCurve->SetPoint(currPoint,CurrentPeak,CurrentEnergy);
        calCurve->SetPointError(currPoint,(*i).efadc,CurrentDelta);
        r = calCurve->Fit("pol1","SQ");
        a = r->Parameter(1);
    }
    r->Print("V");
    return calCurve; 
}
Esempio n. 6
0
Double_t dsqrtFunc(const TF1 *fcn, const Double_t x, const TFitResultPtr fs) {
  Double_t df[2];
  Double_t a = fcn->GetParameter(0);
  Double_t b = fcn->GetParameter(1);

  TF1 *deriv_par0 = new TF1("dfdp0",df_dParsqrt,130,1620,3);
  deriv_par0->SetParameters(0,a,b); // This will set the derivative for the first parameter.
  TF1 *deriv_par1 = new TF1("dfdp1",df_dParsqrt,130,1620,3);
  deriv_par1->SetParameters(1,a,b); // This will set the derivative for the second parameter
  df[0] = deriv_par0->Eval(x);
  df[1] = deriv_par1->Eval(x);
  Double_t err2 = df[0]*df[0]*(fs->GetCovarianceMatrix()[0][0])
                  + df[1]*df[1]*(fs->GetCovarianceMatrix()[1][1])
		  + 2.0*df[0]*df[1]*(fs->GetCovarianceMatrix()[0][1]);
  assert(err2>=0);
  return sqrt(err2);
}
Esempio n. 7
0
void PlotERes(string FilterSet){


  stringstream name;
  name<<FilterSet<<"_vsEnergy";

  
  TH2F* thePlot = (TH2F*)gDirectory->Get(name.str().c_str());

  if (thePlot==NULL){
    cout<<"No plot"<<endl;
    return;
  }

  int numYBins = thePlot->GetNbinsY();

  TF1 * myFunc = new TF1("myFunc","gaus",-0.3,0.3);
  

  double * x = (double*)malloc(numYBins*sizeof(double));
  double * y = (double*)malloc(numYBins*sizeof(double));
  double * ey = (double*)malloc(numYBins*sizeof(double));
  
  for (int i=0;i<numYBins;i++){
    


    TH1D* proj=thePlot->ProjectionX("_px",i,numYBins-1);
    if (proj->GetEntries()>40){
      TFitResultPtr result = proj->Fit("myFunc","RQS");
      Int_t status = result;
      if (status==0){
	cout<<result->Value(2)*2.35*4<<endl;
	x[i]=i;
	y[i]=result->Value(2)*2.35*4;
	ey[i]=result->UpperError(2)*2.35*4;
      }
    }
  }
  
  
  TGraphErrors * graph = new TGraphErrors(numYBins,x,y,0,ey);
  graph->GetHistogram()->SetMarkerStyle(5);
  graph->Draw("AP");
}
Esempio n. 8
0
File: hw.C Progetto: geonmo/HepClass
hw()
{
    Float_t data;
    TFile *f=new TFile("data.root");
    TTree* tree = f->Get("mytree");
    TBranch* branch = tree->GetBranch("data");
    branch->SetAddress(&data);

    TH1F* h1 = new TH1F("h1","h1",200,0.0,5.0);
    for(Int_t i= 0 ; i< tree->GetEntries() ; i++) {
	tree->GetEntry(i);
        h1->Fill( data) ;
    }
       
    TF1 *f2 = new TF1("f2", "[0]*x+[1]+gaus(2)", 0.0, 5.0);
    f2->SetParameter(3,3.7);

    TVirtualFitter *min = TVirtualFitter::Fitter(0,2);
    TVirtualFitter::SetDefaultFitter("Minuit");

    TFitResultPtr fitresult = h1->Fit("f2", "MES");
    cout<< "Parameter 0" << fitresult->Parameter(0) << "+-" << fitresult->ParError(0) << endl;
    cout<<  "Parameter 1" <<fitresult->Parameter(1) << "+-" << fitresult->ParError(1) << endl;
    cout << "Chi2 " << fitresult->Chi2() << endl;
    cout << "NDF " << fitresult->Ndf() << endl;
    cout << "Chi2 probability " << fitresult->Prob() << endl;
    TMatrixD covmat(fitresult->GetCovarianceMatrix());
    cout << "Covariance matrix" << endl;
    covmat.Print();
    TCanvas *c1 = new TCanvas("c1", "binned line fit", 600, 600);
    c1->Draw();
    h1->Draw();


}
Esempio n. 9
0
TH1F*	makehist( string id, int ndf )
{
	int	hits_count = ndf + 2;
	TString	hist_name, cut, title;
	hist_name += id;
	hist_name += "_chisq_";
	hist_name += hits_count;
	hist_name += "hits";
	cut += id;
	cut += "_hits_count == ";
	cut += hits_count;
	float	min_x = 0;
	float	max_x = (ndf == 2) ? 2.0 : 0.5;
	TH1F	*hist = new TH1F(hist_name.Data(), cut, 1000, min_x, max_x);
	events->Draw(Form("%s_chisq >> %s", id.c_str(), hist_name.Data()), cut);
	if (hits_count > 3)
	{
		TF1 *func = new TF1("func", "[0]*exp([1]*x)+[2]");
		TFitResultPtr fit = hist->Fit(func, "SQ", "", 0.0, 0.5); // S - return fit result, Q - quiet
		std::cout << hist_name << "\tslope: " << fit->Parameter(1) << "\tadd const: " << fit->Parameter(2) << std::endl;
	}
	if (id[1] == '3')
	{
		title += "Left ";
	}
	else
	{
		title += "Right ";
	}
	title += id[2];
	title += " (";
	title += cut;
	title += ")";
	hist->SetTitle(title);
	hist->SetLabelSize(0.04, "X");
	hist->SetLabelSize(0.04, "Y");
	hist->SetTitleSize(0.05, "X");
	hist->SetTitleSize(0.05, "Y");
	hist->SetTitleOffset(0.9, "X");
	hist->SetTitleOffset(1.1, "Y");
	hist->GetXaxis()->SetTitle("#chi^2, [mm]");
	hist->GetYaxis()->SetTitle("N");

	return hist;
}
Esempio n. 10
0
	double FitConfidence::choleskyUncertainty( double xx, TFitResultPtr fitResult, TF1 * f, int nSamples ){
		int nP = f->GetNpar();

		TMatrixDSym cov = fitResult->GetCovarianceMatrix();
		double *covArray = new double[ nP * nP ]; // number of parameters x number of parameters
		covArray = cov.GetMatrixArray();

		return choleskyUncertainty( xx, covArray, f, nSamples );
	}
Esempio n. 11
0
void estimateEfficiencyAndPurity(TH1* fraction,double cut,double& efficiency, double& purity, double& efferror, double& purerror, TFitResultPtr fitRes) {
  // efficiency loss is defined as the estimated signal below the cut over the estimated total signal
  double rangeLow, rangeHigh;
  TF1* expo = fraction->GetFunction("expo");
  expo->GetRange(rangeLow, rangeHigh);

  double signalLoss         = expo->Integral(0,cut)/fraction->GetBinWidth(1);
  double signalLossError = expo->IntegralError(0,cut,fitRes->GetParams(),fitRes->GetCovarianceMatrix().GetMatrixArray())/fraction->GetBinWidth(1);
  
  double signal_expopart         = expo->Integral(cut,fraction->GetBinLowEdge(fraction->FindBin(rangeHigh)+1))/fraction->GetBinWidth(1);
  double signal_expopartError = expo->IntegralError(cut, fraction->GetBinLowEdge(fraction->FindBin(rangeHigh)+1),fitRes->GetParams(),fitRes->GetCovarianceMatrix().GetMatrixArray())/fraction->GetBinWidth(1);

  double signal_toppoart = fraction->Integral(fraction->FindBin(rangeHigh)+1,fraction->FindBin(1.)+1);
  
  efficiency = (signal_expopart+signal_toppoart)/(signal_expopart+signal_toppoart+signalLoss);
  efferror = TMath::Sqrt( pow(signalLoss,2)*pow(signal_expopartError,2) + pow(signal_toppoart+signal_expopart,2)*pow(signalLossError,2) )/pow(signal_expopart+signal_toppoart+signalLoss,2);
  
  // purity is defined as the signal above the cut (signal_expopart+signal_toppoart) 
  // over the total data above that cut
  
  double data_kept = fraction->Integral(fraction->FindBin(cut),fraction->FindBin(1.)+1);
  double allBeforeRangeHigh = fraction->Integral(fraction->FindBin(cut),fraction->FindBin(rangeHigh));
  purity = (signal_expopart+signal_toppoart)/data_kept;
  purerror = signal_expopartError/data_kept; 
 
  if(purity > 1.){
    std::cout << "#################################################"<<std::endl;
    std::cout << "cut: "<<cut<<" purity:" << purity <<std::endl;
    std::cout << "signalLoss: " << signalLoss << " signalExtrapolated: " << signal_expopart << " signalTop: " << signal_toppoart << std::endl;
    std::cout << "all b.r.h.: " << allBeforeRangeHigh << std::endl;
    std::cout << "total signal with expo: "<< (signal_expopart+signal_toppoart)<< std::endl;
    std::cout << "total signal integrating: "<< (allBeforeRangeHigh+signal_toppoart)<< std::endl;
    std::cout << "data kept:  " << data_kept  << std::endl;
    std::cout << "ratio:      " << allBeforeRangeHigh/signal_expopart << std::endl;
    std::cout << "#################################################"<<std::endl;
  }
 
  //   std::cout << "estimateEfficiencyAndPurity for cut=" << cut << std::endl;
  //   std::cout << "signal: " << signalLoss << " " << signal_expopart << " " << signal_toppoart << std::endl;
  //   std::cout << "data kept: " << data_kept << std::endl;
  //   std::cout << "eff: " << efficiency << "+/- " << efferror << " pur: " << purity << " +/- " << purerror << std::endl;
}
Esempio n. 12
0
Double_t dpol2Func(const TF1 *fcn, const Double_t x, const TFitResultPtr fs) {
  Double_t df[3];
  Double_t a = fcn->GetParameter(0);
  Double_t b = fcn->GetParameter(1);
  Double_t c = fcn->GetParameter(2);
  
  df[0] = 1;
  df[1] = x;
  df[2] = x*x;
  
  Double_t err2=0;
  for(Int_t i=0; i<3; i++) {
    err2 += df[i]*df[i]*(fs->GetCovarianceMatrix()[i][i]);
    for(Int_t j=i+1; j<3; j++) {
      err2 += 2.0*df[i]*df[j]*(fs->GetCovarianceMatrix()[i][j]);
    }
  }

  assert(err2>=0);
  return sqrt(err2);
}
Esempio n. 13
0
TH1F*	make_drift_efficiency_hist(char arm, char axis, TTree *events)
{
	if ((arm != 'l') && (arm != 'r'))
	{
		throw "make_drift_efficiency_hist: Invalid arm value";
	}
	if ((axis != 'X') && (axis != 'Y'))
	{
		throw "make_drift_efficiency_hist: Invalid axis value";
	}
	char arm_chamber = (arm == 'l') ? '3' : '4';
	int canvas_cell = 1 + (int)(arm == 'l') + 2 * (int)(axis == 'X');

	TH2F *four_hit_theta_x = new TH2F(
		Form("%c%c_four_hit_theta_x", arm, axis), "",
		ANGLE_BINS, 0, ANGLE_MAX,
		X_BINS, X_MIN, X_MAX
		);
	four_hit_theta_x->SetOption("zcol");
	TH2F *any_theta_x = new TH2F(
		Form("%c%c_any_theta_x", arm, axis), "",
		ANGLE_BINS, 0, ANGLE_MAX,
		X_BINS, X_MIN, X_MAX
		);
	any_theta_x->SetOption("zcol");

	TH1F *four_hit_theta = new TH1F(
		Form("%c%c_four_hit_theta", arm, axis), "",
		ANGLE_BINS, 0, ANGLE_MAX
		);
	TH1F *any_theta = new TH1F(
		Form("%c%c_any_theta", arm, axis), "",
		ANGLE_BINS, 0, ANGLE_MAX
		);

	c1.cd();
	TH2F	*beam_profile = new TH2F("beam_profile", ";Z, [mm];Y, [mm]", 100, -20, 20, 100, -20, 20);
	beam_profile->SetOption("zcol");
	events->Draw("RL_y:RL_z >> beam_profile", "", "ZCOL");
	TF2	*xygaus = new TF2("xygaus", "xygaus");
	TFitResultPtr fit = beam_profile->Fit(xygaus, "S"); // S - return fit result 
	const double *params = fit->GetParams();
	if (!params)
	{
		throw "Error determining beam profile parameters.";
	}
	const char	*cut = Form(
		"(abs(RL_z - (%f)) < %f) && "
		"(abs(RL_y - (%f)) < %f) && "
		"(RL_x < %f) && "
		"(RL_x > %f) && "
		"(abs(LR_z - (%f)) < %f) && "
		"(abs(LR_y - (%f)) < %f) && "
		"(LR_x < %f) && "
		"(LR_x > %f)",
		params[1], params[2] * 2,
		params[3], params[4] * 2,
		X_MAX, X_MIN,
		params[1], params[2] * 2,
		params[3], params[4] * 2,
		X_MAX, X_MIN
		);

	c2.cd(canvas_cell);
	events->Draw(
		Form("RL_x:theta_%c >> %s", arm, any_theta_x->GetName()),
		cut
		);
	events->Draw(
		Form("RL_x:theta_%c >> %s", arm, four_hit_theta_x->GetName()),
		Form("(t%c%c_hits_count[0] == 4) && %s", arm_chamber, axis, cut)
		);
	TH2F *u_tx = new TH2F(
		Form("%c%c_efficiency_theta_x", arm, axis), "",
		ANGLE_BINS, 0, ANGLE_MAX,
		X_BINS, X_MIN, X_MAX
		);
	u_tx->Divide(four_hit_theta_x, any_theta_x);
	u_tx->GetXaxis()->SetTitle("\\Theta, rad");
	u_tx->GetYaxis()->SetTitle("X coordinate on target, mm");
	u_tx->SetOption("zcol");
	u_tx->Draw("zcol");

	c3.cd(canvas_cell);
	events->Draw(
		Form("theta_%c >> %s", arm, any_theta->GetName()),
		cut
		);
	events->Draw(
		Form("theta_%c >> %s", arm, four_hit_theta->GetName()),
		Form("(t%c%c_hits_count[0] == 4) && %s", arm_chamber, axis, cut)
		);
	TH1F *u_t = new TH1F(
		Form("%c%c_efficiency_theta", arm, axis), "",
		ANGLE_BINS, 0, ANGLE_MAX
		);
	u_t->Divide(four_hit_theta, any_theta);
	u_t->GetXaxis()->SetTitle("\\Theta, rad");
	u_t->GetYaxis()->SetTitle("Efficiency, 1");
	u_t->GetYaxis()->SetRangeUser(0.0, 1.0);
	u_t->Draw();

	return u_t;
}
Esempio n. 14
0
int main(int argc, char** argv)
{
  //Check if all nedeed arguments to parse are there
  if( argc < 2 )
  {
    std::cerr << ">>> linearityPlots_MZ::usage: " << argv[0] << " evtsPerPoint_cat0 (evtsPerPoint_cat1 evtsPerPoint_cat2 ...)" << std::endl;
    return -1;
  }
  
  int nCat = argc - 1;
  int* evtsPerPoint = new int[nCat];
  for(int iCat = 0; iCat < nCat; ++iCat)
    evtsPerPoint[iCat] = atoi(argv[iCat+1]);
  
  
  std::vector<std::string> directories;
  if(drawSmearSys == false && drawScaleSys == false)    
    directories.push_back( ("data/2012/Winter2013/MZ_"+analysis+"_nonGlobe_powheg-runDependent_phoTunedRegV5_Dphi3p15").c_str() );
  if(drawSmearSys == true || drawScaleSys == true)  
    directories.push_back( ("data/2012/Winter2013/MZ_"+analysis+"_nonGlobe_powheg-runDependent_phoTunedRegV5_Dphi3p15_std").c_str() );
  if(drawSmearSys == true){
    directories.push_back(("data/2012/Winter2013/MZ_"+analysis+"_nonGlobe_powheg-runDependent_phoTunedRegV5_Dphi3p15_smearPlus1").c_str());
    directories.push_back(("data/2012/Winter2013/MZ_"+analysis+"_nonGlobe_powheg-runDependent_phoTunedRegV5_Dphi3p15_smearMinus1").c_str());
  }
  if(drawScaleSys == true){
    directories.push_back(("data/2012/Winter2013/MZ_"+analysis+"_nonGlobe_powheg-runDependent_phoTunedRegV5_Dphi3p15_scalePlus1").c_str());
    directories.push_back(("data/2012/Winter2013/MZ_"+analysis+"_nonGlobe_powheg-runDependent_phoTunedRegV5_Dphi3p15_scaleMinus1").c_str());
  }
  //directories.push_back( "data/2012/Winter2013/MZ_CiC_nonGlobe_powheg-runDependent_phoTunedRegV5_Dphi3p15_10m4_BinErrsOK_P0" );
  //directories.push_back( "data/2012/Winter2013/MZ_CiC_nonGlobe_powheg-runDependent_phoTunedRegV5_Dphi3p15_10m4_BinErrsOK_EXP" );
  unsigned int nDir = directories.size();
  std::cout << " >>>>>>>>>> nDir = " << nDir << std::endl;
  float PointY[nCat][4];
  float PointX[nCat][4];
  float PointYE[nCat][4];
  float PointXE[nCat][4];

  
  float SysError[nCat][7];
  SysError[0][0] = 0.00380885;
  SysError[0][1] = -0.0366029;
  SysError[0][2] = -0.179775;
  SysError[0][3] = -0.289;
  SysError[0][4] = 0.0616593;
  SysError[0][5] = -0.00157475;
  SysError[0][6] = -0.00207482;

  SysError[1][0] = -0.0228756;
  SysError[1][1] = 0.00991204;
  SysError[1][2] = -0.196126;
  SysError[1][3] = -0.489761;
  SysError[1][4] = 0.0772905;
  SysError[1][5] = 0.016216;
  SysError[1][6] = -0.0143245;

  SysError[2][0] = -0.674561;
  SysError[2][1] = -1.22921;
  SysError[2][2] = -0.553516;
  SysError[2][3] = -0.392232;
  SysError[2][4] = 0.135323;
  SysError[2][5] = -0.0389127;
  SysError[2][6] = -0.0323834; 

  SysError[3][0] = -0.931675;
  SysError[3][1] = -1.20162;
  SysError[3][2] = -0.576185;
  SysError[3][3] = -0.456856;
  SysError[3][4] = 0.182718;
  SysError[3][5] = -0.016453;
  SysError[3][6] = -0.00577606; 
  
  //-----------------------------
  // Decide which methods to draw
  
  std::vector<std::string> methods;
  //methods.push_back( "fit" );
  //methods.push_back( "gausFit" );
  //methods.push_back( "mean" );
  methods.push_back( "recursiveMean" );
  //  methods.push_back( "smallestInterval" );
  int nMethods = methods.size();
  
  std::vector<std::string> nameTrial;
  nameTrial.push_back("std");
  if(drawSmearSys == true){
    nameTrial.push_back("smearPlus1");
    nameTrial.push_back("smearMinus1");
  }
  if(drawScaleSys == true){
    nameTrial.push_back("scalePlus1");
    nameTrial.push_back("scaleMinus1");
  }

  //--------------------
  // Set fitting options
  
  TVirtualFitter::SetDefaultFitter("Minuit2");
  
  setTDRStyle();
  gStyle->SetPadTopMargin(0.05);
  gStyle->SetPadBottomMargin(0.13);
  gStyle->SetPadLeftMargin(0.13);
  gStyle->SetPadRightMargin(0.17);
  gStyle->SetLabelSize(0.04,"XYZ");
  gStyle->SetTitleSize(0.05,"XYZ");
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  
  std::vector<int> colors;
  std::vector<int> linestyles;
  std::vector<int> markerstyles;
  colors.push_back(kRed+1);
  colors.push_back(kOrange+1);
  colors.push_back(kGreen+1);
  colors.push_back(kBlue+1);
  linestyles.push_back(1);
  linestyles.push_back(2);
  linestyles.push_back(2);
  markerstyles.push_back(20);
  markerstyles.push_back(26);
  markerstyles.push_back(32);
  
  
  
  //----------------
  // Define canvases
  
  TCanvas* c_all = new TCanvas("c_all","c_all");
  c_all -> Divide(2,2);
  
  TCanvas** c = new TCanvas*[nCat];
  
  
  
  //----------------------------
  // Define infiles and canvases
  for(unsigned int iDir = 0; iDir < directories.size(); ++iDir)
  {
    std::string directory = directories.at(iDir);
    std::string* inFileNames = new std::string[nCat];
    
    std::string baseFileName = "studyLinearity_MZ_";
    if( MCClosure == true) directory += "_MCClosure"+MCSyst;
    
    for(int iMeth = 0; iMeth < nMethods; ++iMeth)
    {
      std::cout << ">>> method: " << methods.at(iMeth) << std::endl;
      
      TLegend** legend = new TLegend*[nCat];
      for(int iCat = 0; iCat < nCat; ++iCat)
      {
        legend[iCat] = new TLegend(0.16, 0.77, 0.30, 0.92);
        legend[iCat] -> SetFillColor(kWhite);
        legend[iCat] -> SetFillStyle(1001);  
        legend[iCat] -> SetTextFont(42);  
        legend[iCat] -> SetTextSize(0.05);
      }
      
      TLatex* latex = new TLatex(0.14,0.96,Form("analysis: %s   scale estimator: %s",analysis.c_str(),(methods.at(iMeth)).c_str()));
      latex -> SetNDC();
      latex -> SetTextFont(42);
      latex -> SetTextSize(0.04);
      
      double* scale_MZ = new double[nCat];
      
      TGraphAsymmErrors** g = new TGraphAsymmErrors*[nCat];
      TGraphAsymmErrors** gClone = new TGraphAsymmErrors*[nCat];
      
      TF1** f_fit = new TF1*[nCat];
      TH1F** hint = new TH1F*[nCat];
      
      
      for(int iCat = 0; iCat < nCat; ++iCat)
      {
        std::cout << "\n***************** cat: " << iCat << " *****************" << std::endl;
        
        char EvtString[50];
        sprintf(EvtString,"cat%d_%devtsPerPoint",iCat,evtsPerPoint[iCat]);
        
        inFileNames[iCat] = directory + "/" + baseFileName + std::string(EvtString) + ".root";
        TFile* f = TFile::Open((inFileNames[iCat]).c_str(),"READ");
        std::cout << ">>> inFileName: " << inFileNames[iCat] << std::endl;
        
        char graphName[50];
        sprintf(graphName,"step1/scale_%s_DAOverMC",methods.at(iMeth).c_str());
        g[iCat] = (TGraphAsymmErrors*)( f->Get(graphName) );
        gClone[iCat] = (TGraphAsymmErrors*)( f->Get(graphName) );
        
	if(addSyst == true){
	  for(int point = 0; point < g[iCat]->GetN(); ++point){
	    double ey = g[iCat] -> GetErrorY(point);
	    double statE2 = pow(ey,2);
	    double sysE2 = pow(0.01*SysError[iCat][point], 2);
  	    g[iCat] -> SetPointEYhigh(point, sqrt(statE2 + sysE2) );
  	    g[iCat] -> SetPointEYlow (point, sqrt(statE2 + sysE2) );
	  }
	}
 	if(writeFunctions == true && rescaleErrors == true){
	  
	  gClone[iCat]->RemovePoint(7);
	  gClone[iCat]->RemovePoint(6);
	  gClone[iCat]->RemovePoint(5);
	  gClone[iCat]->RemovePoint(4);
	  
	  /*
	  g[iCat]->RemovePoint(7);  
	  g[iCat]->RemovePoint(6);  
	  g[iCat]->RemovePoint(5);  
	  g[iCat]->RemovePoint(4);  
	  */
 	}
	TF1* f_scaleVsEt = (TF1*)( f->Get("f_scaleVsEt") );

        if( iDir == 0 ) c[iCat] = new TCanvas();
        c[iCat] -> cd();
        c[iCat] -> SetGridx();
        c[iCat] -> SetGridy();
        //c[iCat] -> SetLogx();
        
        c_all -> cd(iCat+1);
        gPad -> SetGridx();
        gPad -> SetGridy();
        
        g[iCat] -> SetPoint(g[iCat]->GetN(),1500.,1.);
        g[iCat] -> GetXaxis() -> SetRangeUser(60,200.);        
        g[iCat] -> GetXaxis() -> SetMoreLogLabels();
        g[iCat] -> GetXaxis() -> SetTitle("H_{T} [GeV]");
        g[iCat] -> GetYaxis() -> SetTitle("#LTm_{ee}#GT^{data} / #LTm_{ee}#GT^{MC}");
        g[iCat] -> GetXaxis() -> SetTitleSize(0.05);
        g[iCat] -> GetYaxis() -> SetTitleSize(0.05);
        g[iCat] -> GetXaxis() -> SetTitleOffset(1.10);
        g[iCat] -> GetYaxis() -> SetTitleOffset(1.28);
        g[iCat] -> GetXaxis() -> SetLabelSize(0.04);
        g[iCat] -> GetYaxis() -> SetLabelSize(0.04);
        g[iCat] -> GetYaxis() -> SetNdivisions(405);
        g[iCat] -> SetMarkerSize(1.5);
        g[iCat] -> SetMarkerColor(colors.at(iCat));
        g[iCat] -> SetMarkerStyle(markerstyles.at(iDir));
        g[iCat] -> SetLineColor(kBlack);
        g[iCat] -> SetLineWidth(1);
        
	if(iCat == 0 || iCat == 1){
	  g[iCat] -> SetMinimum(0.9951);
	  g[iCat] -> SetMaximum(1.0049);
	}
	else{
	  g[iCat] -> SetMinimum(0.985);
	  g[iCat] -> SetMaximum(1.015);
	}
	if(MCClosure == true){ 
	  g[iCat] -> SetMinimum(0.98);
	  g[iCat] -> SetMaximum(1.02);
        }
        if( drawFitFunc == false )
        {
          if( iDir == 0 )
          {
            c[iCat] -> cd();
            g[iCat] -> Draw("AP");
            c_all -> cd(iCat+1);
            g[iCat] -> Draw("AP"); 
          }
          else
          {
            c[iCat] -> cd();
            g[iCat] -> Draw("P,same");
            c_all -> cd(iCat+1);
            g[iCat] -> Draw("P,same");
          }
	 
          if(MCClosure && drawFitFunc == false)
          {
//             TF1* f_scaleVsEt = new TF1("f_scaleVsEt", "1. + [0] * (1 - exp(-[1] * (0.5*x-45.)) )",0., 1000.);
//             f_scaleVsEt -> SetParameters(7.50e-03,2.00e-02);
	    //TF1* f_scaleVsEt = new TF1("f_scaleVsEt", "1.+0.000",0., 1000.);
            f_scaleVsEt->SetLineColor(kBlack);
            c[iCat] -> cd();
            f_scaleVsEt->Draw("same");
            c_all -> cd(iCat+1);
            f_scaleVsEt->Draw("same");
          }
        }
        else
        {
          if( iDir == 0 )
          {
            c[iCat] -> cd();
            g[iCat] -> Draw("AP");
            c_all -> cd(iCat+1);
            g[iCat] -> Draw("AP");
	  }
          else
          {
            c[iCat] -> cd();
            g[iCat] -> Draw("P,same");
            c_all -> cd(iCat+1);
            g[iCat] -> Draw("P,same");
	  }
        }
        
        char funcName[150];
        sprintf(funcName,"f_prefit_%s_%d",methods.at(iMeth).c_str(),iCat);
        TF1* f_prefit;
        if( fitMethod == "pol0")
        {
          f_prefit = new TF1(funcName,"[0]",55., 230.);
          f_prefit -> SetParameter(0,1.);         
        }
        if( fitMethod == "pol1")
        {
          f_prefit = new TF1(funcName,"[0]+[1]*(x-90.)",55., 210.);
          f_prefit -> SetParameters(1.,0.00002);         
        }
        if( fitMethod == "exp3par")
        {
          f_prefit = new TF1(funcName,"1.+[0]*(1.-exp(-1.*[1]*(x-90.)))+[2]",55., 230.);
          f_prefit -> SetParameters(0.005,0.02,0.);
        }
        if( fitMethod == "exp")
        {
	  f_prefit = new TF1(funcName,"1.+[0]*(1.-exp(-1.*[1]*(x-90.)) )",55., 230.);
          f_prefit -> SetParameters(0.005,0.02);
          f_prefit -> SetParLimits(0,0.,1.);
          f_prefit -> SetParLimits(1,0.,0.05);
        }
        
        TFitResultPtr fitResult1;
        int fitStatus1 = -1;
	gClone[iCat] -> Fit(funcName,"QRHNS");
        //g[iCat] -> Fit(funcName,"QRHNS");
        fitStatus1 = fitResult1;
        
        //std::cout << " fitStatus1 = " << fitStatus1 << std::endl;
        //std::cout << " f_prefit->GetParameter(0) = " << f_prefit->GetParameter(0) << std::endl;
        //std::cout << " f_prefit->GetParameter(1) = " << f_prefit->GetParameter(1) << std::endl;
        std::cout << " f_prefit->GetChisquare()/f_prefit->GetNDF() = " << f_prefit->GetChisquare()/f_prefit->GetNDF() << std::endl;
        
        if( drawFitFunc == true && rescaleErrors == true )
        {
          for(int point = 0; point < g[iCat]->GetN(); ++point)
          {
  	    double ey = g[iCat] -> GetErrorY(point);
	    if(addSyst == false){
	      g[iCat] -> SetPointEYhigh(point,ey*sqrt(f_prefit->GetChisquare()/f_prefit->GetNDF()));
	      g[iCat] -> SetPointEYlow (point,ey*sqrt(f_prefit->GetChisquare()/f_prefit->GetNDF()));
	  
	      if(point == 4 || point == 5 || point == 6 || point == 7){
		g[iCat] -> SetPointEYhigh(point, sqrt(pow(g[iCat] -> GetErrorY(point),2)+pow(0.0005,2)) );
		g[iCat] -> SetPointEYlow(point, sqrt(pow(g[iCat] -> GetErrorY(point),2)+pow(0.0005,2)) );
		}
	  
	    }
	    //std::cout << " >>>  prima ey = " << ey  << std::endl;

	    if(SysError[iCat][point] != 0. && addSyst == true){
	      double statE2 = (pow(ey,2) - pow(0.01*SysError[iCat][point], 2));
	      //double statE2 = pow(ey,2);
	      double sysE2 = pow(SysError[iCat][point], 2);
	      //double sysE2 = pow(SysError[iCat][point], 2);
	      
 	      double errorN2 =  ( (statE2) * (f_prefit->GetChisquare()/f_prefit->GetNDF()) / sysE2 - statE2/sysE2 + 
				  0.01*(f_prefit->GetChisquare()/f_prefit->GetNDF()) );
// 	      // 	      double errorN2 =  (statE2 + sysE2) * f_prefit->GetChisquare()/f_prefit->GetNDF() / sysE2 - statE2/sysE2;
// 	      //	      double errorN2 =  num2/ (f_prefit->GetChisquare()/f_prefit->GetNDF()) / sysE2 - statE2/sysE2;


  	      g[iCat] -> SetPointEYhigh(point, sqrt( statE2 + errorN2*sysE2) );
  	      g[iCat] -> SetPointEYlow (point, sqrt( statE2 + errorN2*sysE2) );

// 	      g[iCat] -> SetPointEYhigh(point, sqrt( statE2 + sysE2) );
//  	      g[iCat] -> SetPointEYlow (point, sqrt( statE2 + sysE2) );
 	      std::cout << " >>>  dopo ey = " << sqrt(statE2 + sysE2) << std::endl;

	    }
	      /*
	      double statE2 = (pow(ey,2) - pow(0.0001*SysError[iCat][point], 2));
	      double errorN2 = ( (pow(ey,2) * f_prefit->GetChisquare()/f_prefit->GetNDF() - statE2 ) /
				 (pow(0.0001*SysError[iCat][point], 2)) );
	      if(iCat == 0){
	      g[iCat] -> SetPointEYhigh(point, sqrt( statE2 + pow(0.0015*SysError[iCat][point], 2)) );
	      g[iCat] -> SetPointEYlow (point, sqrt( statE2 + pow(0.0015*SysError[iCat][point], 2)) );
	      }
	      if(iCat == 1){
	      g[iCat] -> SetPointEYhigh(point, sqrt( statE2 + pow(0.015*SysError[iCat][point], 2)) );
	      g[iCat] -> SetPointEYlow (point, sqrt( statE2 + pow(0.015*SysError[iCat][point], 2)) );
	      }
	      if(iCat == 2){
	      g[iCat] -> SetPointEYhigh(point, sqrt( statE2 + pow(0.003*SysError[iCat][point], 2)) );
	      g[iCat] -> SetPointEYlow (point, sqrt( statE2 + pow(0.003*SysError[iCat][point], 2)) );
	      }
	      if(iCat == 3){
	      g[iCat] -> SetPointEYhigh(point, sqrt( statE2 + pow(0.005*SysError[iCat][point], 2)) );
	      g[iCat] -> SetPointEYlow (point, sqrt( statE2 + pow(0.005*SysError[iCat][point], 2)) );
	      }
	      */
// 	      std::cout << " >>>  cat >> " << iCat << " point = " << point << " k = " << errorN2 * sqrt(0.0001) << std::endl;
// 	      std::cout << " >>>  cat >> " << iCat << " point = " << point << " stat = " << sqrt(statE2) << std::endl;
//	  }
	  }
        }
        if( drawFitFunc == false && rescaleErrors == true )      
        {
          if( MCClosure == true )
          {
 	    for(int point = 0; point < g[iCat]->GetN(); ++point)
            {
              double ey = g[iCat] -> GetErrorY(point);
	      if(addSyst == false){
		g[iCat] -> SetPointEYhigh(point,ey*sqrt(f_prefit->GetChisquare()/f_prefit->GetNDF()));
		g[iCat] -> SetPointEYlow (point,ey*sqrt(f_prefit->GetChisquare()/f_prefit->GetNDF()));
	      }
	      if(SysError[iCat][point] != 0. && addSyst == true){
		double statE2 = (pow(ey,2) - pow(0.0001*SysError[iCat][point], 2));
		double sysE2 = pow(0.0001*SysError[iCat][point], 2);
		double errorN2 =  (statE2 + sysE2) * f_prefit->GetChisquare()/f_prefit->GetNDF() / sysE2 - statE2/sysE2;
		
		g[iCat] -> SetPointEYhigh(point, sqrt( statE2 + errorN2*sysE2) );
		g[iCat] -> SetPointEYlow (point, sqrt( statE2 + errorN2*sysE2) );
	      }
	    }
          }
        }
	////////////////

	int fitStatus1b = -1;
        g[iCat] -> Fit(funcName,"QRHNS");
	fitStatus1b = fitResult1;
	std::cout << " f_prefit->GetChisquare()/f_prefit->GetNDF() = " << f_prefit->GetChisquare()/f_prefit->GetNDF() << std::endl;

	if( rescaleErrors == true )
	  {
	    for(int point = 0; point < g[iCat]->GetN(); ++point)
	      {
		double ey = g[iCat] -> GetErrorY(point);
		if(addSyst == false){
		  g[iCat] -> SetPointEYhigh(point,ey*sqrt(f_prefit->GetChisquare()/f_prefit->GetNDF()));
		  g[iCat] -> SetPointEYlow (point,ey*sqrt(f_prefit->GetChisquare()/f_prefit->GetNDF()));
		}
	      }
	  }

	////////////
        
        
        sprintf(funcName,"f_fit_%s_%d",methods.at(iMeth).c_str(),iCat);
        if( fitMethod == "pol0")
        {
          f_fit[iCat] = new TF1(funcName,"[0]",55., 230.);
          f_fit[iCat] -> SetParameter(0,1.);         
        }
        if( fitMethod == "pol1" )
        {
	  f_fit[iCat] = new TF1(funcName,"[0]+[1]*(x-90.)",55., 230.);
          f_fit[iCat] -> SetParameters(1.,0.00001);
        }
        if( fitMethod == "exp3par")
        {
          f_fit[iCat] = new TF1(funcName,"1.+[0]*(1.-exp(-1.*[1]*(x-90.)))+[2]",55., 230.);
          f_fit[iCat] -> SetParameters(0.005,0.02,0.);
        }
        if( fitMethod == "exp")
        {
          f_fit[iCat] = new TF1(funcName,"1.+[0]*(1.-exp(-1.*[1]*(x-90.)))",55., 230.);
          f_fit[iCat] -> SetParameters(0.005,0.02);
        }
        f_fit[iCat] -> SetLineColor(kBlue+2);
        f_fit[iCat] -> SetLineWidth(3);
        f_fit[iCat] -> SetLineStyle(linestyles.at(iDir));
        
        TFitResultPtr fitResult;
        int fitStatus = -1;
        int nTrials = 0;
        while( (fitStatus != 0) && (nTrials < 10) )
        {
          fitResult = g[iCat] -> Fit(funcName,"QRHNS");
          fitStatus = fitResult;
          if( fitStatus == 1 ) break;
          ++nTrials;
        }
        std::cout << " >>>> fitStatus = " << fitStatus << std::endl;
        std::cout << " >>>> nTrials = " << nTrials << std::endl;
        if( fitStatus == 0 && MCClosure == false )
        {
          TMatrixDSym cov = fitResult->GetCovarianceMatrix();
          TMatrixDSym cor = fitResult->GetCorrelationMatrix();
          for(int aa=0; aa<f_fit[iCat]->GetNpar(); ++aa){
	    for(int bb=0; bb<f_fit[iCat]->GetNpar(); ++bb){
	    std::cout << " (corMatrix[" << aa << "])[" << bb << "] = " << cor[aa][bb] << "; " << std::endl;
            }
          }
        }
	//	g[iCat]->AddPoint(0);

        std::cout << " f_fit[iCat]->GetChisquare()/f_fit[iCat]->GetNDF() = " << f_fit[iCat]->GetChisquare()/f_fit[iCat]->GetNDF() << std::endl;
        
        if( drawFitFunc == true )
        {
          hint[iCat] = new TH1F("hint","",5000,55.,1055.);
          (TVirtualFitter::GetFitter()) -> GetConfidenceIntervals(hint[iCat],0.68);
          hint[iCat] -> SetMarkerSize(0);
          hint[iCat] -> SetFillColor(kAzure-9);
          hint[iCat] -> SetFillStyle(3001);
          c[iCat] -> cd();
          f_fit[iCat] -> Draw("same");
          if( iDir == 0 )
          {
            hint[iCat] -> Draw("same,E4");
            f_fit[iCat] -> Draw("same");
	  }
	  g[iCat]->Draw("P,same");
          c_all -> cd(iCat+1);
          f_fit[iCat] -> Draw("same");
          if( iDir == 0 )
          {
            hint[iCat] -> Draw("same,E4");
            f_fit[iCat] -> Draw("same");
	  }
	  g[iCat]->Draw("P,same");
        }
            
        if( MCClosure == false && writeFunctions == true)
	  {
	    TFile TF1_defaultDiffNonLin((("TF1_pol1_EtScale/TF1_"+fitMethod+"_"+analysis+"_"+nameTrial.at(iDir)+Form("_cat%d.root",iCat))).c_str(), "recreate");
          
	    TF1* defaultDiffNonLinET;
	    TF1* defaultDiffNonLinHT;
	    if(fitMethod == "exp")
	      {
		defaultDiffNonLinET = new TF1(Form("cat%d", iCat), "1.+[0]*(1.-exp(-1.*[1]*(x-45.)))", 20., 1000.);
		defaultDiffNonLinET->SetParameter(0, f_fit[iCat]->GetParameter(0));
		defaultDiffNonLinET->SetParError(0, f_fit[iCat]->GetParError(0));
		defaultDiffNonLinET->SetParameter(1, 2.*f_fit[iCat]->GetParameter(1));
		defaultDiffNonLinET->SetParError(1, 2.*f_fit[iCat]->GetParError(1));
	      }
	    if(fitMethod == "exp3par")
	      {
		defaultDiffNonLinET = new TF1(Form("cat%d", iCat), "1.+[0]*(1.-exp(-1.*[1]*(x-45.)))+[2]", 20., 1000.);
		defaultDiffNonLinET->SetParameter(0, f_fit[iCat]->GetParameter(0));
		defaultDiffNonLinET->SetParError(0, f_fit[iCat]->GetParError(0));
		defaultDiffNonLinET->SetParameter(1, 2.*f_fit[iCat]->GetParameter(1));
		defaultDiffNonLinET->SetParError(1, 2.*f_fit[iCat]->GetParError(1));
		defaultDiffNonLinET->SetParameter(2, f_fit[iCat]->GetParameter(2));
		defaultDiffNonLinET->SetParError(2, f_fit[iCat]->GetParError(2));
	      }
	    if( fitMethod == "pol1" )
	      {
		defaultDiffNonLinET = new TF1(Form("ET_cat%d", iCat), "[0]+ [1] * (x-45.)", 20., 1000.);
		defaultDiffNonLinET->SetParameter(0, f_fit[iCat]->GetParameter(0));
		defaultDiffNonLinET->SetParError(0, f_fit[iCat]->GetParError(0));
		defaultDiffNonLinET->SetParameter(1, 2.*f_fit[iCat]->GetParameter(1));
		defaultDiffNonLinET->SetParError(1, 2.*f_fit[iCat]->GetParError(1));
		
		defaultDiffNonLinHT = new TF1(Form("HT_cat%d", iCat), "[0]+ [1] * (x-90.)", 20., 1000.);
		defaultDiffNonLinHT->SetParameter(0, f_fit[iCat]->GetParameter(0));
		defaultDiffNonLinHT->SetParError(0, f_fit[iCat]->GetParError(0));
		defaultDiffNonLinHT->SetParameter(1, f_fit[iCat]->GetParameter(1));
		defaultDiffNonLinHT->SetParError(1, f_fit[iCat]->GetParError(1));
	      }
	    if( fitMethod == "pol0" )
	      {
		defaultDiffNonLinET = new TF1(Form("ET_cat%d", iCat), "[0]", 20., 1000.);
		defaultDiffNonLinET->SetParameter(0, 0.5*f_fit[iCat]->GetParameter(0));
		defaultDiffNonLinET->SetParError(0, 0.5*f_fit[iCat]->GetParError(0));
		
		defaultDiffNonLinHT = new TF1(Form("HT_cat%d", iCat), "[0]+ [1] * (x-90.)", 20., 1000.);
		defaultDiffNonLinHT->SetParameter(0, f_fit[iCat]->GetParameter(0));
		defaultDiffNonLinHT->SetParError(0, f_fit[iCat]->GetParError(0));
		defaultDiffNonLinHT->SetParameter(1, f_fit[iCat]->GetParameter(1));
		defaultDiffNonLinHT->SetParError(1, f_fit[iCat]->GetParError(1));
	      }
	    
	    defaultDiffNonLinET -> Write();
	    defaultDiffNonLinHT -> Write();
	    TF1_defaultDiffNonLin.Close();
	  }

	std::cout << " CIAOOOOOOOOO " << std::endl;
	std::cout << " iCat =  " << iCat << std::endl;
	std::cout << " iDir =  " << iDir << std::endl;

	if(iCat == 0 && iDir == 1){
 	  TFile perTommaso("perRara.root","recreate"); 
	  // 	  for(int i =0; i<4; ++i){                                         
 	    g[iCat]->Write(Form("graph_cat%d",iCat));                               
	    // 	  }                                                                
 	  perTommaso.Close();        
	} 


        
        legend[iCat] -> AddEntry(g[iCat],Form("cat. %d",iCat),"PL");
        
        
        TH1F* h_Ht_MC = (TH1F*)( f->Get("h_Ht_MC") );
        double HT_Z = h_Ht_MC->GetMean();
        scale_MZ[iCat] = f_fit[iCat] -> Eval(HT_Z);
        
        std::cout << std::fixed << "rel. scale(MZ): "  << std::setprecision(4) << scale_MZ[iCat] << std::endl;
        
        
        c[iCat] -> cd();
        legend[iCat] -> Draw("same");
        latex -> Draw("same");
        c_all -> cd(iCat+1);
        legend[iCat] -> Draw("same");
        latex -> Draw("same");
             
        std::string MCClosureLabel;
        if( MCClosure == true ) MCClosureLabel = "MCClosure_";
        else                    MCClosureLabel = "_";
        
        if( iDir == nDir-1 )
        {
          char pdfName[250];
          sprintf(pdfName,"%s/scale_%s_%s_%s_cat%d_%sDAOverMC.pdf",
                  directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),iCat,MCClosureLabel.c_str());
	  if(drawScaleSys == true) sprintf(pdfName,"%s/scale_%s_%s_%s_cat%d_ScaleSys_%sDAOverMC.pdf",
		  directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),iCat,MCClosureLabel.c_str());
	  if(drawSmearSys == true) sprintf(pdfName,"%s/scale_%s_%s_%s_cat%d_SmearSys_%sDAOverMC.pdf",
		  directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),iCat,MCClosureLabel.c_str());
	  if(MCClosure == true)           sprintf(pdfName,"%s/scale_%s_%s_%s_cat%d_%sDAOverMC.pdf",
                  directory.c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),iCat,MCClosureLabel.c_str());
          std::cout << ">>> saving file " << pdfName << std::endl;
          c[iCat] -> Print(pdfName,"pdf");
          
          char pngName[250];
          sprintf(pngName,"%s/scale_%s_%s_%s_cat%d_%sDAOverMC.png",
                  directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),iCat,MCClosureLabel.c_str());
	  if(drawScaleSys == true) sprintf(pngName,"%s/scale_%s_%s_%s_cat%d_ScaleSys_%sDAOverMC.png",
		  directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),iCat,MCClosureLabel.c_str());
	  if(drawSmearSys == true) sprintf(pngName,"%s/scale_%s_%s_%s_cat%d_SmearSys_%sDAOverMC.png",
		  directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),iCat,MCClosureLabel.c_str());
	  if(MCClosure == true)           sprintf(pngName,"%s/scale_%s_%s_%s_cat%d_%sDAOverMC.png",
                  directory.c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),iCat,MCClosureLabel.c_str());
          std::cout << ">>> saving file " << pngName << std::endl;
          c[iCat] -> Print(pngName,"png");
	  std::cout << " >>> pngName = " << pngName << std::endl;
          
          if( iCat == nCat-1 )
          {
            sprintf(pdfName,"%s/scale_%s_%s_%s_allCat_%sDAOverMC.pdf",
                    directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),MCClosureLabel.c_str());
	    if(drawScaleSys == true) sprintf(pdfName,"%s/scale_%s_%s_%s_allCat_ScaleSys_%sDAOverMC.pdf",
	          directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),MCClosureLabel.c_str());
	    if(drawSmearSys == true) sprintf(pdfName,"%s/scale_%s_%s_%s_allCat_SmearSys_%sDAOverMC.pdf",
		  directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),MCClosureLabel.c_str());
	    if(MCClosure == true)           sprintf(pdfName,"%s/scale_%s_%s_%s_allCat_%sDAOverMC.pdf",
                  directory.c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),MCClosureLabel.c_str());
            std::cout << ">>> saving file " << pdfName << std::endl;
            c_all -> Print(pdfName,"pdf");
            
            sprintf(pngName,"%s/scale_%s_%s_allCat_%sDAOverMC.png",
                    directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),MCClosureLabel.c_str());
	    if(drawScaleSys == true) sprintf(pngName,"%s/scale_%s_%s_%s_allCat_ScaleSys_%sDAOverMC.png",
	          directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),MCClosureLabel.c_str());
	    if(drawSmearSys == true) sprintf(pngName,"%s/scale_%s_%s_%s_allCat_SmearSys_%sDAOverMC.png",
		  directories[0].c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),MCClosureLabel.c_str());
	  if(MCClosure == true)           sprintf(pngName,"%s/scale_%s_%s_%s_allCat_%sDAOverMC.png",
                  directory.c_str(),analysis.c_str(),(methods.at(iMeth)).c_str(),fitMethod.c_str(),MCClosureLabel.c_str());
            std::cout << ">>> saving file " << pngName << std::endl;
            c_all -> Print(pngName,"png"); 
	  std::cout << " >>> All pngName = " << pngName << std::endl;
          }
        }
      }
//       TFile perTommaso("perTommaso_MZdiagonal_EtDep.root","recreate");
//       for(int i =0; i<4; ++i){
// 	g[i]->Write(Form("graph_cat%d",i));
//       }
//       perTommaso.Close();
    }
  }
}  
Esempio n. 15
0
void analyzeInclusivejet(){
	
	float cutEtaJet = 2;
	
	float cutPtJet =100;
	
	
	// Tree variables
	
	//Trigger trigger;
	float jtpt_ic5[1000];
	float jteta_ic5[1000];
	float jtphi_ic5[1000];
	int njets_ic5;
	
	float jtpt_ak3[1000];
	float jteta_ak3[1000];
	float jtphi_ak3[1000];
	int njets_ak3;
	
	int run;
	int evt;
	int bin;
	
	
	const int NBINS=15;
	Double_t BOUNDARIES[NBINS] = {60,65,72,80,90,100,120,140,160,180,200,220,240,280,350};
	
	
	TH1F* hak3pujet_cut = new TH1F("hak3pujet_cut","AK3PU Jet Spectra with cut;p_{T}; # of Events",NBINS-1,BOUNDARIES);
	TH1F* hak3pujet = new TH1F("hak3pujet","AK3PU Jet Spectra;p_{T}; # of Events",NBINS-1,BOUNDARIES);
	hak3pujet_cut->Sumw2();
	hak3pujet->Sumw2();
	
	
	TString inname="merged.root";
	TFile* inf = new TFile(inname,"read");
	
	TTree* ic5t = (TTree*)inf->Get("icPu5JetAnalyzer/t");
	TTree* t = (TTree*)inf->Get("hltanalysis/HltTree");
	
	ic5t->SetBranchAddress("jtpt",jtpt_ic5);
	ic5t->SetBranchAddress("jteta",jteta_ic5);
	ic5t->SetBranchAddress("jtphi",jtphi_ic5);
	ic5t->SetBranchAddress("nref",&njets_ic5);
	
	TTree* ak3t = (TTree*)inf->Get("akPu3PFJetAnalyzer/t");
	
	ak3t->SetBranchAddress("jtpt",jtpt_ak3);
	ak3t->SetBranchAddress("jteta",jteta_ak3);
	ak3t->SetBranchAddress("jtphi",jtphi_ak3);
	ak3t->SetBranchAddress("nref",&njets_ak3);
	
	t->SetBranchAddress("Run",&run);
	t->SetBranchAddress("Event",&evt);
	t->SetBranchAddress("hiBin",&bin);
	
	TString outname = "JetSkimTree.root";
			
	int Nevents = t->GetEntries();
	for(int iev = 0; iev < Nevents; ++iev){
		t->GetEntry(iev);
		ic5t->GetEntry(iev);
		ak3t->GetEntry(iev);
		
		for(int i = 0; i < njets_ak3; ++i){
			//if(jtpt_ak3[i] < cutPtJet) continue;
			if(fabs(jteta_ak3[i]) > cutEtaJet) continue;
			hak3pujet->Fill(jtpt_ak3[i]);
							}//1st for loop
		
		int id=0;
		for(int i = 0; i < njets_ak3; ++i){
			if(fabs(jteta_ic5[i]) < cutEtaJet)
				id =1;
			
		}// 2nd for loop
		if(id == 1){
				for(int i = 0; i < njets_ak3; ++i){
					if(jtpt_ic5[i] < cutPtJet) continue;
					//if(jtpt_ak3[i] < cutPtJet) continue;
					if(fabs(jteta_ak3[i]) > cutEtaJet) continue;
					hak3pujet_cut->Fill(jtpt_ak3[i]);
				}
			
	}// if loop
	}//evt loop
	
	
	TCanvas *c1 = new TCanvas("c1", "",46,477,700,509);
	c1->Range(-125,-11.1492,1125,3.24528);
	c1->SetBorderSize(0);
	c1->SetBorderMode(0);
	c1->SetLeftMargin(0.16);
	c1->SetTopMargin(0.06);
	c1->SetBottomMargin(0.17);
	c1->SetTicks(1,1);
	
	
	
	gROOT->LoadMacro("erf.C");
		
	TGraphAsymmErrors *dividedthingy= new TGraphAsymmErrors;
	dividedthingy->BayesDivide(hak3pujet_cut,hak3pujet);
	
	
	float xstart=20.0;
	float xend=300.0;
	
	
	TF1 *fitfcn = new TF1("fitfcn",erf,xstart,xend,2); //<============
	fitfcn->SetParameter(0,40); //<============= 
	TFitResultPtr results =dividedthingy->Fit("fitfcn","VSR");
	
	cout << "Chi2: " << results->Chi2() << " / " << results->Ndf() << " NDF" << endl;
	
	float turnon=fitfcn->GetX(0.99,10,300);
	cout << "99% at: " << turnon << endl;
	char turnontext[50]="";
	sprintf(turnontext," ak5pu at %4.1f",turnon);
	
	
	
	dividedthingy->GetFunction("fitfcn")->SetLineColor(3);
	dividedthingy->SetLineColor(1);
	dividedthingy->Draw("Ap");
	
	
	
	TText *t2 = new TText(95,0.08,turnontext);
	t2->SetTextSize(0.055);
	t2->SetTextColor(1);
	t2->Draw();
		
		
	
}
Esempio n. 16
0
bool FitPeak(Double_t *par, TH1 *h, Float_t &area, Float_t &darea){

   Double_t binWidth = h->GetXaxis()->GetBinWidth(1000);//Need to find the bin widths so that the integral makes sense
   Int_t rw = binWidth*20;  //This number may change depending on the source used   
   //Set the number of iterations. The code is pretty quick, so having a lot isn't an issue	
   TVirtualFitter::SetMaxIterations(4999);
   Int_t xp = par[1];

   //Define the fit function and the range of the fit
   TF1 *pp = new TF1("photopeak",fitFunction,xp-rw,xp+rw,10);

   //Name the parameters so it is easy to see what the code is doing
   pp->SetParName(0,"Height");
   pp->SetParName(1,"centroid");
   pp->SetParName(2,"sigma");
   pp->SetParName(3,"beta");
   pp->SetParName(4,"R");
   pp->SetParName(5,"step");
   pp->SetParName(6,"A");
   pp->SetParName(7,"B");
   pp->SetParName(8,"C");
   pp->SetParName(9,"bg offset");

   //Set some physical limits for parameters
   pp->SetParLimits(1,xp-rw,xp+rw);
   pp->SetParLimits(3,0,30);
   pp->SetParLimits(4,0,10);
   pp->SetParLimits(5,0.000,1000000);
   pp->SetParLimits(9,xp-20,xp+20);

   //Actually set the parameters in the photopeak function
   pp->SetParameters(par);

//   pp->FixParameter(4,0);
 //  pp->FixParameter(5,0);

   pp->SetNpx(1000); //Draws a nice smooth function on the graph
   TFitResultPtr fitres = h->Fit("photopeak","RFS");
   pp->Draw("same");      

   pp->GetParameters(&par[0]); 
   TF1 *photopeak = new TF1("photopeak",photo_peak,xp-rw,xp+rw,10);
   photopeak->SetParameters(par);

   Double_t integral = photopeak->Integral(xp-rw,xp+rw)/binWidth;

   std::cout << "FIT RESULT CHI2 " << fitres->Chi2() << std::endl;

   std::cout << "FWHM = " << 2.35482*fitres->Parameter(2)/binWidth <<"(" << fitres->ParError(2)/binWidth << ")" << std::endl;
   std::cout << "NDF: " << fitres->Ndf() << std::endl;
   std::cout << "X sq./v = " << fitres->Chi2()/fitres->Ndf() << std::endl;

   TVirtualFitter *fitter = TVirtualFitter::GetFitter();

   assert(fitter != 0); //make sure something was actually fit
   Double_t * covMatrix = fitres->GetCovarianceMatrix(); //This allows us to find the uncertainty in the integral

   Double_t sigma_integral = photopeak->IntegralError(xp-rw,xp+rw)/binWidth;

   std::cout << "Integral = " << integral << " +/- " << sigma_integral << std::endl;

   area = integral;
   darea = sigma_integral;

   if(fitres->Chi2()/fitres->Ndf() > 5.0)
      return false;

   return true;

//   myFitResult.fIntegral = integral;


 //  return photopeak;

}
Esempio n. 17
0
void bToDRawYield()
{
	gStyle->SetTextSize(0.05);
	gStyle->SetTextFont(42);
	gStyle->SetPadRightMargin(0.04);
	gStyle->SetPadLeftMargin(0.14);
	gStyle->SetPadTopMargin(0.1);
	gStyle->SetPadBottomMargin(0.14);
	gStyle->SetTitleX(.0f);
	gStyle->SetOptFit(1111);
	gStyle->SetOptStat(0);
	gStyle->SetOptTitle(0);

	TCanvas* c4 = new TCanvas("c4","",800,600);
	c4->Divide(2,2);

	TCanvas* c2 = new TCanvas("c2","",400,600);
	c2->Divide(1,2);

	TCanvas* c1 = new TCanvas();

	TCanvas* c15 = new TCanvas("c15","",810,1000);
	c15->Divide(3,5);

	TFile* fPbPb = new TFile("bFeedDownPbPb.hist.root");
	TFile* fPbPbMB = new TFile("bFeedDownPbPbMB.hist.root");
	TFile* fPbPbMC = new TFile("bFeedDownPbPbMC.hist.root");
	TFile* fPbPbMBMC = new TFile("bFeedDownPbPbMBMC.hist.root");

	TH3D* hDataPbPb = (TH3D*)fPbPb->Get("hData");
	TH3D* hSidebandPbPb = (TH3D*)fPbPb->Get("hSideband");
	TH3D* hDataPbPbMB = (TH3D*)fPbPbMB->Get("hData");
	TH3D* hSidebandPbPbMB = (TH3D*)fPbPbMB->Get("hSideband");
	TH3D* hPtMD0DcaPbPb = (TH3D*)fPbPb->Get("hPtMD0Dca");
	TH3D* hPtMD0DcaPbPbMB = (TH3D*)fPbPbMB->Get("hPtMD0Dca");

	TH3D* hMCPSignalPbPb = (TH3D*)fPbPbMC->Get("hMCPSignal");
	TH3D* hMCNPSignalPbPb = (TH3D*)fPbPbMC->Get("hMCNPSignal");
	TH3D* hMCPSignalPbPbMB = (TH3D*)fPbPbMBMC->Get("hMCPSignal");
	TH3D* hMCNPSignalPbPbMB = (TH3D*)fPbPbMBMC->Get("hMCNPSignal");
	TH3D* hPtMD0DcaMCPSignalPbPb = (TH3D*)fPbPbMC->Get("hPtMD0DcaMCPSignal");
	TH3D* hPtMD0DcaMCPSwappedPbPb = (TH3D*)fPbPbMC->Get("hPtMD0DcaMCPSwapped");
	TH3D* hPtMD0DcaMCPSignalPbPbMB =(TH3D*)fPbPbMBMC->Get("hPtMD0DcaMCPSignal");
	TH3D* hPtMD0DcaMCPSwappedPbPbMB = (TH3D*)fPbPbMBMC->Get("hPtMD0DcaMCPSwapped");

	TH3D* hData = (TH3D*)hDataPbPb->Clone("hData");
	hData->Sumw2();
	hData->Add(hDataPbPbMB);

	TH3D* hSideband = (TH3D*)hSidebandPbPb->Clone("hSideband");
	hSideband->Sumw2();
	hSideband->Add(hSidebandPbPbMB);

	TH3D* hPtMD0Dca = (TH3D*)hPtMD0DcaPbPb->Clone("hPtMD0Dca");
	hPtMD0Dca->Sumw2();
	hPtMD0Dca->Add(hPtMD0DcaPbPbMB);

	TH3D* hMCPSignal = (TH3D*)hMCPSignalPbPb->Clone("hMCPSignal");
	hMCPSignal->Sumw2();
	hMCPSignal->Add(hMCPSignalPbPbMB);

	TH3D* hMCNPSignal = (TH3D*)hMCNPSignalPbPb->Clone("hMCNPSignal");
	hMCNPSignal->Sumw2();
	hMCNPSignal->Add(hMCNPSignalPbPbMB);

	TH3D* hPtMD0DcaMCPSignal = (TH3D*)hPtMD0DcaMCPSignalPbPb->Clone("hPtMD0DcaMCPSignal");
	hPtMD0DcaMCPSignal->Sumw2();
	hPtMD0DcaMCPSignal->Add(hPtMD0DcaMCPSignalPbPbMB);

	TH3D* hPtMD0DcaMCPSwapped =(TH3D*)hPtMD0DcaMCPSwappedPbPb->Clone("hPtMD0DcaMCPSwapped");
	hPtMD0DcaMCPSwapped->Sumw2();
	hPtMD0DcaMCPSwapped->Add(hPtMD0DcaMCPSwappedPbPbMB);

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

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

	const int nPtBins = 14;
	float ptBins[nPtBins+1] = {2.,3.,4.,5.,6.,8.,10.,12.5,15.0,20.,25.,30.,40.,60.,100};

	float pts[nPtBins];
	float ptErrors[nPtBins];
	float promptFraction[nPtBins];
	float totalYield[nPtBins];
	float totalYieldInvMassFit[nPtBins];
	float totalYieldInvMassFitError[nPtBins];
	float bToDYield[nPtBins];
	float bToDYieldError[nPtBins];
	float bToDYieldErrorDataOnly[nPtBins];
	float promptDYield[nPtBins];
	float promptDYieldError[nPtBins];
	float promptDYieldErrorDataOnly[nPtBins];

	const int nBinY = 14;
	Float_t binsY[nBinY+1];
	float firstBinYWidth = 0.001;
	float binYWidthRatio = 1.27;
	binsY[0]=0;
	for(int i=1; i<=nBinY; i++)
		binsY[i] = binsY[i-1]+firstBinYWidth*pow(binYWidthRatio,i-1);
	cout<<"last y bin: "<<binsY[nBinY]<<endl;

	//  for(int i=1; i<=nPtBins; i++)
	for(int i =7; i<=7; i++)
	{
		pts[i-1] = 0.5*(ptBins[i-1]+ptBins[i]);
		ptErrors[i-1] = 0.5*(ptBins[i]-ptBins[i-1]);
		float ptLow = ptBins[i-1];
		float ptHigh = ptBins[i];
		cout<<endl<<"======================================="<<endl;
		cout<<"pT range: "<<ptLow<<" "<<ptHigh<<endl;

		TLatex* texPtY = new TLatex(0.32,0.82,Form("%.1f < p_{T} < %.1f GeV/c      |y| < 1.0",ptLow,ptHigh));
		texPtY->SetNDC();
		texPtY->SetTextFont(42);
		texPtY->SetTextSize(0.06);
		texPtY->SetLineWidth(2);

		TLatex* texPt = new TLatex(0.18,0.82,Form("%.1f < p_{T} < %.1f GeV/c",ptLow,ptHigh));
		texPt->SetNDC();
		texPt->SetTextFont(42);
		texPt->SetTextSize(0.06);
		texPt->SetLineWidth(2);

		TLatex* texY = new TLatex(0.18,0.74,Form("|y| < 1.0"));
		texY->SetNDC();
		texY->SetTextFont(42);
		texY->SetTextSize(0.06);
		texY->SetLineWidth(2);

		c2->cd(1);

		hPtMD0Dca->GetZaxis()->SetRange(1,100);
		hPtMD0Dca->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hPtMD0DcaMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hPtMD0DcaMCPSwapped->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		TH1D* hMData = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_%1.1f_%1.1f", ptLow, ptHigh));
		TH1D* hMMCSignal = (TH1D*)hPtMD0DcaMCPSignal->Project3D("y");
		TH1D* hMMCSwapped = (TH1D*)hPtMD0DcaMCPSwapped->Project3D("y");

		setColorTitleLabel(hMData);
		setColorTitleLabel(hMMCSignal);
		setColorTitleLabel(hMMCSwapped);

		TF1* fMass = fitMass(hMData, hMMCSignal, hMMCSwapped);

		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		TF1* fSignalAndSwapped = new TF1("fSignalAndSwapped","[0]*([3]*([5]*Gaus(x,[1],[2]*(1+[7]))/(sqrt(2*3.1415927)*[2]*(1+[7]))+(1-[5])*Gaus(x,[1],[6]*(1+[7]))/(sqrt(2*3.1415927)*[6]*(1+[7])))+(1-[3])*Gaus(x,[1],[4]*(1+[7]))/(sqrt(2*3.1415927)*[4]*(1+[7])))", 1.7, 2.0);      
		fSignalAndSwapped->SetParameter(0,fMass->GetParameter(0));
		fSignalAndSwapped->SetParameter(1,fMass->GetParameter(1));
		fSignalAndSwapped->SetParameter(2,fMass->GetParameter(2));
		fSignalAndSwapped->SetParameter(3,fMass->GetParameter(7));
		fSignalAndSwapped->SetParameter(4,fMass->GetParameter(8));
		fSignalAndSwapped->SetParameter(5,fMass->GetParameter(9));
		fSignalAndSwapped->SetParameter(6,fMass->GetParameter(10));
		fSignalAndSwapped->SetParameter(7,fMass->GetParameter(11));

		TF1* background = new TF1("fBackground","[0]+[1]*x+[2]*x*x+[3]*x*x*x");
		background->SetParameter(0,fMass->GetParameter(3));
		background->SetParameter(1,fMass->GetParameter(4));
		background->SetParameter(2,fMass->GetParameter(5));
		background->SetParameter(3,fMass->GetParameter(6));

		cout<<"MC signal width: "<<fMass->GetParameter(2)<<"   "<<fMass->GetParameter(10)<<endl;
		cout<<"MC swapped width: "<<fMass->GetParameter(8)<<endl;

		float massD = 1.8649;
		float massSignal1 = massD-0.025;
		float massSignal2 = massD+0.025;
		float massSideBand1 = massD-0.1;
		float massSideBand2 = massD-0.075;
		float massSideBand3 = massD+0.075;
		float massSideBand4 = massD+0.1;

		float scaleSideBandBackground = background->Integral(massSignal1, massSignal2)/(background->Integral(massSideBand1, massSideBand2)+background->Integral(massSideBand3, massSideBand4));
		cout<<"scaleSideBandBackground: "<<scaleSideBandBackground<<endl;
		totalYieldInvMassFit[i-1] = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
		totalYieldInvMassFitError[i-1] = fMass->GetParError(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
		cout<<"totalYieldInvMassFit: "<<totalYieldInvMassFit[i-1]<<" +- "<<totalYieldInvMassFitError[i-1]<<endl;
		float scaleSideBandMethodSignal = fSignalAndSwapped->GetParameter(0)*fSignalAndSwapped->GetParameter(3) / (fSignalAndSwapped->Integral(massSignal1, massSignal2)-fSignalAndSwapped->Integral(massSideBand1, massSideBand2)-fSignalAndSwapped->Integral(massSideBand3, massSideBand4));
		cout<<"scaleSideBandMethodSignal: "<<scaleSideBandMethodSignal<<endl;

		TLatex* texScale = new TLatex(0.18,0.66,Form("side band bg scale: %1.3f", scaleSideBandBackground));
		texScale->SetNDC();
		texScale->SetTextFont(42);
		texScale->SetTextSize(0.06);
		texScale->SetLineWidth(2);
		texScale->Draw();

		TLine* lineSignal1 = new TLine(massSignal1, 0, massSignal1, hMData->GetMaximum()*0.5);
		TLine* lineSignal2 = new TLine(massSignal2, 0, massSignal2, hMData->GetMaximum()*0.5);
		TLine* lineSideBand1 = new TLine(massSideBand1, 0, massSideBand1, hMData->GetMaximum()*0.5);
		TLine* lineSideBand2 = new TLine(massSideBand2, 0, massSideBand2, hMData->GetMaximum()*0.5);
		TLine* lineSideBand3 = new TLine(massSideBand3, 0, massSideBand3, hMData->GetMaximum()*0.5);
		TLine* lineSideBand4 = new TLine(massSideBand4, 0, massSideBand4, hMData->GetMaximum()*0.5);
		lineSignal1->Draw();
		lineSignal2->Draw();
		lineSideBand1->Draw();
		lineSideBand2->Draw();
		lineSideBand3->Draw();
		lineSideBand4->Draw();

		c2->cd(2);
		gPad->SetLogy();

		hData->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hSideband->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hMCNPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);

		TH1D* hD0DcaData0 = (TH1D*)hData->Project3D("y")->Clone("hD0DcaData0");
		TH1D* hD0DcaSideband = (TH1D*)hSideband->Project3D("y")->Clone("hD0DcaSideband");
		TH1D* hD0DcaMCPSignal0 = (TH1D*)hMCPSignal->Project3D("y")->Clone("hD0DcaMCPSignal0");
		TH1D* hD0DcaMCNPSignal0 = (TH1D*)hMCNPSignal->Project3D("y")->Clone("hD0DcaMCNPSignal0");

		float integralRawYieldMCP = hD0DcaMCPSignal0->Integral();
		float integralRawYieldMCNP = hD0DcaMCNPSignal0->Integral();
		cout<<"integralRawYieldMCP: "<<integralRawYieldMCP<<endl;
		cout<<"integralRawYieldMCNP: "<<integralRawYieldMCNP<<endl;

		hD0DcaMCPSignal = hD0DcaMCPSignal0;
		hD0DcaMCNPSignal = hD0DcaMCNPSignal0;

		divideBinWidth(hD0DcaData0);
		divideBinWidth(hD0DcaSideband);
		setColorTitleLabel(hD0DcaData0, 1);
		hD0DcaData0->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaData0->GetYaxis()->SetTitle("counts per cm");

		TH1D* hD0DcaSideband0 = (TH1D*)hD0DcaSideband->Clone("hD0DcaSideband0");
		hD0DcaSideband->Scale(scaleSideBandBackground);

		TH1D* hD0DcaDataSubSideBand = (TH1D*)hD0DcaData0->Clone("hD0DcaDataSubSideBand");
		hD0DcaDataSubSideBand->Add(hD0DcaSideband,-1);
		hD0DcaDataSubSideBand->Scale(scaleSideBandMethodSignal);

		hD0DcaData0->SetMarkerSize(0.6);
		hD0DcaData0->Draw();
		hD0DcaSideband->Draw("hsame");
		hD0DcaSideband0->SetLineStyle(2);
		hD0DcaSideband0->Draw("hsame");

		TLegend* leg1 = new TLegend(0.44,0.6,0.90,0.76,NULL,"brNDC");
		leg1->SetBorderSize(0);
		leg1->SetTextSize(0.06);
		leg1->SetTextFont(42);
		leg1->SetFillStyle(0);
		leg1->AddEntry(hD0DcaData0,"D^{0} candidate","pl");
		leg1->AddEntry(hD0DcaSideband,"side band","l");
		leg1->AddEntry(hD0DcaSideband0,"side band unscaled","l");
		leg1->Draw("same");

		texCms->Draw();
		texCol->Draw();
		texPtY->Draw();

		c2->SaveAs(Form("plots/PbPb_%.0f_%.0f_sideBand.pdf",ptLow,ptHigh));

		c2->cd(1);
		hMMCSignal->Draw();
		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		c2->cd(2);
		gPad->SetLogy(0);
		hMMCSwapped->Draw();
		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		c2->SaveAs(Form("plots/PbPb_%.0f_%.0f_McInvMassFit.pdf",ptLow,ptHigh));

		c15->cd(1);

		fitMass(hMData, hMMCSignal, hMMCSwapped);

		texPt->Draw();
		texY->Draw();

		TH1D* hD0DcaDataFit = new TH1D("hD0DcaDataFit", ";D^{0} DCA (cm);dN / d(D^{0} DCA) (cm^{-1})", nBinY, binsY);

		for(int j=1; j<=14; j++)
		{
			c15->cd(j+1);
			hPtMD0Dca->GetZaxis()->SetRange(j,j);
			float D0DcaLow = hPtMD0Dca->GetZaxis()->GetBinLowEdge(j);
			float D0DcaHigh = hPtMD0Dca->GetZaxis()->GetBinUpEdge(j);
			TH1D* hMData_D0Dca = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_pt_%1.1f_%1.1f_D0Dca_%1.4f_%1.4f", ptLow, ptHigh, D0DcaLow, D0DcaHigh));
			setColorTitleLabel(hMData_D0Dca);
			fMass = fitMass(hMData_D0Dca, hMMCSignal, hMMCSwapped);

			float yield = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);
			float yieldError = fMass->GetParError(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);

			hD0DcaDataFit->SetBinContent(j, yield);
			hD0DcaDataFit->SetBinError(j, yieldError);

			TLatex* texD0Dca = new TLatex(0.18,0.82,Form("D^{0} DCA: %1.4f - %1.4f",D0DcaLow,D0DcaHigh));
			texD0Dca->SetNDC();
			texD0Dca->SetTextFont(42);
			texD0Dca->SetTextSize(0.06);
			texD0Dca->SetLineWidth(2);
			texD0Dca->Draw();

			TLatex* texYield = new TLatex(0.18,0.74,Form("D^{0} yield: %1.0f #pm %1.0f",yield,yieldError));
			texYield->SetNDC();
			texYield->SetTextFont(42);
			texYield->SetTextSize(0.06);
			texYield->SetLineWidth(2);
			texYield->Draw();
		}

		c15->SaveAs(Form("plots/PbPb_%.0f_%.0f_invMassFit.pdf",ptLow,ptHigh));

		divideBinWidth(hD0DcaDataFit);

		c4->cd(1);
		gPad->SetLogy();

		normalize(hD0DcaMCPSignal);
		setColorTitleLabel(hD0DcaMCPSignal, 2);
		hD0DcaMCPSignal->GetXaxis()->SetRangeUser(0,0.07);

		normalize(hD0DcaMCNPSignal);
		setColorTitleLabel(hD0DcaMCNPSignal, 4);
		hD0DcaMCNPSignal->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaMCNPSignal->GetYaxis()->SetTitle("dN / d(D^{0} DCA) (cm^{-1})");
		hD0DcaMCNPSignal->GetXaxis()->SetTitle("D^{0} DCA (cm)");
		hD0DcaMCNPSignal->SetMaximum(hD0DcaMCPSignal->GetMaximum()*3.);

		hD0DcaMCNPSignal->Draw("");
		hD0DcaMCPSignal->Draw("same");

		TLegend* leg2 = new TLegend(0.54,0.72,0.90,0.88,NULL,"brNDC");
		leg2->SetBorderSize(0);
		leg2->SetTextSize(0.06);
		leg2->SetTextFont(42);
		leg2->SetFillStyle(0);
		leg2->AddEntry(hD0DcaMCPSignal,"MC Prompt D^{0}","pl");
		leg2->AddEntry(hD0DcaMCNPSignal,"MC Non-prompt D^{0}","pl");
		leg2->Draw("same");

		c4->cd(2);
		gPad->SetLogy();

		TH1D* hD0DcaData = hD0DcaDataFit;
		if(pts[i-1]>20) hD0DcaData = hD0DcaDataSubSideBand;

		setColorTitleLabel(hD0DcaData, 1);

		double integralTotalYield = hD0DcaData->Integral(1,hD0DcaData->GetXaxis()->GetNbins(),"width");
		cout<<"integralTotalYield: "<<integralTotalYield<<endl;

		TF1* fMix = new TF1("fMix",&funMix, 0., 0.5, 2);
		fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
		fMix->SetParLimits(0,0,2*integralTotalYield);
		fMix->SetParLimits(1,0,2*integralTotalYield);

		fMix->SetLineColor(2);
		fMix->SetFillColor(kRed-9);
		fMix->SetFillStyle(1001);

		float fitRangeL = 0;
		float fitRangeH = 0.08;

		hD0DcaData->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaData->Draw();
		int fitStatus = 1;
		TFitResultPtr fitResult;
		double fitPrecision = 1.e-6;
		while(fitStatus)
		{
			TFitter::SetPrecision(fitPrecision);
			fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
			fMix->SetParError(0,0.1*integralTotalYield);
			fMix->SetParError(1,0.1*integralTotalYield);
			fitResult = hD0DcaData->Fit("fMix","E SNQ0", "", fitRangeL, fitRangeH);
			fitStatus = fitResult->Status();
			cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;
			if(fitStatus)
				fitPrecision *= 10;
		}
		cout<<"============== do main fit ============"<<endl;
		fMix->SetParameters(integralTotalYield,0.9);
		fMix->SetParError(0,0.1*integralTotalYield);
		fMix->SetParError(1,0.1);
		fMix->SetNpx(10000);
		fitResult = hD0DcaData->Fit("fMix","E S0", "", fitRangeL, fitRangeH);
		hD0DcaData->GetFunction("fMix")->Draw("flsame");
		fitStatus = fitResult->Status();
		cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;

		TF1* fNP = new TF1("fNP",&funNonPrompt, 0., 0.5, 2);
		fNP->SetParameters(fMix->GetParameter(0),fMix->GetParameter(1));
		fNP->SetRange(fitRangeL,fitRangeH);
		fNP->SetLineColor(4);
		fNP->SetFillStyle(1001);
		fNP->SetFillColor(kBlue-9);
		fNP->SetNpx(10000);
		fNP->Draw("same");  

		hD0DcaData->Draw("same");

		promptDYield[i-1] = fMix->GetParameter(0);
		promptDYieldErrorDataOnly[i-1] = fMix->GetParError(0);
		bToDYield[i-1] = fMix->GetParameter(1);
		bToDYieldErrorDataOnly[i-1] = fMix->GetParError(1);
		totalYield[i-1] = promptDYield[i-1]+bToDYield[i-1];
		promptFraction[i-1] = promptDYield[i-1]/totalYield[i-1];

		cout<<"chi2 / NDF: "<<fitResult->Chi2()<<" / "<<fitResult->Ndf()<<endl;

		texCms->Draw();
		texCol->Draw();
		texPtY->Draw();

		TLatex* texPrompt = new TLatex(0.4,0.73,Form("Prompt D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(0),fMix->GetParError(0)));
		texPrompt->SetNDC();
		texPrompt->SetTextFont(42);
		texPrompt->SetTextSize(0.06);
		texPrompt->SetLineWidth(2);
		texPrompt->Draw();

		TLatex* texNonPrompt = new TLatex(0.4,0.65,Form("B to D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(1),fMix->GetParError(1)));
		texNonPrompt->SetNDC();
		texNonPrompt->SetTextFont(42);
		texNonPrompt->SetTextSize(0.06);
		texNonPrompt->SetLineWidth(2);
		texNonPrompt->Draw();

		TLegend* leg4 = new TLegend(0.56,0.38,0.90,0.62);
		leg4->SetBorderSize(0);
		leg4->SetTextSize(0.06);
		leg4->SetTextFont(42);
		leg4->SetFillStyle(0);
		leg4->AddEntry(hD0DcaData,"Data","pl");
		leg4->AddEntry(fMix,"Prompt D^{0}","f");
		leg4->AddEntry(fNP,"B to D^{0}","f");
		leg4->Draw("same");

		//smear MC smaple with the error, to simulate the MC statistic error effect.
		c4->cd(3);

		hD0DcaMCPSignal = (TH1D*)hD0DcaMCPSignal0->Clone("hMCPSignal");
		hD0DcaMCNPSignal = (TH1D*)hD0DcaMCNPSignal0->Clone("hMCNPSignal");

		TH1D* hNPYield = new TH1D("hNPYield", ";hNPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
		TH1D* hPYield = new TH1D("hPYield", ";hPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
		setColorTitleLabel(hNPYield, 1);
		setColorTitleLabel(hPYield, 1);

		int nSmear = 1000;

		for(int j=0; j<nSmear; j++)
		{
			RandomSmear(hD0DcaMCPSignal0, hD0DcaMCPSignal);
			RandomSmear(hD0DcaMCNPSignal0, hD0DcaMCNPSignal);
			fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
			fMix->SetParError(0,0.1*integralTotalYield);
			fMix->SetParError(1,0.1*integralTotalYield);

			hD0DcaData->Fit("fMix","E QN0");

			hPYield->Fill(fMix->GetParameter(0));
			hNPYield->Fill(fMix->GetParameter(1));
		}

		hPYield->GetXaxis()->SetTitle("prompt D^{0} yield");
		hPYield->GetYaxis()->SetTitle("counts");
		hPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hPYield->GetMaximum());
		hPYield->SetMarkerStyle(20);
		hPYield->SetStats(0);
		hPYield->Draw("e");
		hPYield->Fit("gaus");

		TLatex* texGaussMeanSigmaP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hPYield->GetFunction("gaus")->GetParameter(1),hPYield->GetFunction("gaus")->GetParameter(2)));
		texGaussMeanSigmaP->SetNDC();
		texGaussMeanSigmaP->SetTextFont(42);
		texGaussMeanSigmaP->SetTextSize(0.06);
		texGaussMeanSigmaP->SetLineWidth(2);
		texGaussMeanSigmaP->Draw();

		float promptYieldErrorMc = hPYield->GetFunction("gaus")->GetParameter(2);
		promptDYieldError[i-1] = sqrt(pow(promptDYieldErrorDataOnly[i-1],2)+pow(promptYieldErrorMc,2));

		c4->cd(4);

		hNPYield->GetXaxis()->SetTitle("B to D^{0} yield");
		hNPYield->GetYaxis()->SetTitle("counts");
		hNPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hNPYield->GetMaximum());
		hNPYield->SetMarkerStyle(20);
		hNPYield->SetStats(0);
		hNPYield->Draw("e");
		hNPYield->Fit("gaus");

		TLatex* texGaussMeanSigmaNP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hNPYield->GetFunction("gaus")->GetParameter(1),hNPYield->GetFunction("gaus")->GetParameter(2)));
		texGaussMeanSigmaNP->SetNDC();
		texGaussMeanSigmaNP->SetTextFont(42);
		texGaussMeanSigmaNP->SetTextSize(0.06);
		texGaussMeanSigmaNP->SetLineWidth(2);
		texGaussMeanSigmaNP->Draw();

		float bToDYieldErrorMc = hNPYield->GetFunction("gaus")->GetParameter(2);
		bToDYieldError[i-1] = sqrt(pow(bToDYieldErrorDataOnly[i-1],2)+pow(bToDYieldErrorMc,2));

		cout<<"prompt D yield: "<<promptDYield[i-1]<<" +- "<<promptDYieldError[i-1]<<" (+- "<<promptDYieldErrorDataOnly[i-1]<<" +- "<<promptYieldErrorMc<<" )"<<endl;
		cout<<"B to D yield: "<<bToDYield[i-1]<<" +- "<<bToDYieldError[i-1]<<" (+- "<<bToDYieldErrorDataOnly[i-1]<<" +- "<<bToDYieldErrorMc<<" )"<<endl;
		cout<<"total yield: "<<totalYield[i-1]<<endl;
		cout<<"prompt fraction: "<<promptFraction[i-1]<<endl;

		float promptMCScale = promptDYield[i-1]/integralRawYieldMCP;
		float nonPromptMCScale = bToDYield[i-1]/integralRawYieldMCNP;

		cout<<"promptMCScale: "<<promptMCScale<<endl;
		cout<<"nonPromptMCScale: "<<nonPromptMCScale<<endl;

		//restore original unsmeared histograms before saving plots
		delete hD0DcaMCPSignal;
		delete hD0DcaMCNPSignal;
		hD0DcaMCPSignal = hD0DcaMCPSignal0;
		hD0DcaMCNPSignal = hD0DcaMCNPSignal0;
		hD0DcaData->Fit("fMix","E QN0");

		c4->SaveAs(Form("plots/PbPb_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

		c1->cd();

		TH1D* hD0DcaDataOverFit = (TH1D*)hD0DcaData->Clone("hD0DcaDataOverFit");
		hD0DcaDataOverFit->Divide(fMix);
		hD0DcaDataOverFit->GetYaxis()->SetTitle("data / fit");
		hD0DcaDataOverFit->GetYaxis()->SetRangeUser(0,5);
		hD0DcaDataOverFit->GetXaxis()->SetRangeUser(0,0.07);
		setColorTitleLabel(hD0DcaDataOverFit, 1);
		hD0DcaDataOverFit->Draw("e");

		TF1* fLine1 = new TF1("fLine1", "1", 0,1);
		fLine1->Draw("same");
		hD0DcaDataOverFit->Draw("esame");

		c1->SaveAs(Form("plots/dataOverFit_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

		delete hD0DcaMCPSignal;
		delete hD0DcaMCNPSignal;

	} // end for i ptbins
	c1->cd();

	TH1D* hStupidJie = new TH1D("hStupidJie", "", 100, 0, 100);
	hStupidJie->GetYaxis()->SetRangeUser(0,1);
	hStupidJie->GetXaxis()->SetTitle("p_{T} (GeV/c)");
	hStupidJie->GetYaxis()->SetTitle("prompt fraction");
	hStupidJie->SetStats(0);
	hStupidJie->Draw();
	TGraph* grFraction = new TGraph(nPtBins, pts, promptFraction);
	grFraction->SetName("grPromptFraction");
	grFraction->SetMarkerStyle(20);
	grFraction->Draw("psame");

	c1->SaveAs("promptFraction.pdf");

	c1->SetLogy();

	TH1D* hBtoDRawYield = new TH1D("hBtoDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(bToDYield[i-1] <= 0) continue;
		hBtoDRawYield->SetBinContent(i, bToDYield[i-1]);
		hBtoDRawYield->SetBinError(i, bToDYieldError[i-1]);
	}
	divideBinWidth(hBtoDRawYield);
	setColorTitleLabel(hBtoDRawYield, 1);
	c1->SetBottomMargin(0.14);
	hBtoDRawYield->Draw("p");
	c1->SaveAs("BtoD.pdf");

	TH1D* hPromptDRawYield = new TH1D("hPromptDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(promptDYield[i-1] <= 0) continue;
		hPromptDRawYield->SetBinContent(i, promptDYield[i-1]);
		hPromptDRawYield->SetBinError(i, promptDYieldError[i-1]);
	}
	divideBinWidth(hPromptDRawYield);
	setColorTitleLabel(hPromptDRawYield, 1);
	c1->SetBottomMargin(0.14);
	hPromptDRawYield->Draw("p");
	c1->SaveAs("promptD.pdf");

	TH1D* hTotalDYieldInvMassFit = new TH1D("hTotalDYieldInvMassFit", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(totalYieldInvMassFit[i-1] <= 0) continue;
		hTotalDYieldInvMassFit->SetBinContent(i, totalYieldInvMassFit[i-1]);
		hTotalDYieldInvMassFit->SetBinError(i, totalYieldInvMassFitError[i-1]);
	}
	divideBinWidth(hTotalDYieldInvMassFit);
	setColorTitleLabel(hTotalDYieldInvMassFit, 1);
	hTotalDYieldInvMassFit->Draw("p");
	c1->SaveAs("totalDInvMassFit.pdf");

	TFile* fOut = new TFile("bFeedDownResult.root", "recreate");
	fOut->WriteTObject(grFraction);
	fOut->WriteTObject(hBtoDRawYield);
	fOut->WriteTObject(hPromptDRawYield);
	fOut->WriteTObject(hTotalDYieldInvMassFit);
	fOut->Write();
	fOut->Close();
}
Esempio n. 18
0
void makePlots_vdm_ls(double skip = 10.*11246.)
{
  gROOT->ProcessLine(" .L style.cc+");
#ifdef __CINT__
  style();
#endif

  TFile* file = TFile::Open("histos_vdmpp.root");
  TH1D* h_rate = (TH1D*)file->Get((string("pp/h_rate_ls")).c_str());
  h_rate->Scale(1./h_rate->GetBinWidth(1));
  h_rate->SetTitle(";orbitNb;dN/dT_{Orbit}");
  h_rate->GetXaxis()->SetNdivisions(505);
  h_rate->GetYaxis()->SetTitleOffset(h_rate->GetYaxis()->GetTitleOffset()*0.7);

  canFind = new TCanvas;
  canFind->Divide(1,2);

  vector<string> type;
  type.push_back("X");
  type.push_back("Y");

  vector<double> sectionXBegin;
  vector<double> sectionXEnd;
  vector<double> sectionXTruth;
  vector<double> sectionXMean;
  vector<double> sectionXMeanE;
  vector<TGraphErrors*> sectionXChi;

//   sectionXTruth.push_back(100); //0
//   sectionXTruth.push_back(50);  //1
//   sectionXTruth.push_back(0);   //2
//   sectionXTruth.push_back(-50); //3
//   sectionXTruth.push_back(-100);//4
//   sectionXTruth.push_back(-50); //5
//   sectionXTruth.push_back(0);   //6
//   sectionXTruth.push_back(50);  //7
//   sectionXTruth.push_back(100); //8
//   sectionXTruth.push_back(0);   //9

  //sectionXTruth.push_back(-70); //0
  sectionXTruth.push_back(-370);  //1
  sectionXTruth.push_back(-220);   //2
  sectionXTruth.push_back(-70); //3
  sectionXTruth.push_back(80);//4
  sectionXTruth.push_back(230); //5
  sectionXTruth.push_back(80);   //6
  sectionXTruth.push_back(-70);  //7
  sectionXTruth.push_back(-220); //8
  sectionXTruth.push_back(-370);   //9
  canFind->cd(1);
  FindSections(h_rate,sectionXBegin, sectionXEnd, BEGINX,ENDX,3.*11246.,skip);
  //FindSections(h_rate,sectionXBegin, sectionXEnd, 1.932e8,2.025e8,3.*11246.,skip);
#ifdef __CINT__
  CMSText(1,1,1,string("#DeltaX length scale"),"","pp, #sqrt{s}=2.76 TeV");
#endif
  if(sectionXTruth.size() != sectionXBegin.size())
    {
      cerr << "Sections error: not same size. Truth/Found: " << sectionXTruth.size() << " " <<  sectionXBegin.size() << endl;
      //exit(-1);
    }

  vector<double> sectionYBegin;
  vector<double> sectionYEnd;
  vector<double> sectionYTruth;
  vector<double> sectionYMean;
  vector<double> sectionYMeanE;
  vector<TGraphErrors*> sectionYChi;

//   sectionYTruth.push_back(100);
//   sectionYTruth.push_back(50); 
//   sectionYTruth.push_back(0);  
//   sectionYTruth.push_back(-50);
//   sectionYTruth.push_back(-100);
//   sectionYTruth.push_back(-50);
//   sectionYTruth.push_back(0);  
//   sectionYTruth.push_back(50); 
//   sectionYTruth.push_back(100);
//   sectionYTruth.push_back(0);


  //sectionYTruth.push_back(70); //0
  sectionYTruth.push_back(-370);  //1
  sectionYTruth.push_back(-220);   //2
  sectionYTruth.push_back(-70); //3
  sectionYTruth.push_back(80);//4
  sectionYTruth.push_back(230); //5
  sectionYTruth.push_back(80);   //6
  sectionYTruth.push_back(-70);  //7
  sectionYTruth.push_back(-220); //8
  sectionYTruth.push_back(-370);   //9
  canFind->cd(2);
  //FindSections(h_rate,sectionYBegin, sectionYEnd, 2.038e8,2.12e8,3.*11246.,skip);
  FindSections(h_rate,sectionYBegin, sectionYEnd, BEGINY,ENDY,3.*11246.,skip);
#ifdef __CINT__
  CMSText(1,1,1,string("#DeltaY length scale"),"","pp, #sqrt{s}=2.76 TeV");
#endif
  if(sectionYTruth.size() != sectionYBegin.size())
    {
      cerr << "Sections error: not same size. Truth/Found: " << sectionYTruth.size() << " " <<  sectionYBegin.size() << endl;
      //exit(-1);
    }
  


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

  //GENERAL LOOP OVER SECTIONS
  for(int n=0; n<int(type.size()); n++)
    {
      can1->cd(type[n]=="X"?1:2);
      
      vector<double>& sectionBegin      = type[n]=="X"?sectionXBegin:sectionYBegin;
      vector<double>& sectionEnd        = type[n]=="X"?sectionXEnd:sectionYEnd;
      vector<double>& sectionTruth      = type[n]=="X"?sectionXTruth:sectionYTruth;
      vector<double>& sectionMean       = type[n]=="X"?sectionXMean:sectionYMean;
      vector<double>& sectionMeanE      = type[n]=="X"?sectionXMeanE:sectionYMeanE;
      vector<TGraphErrors*>& sectionChi = type[n]=="X"?sectionXChi:sectionYChi;
        
      const int nSec = int(sectionBegin.size());

      sectionMean.resize(nSec);
      sectionMeanE.resize(nSec);

      TH2D* h_length_scale = (TH2D*)file->Get((string("pp/h_length_scale_") + type[n]).c_str());
      //      for(int i= 0; i<h_length_scale->GetNbinsX()+1;i++) cout << h_length_scale->Print
      TGraphErrors* h_truth_fit_up = new TGraphErrors(0);
      TGraphErrors* h_truth_fit_down = new TGraphErrors(0);
      TGraphErrors* h_truth_fit_crosscheck_up = new TGraphErrors(0);
      TGraphErrors* h_truth_fit_crosscheck_down = new TGraphErrors(0);
      ostringstream profiletitle; profiletitle << "truth_fit_" << type[n];
      ostringstream crosschecktitle; crosschecktitle << "truth_fit_crosscheck_" << type[n];
      h_truth_fit_down->SetName(profiletitle.str().c_str());
      h_truth_fit_crosscheck_down->SetName(crosschecktitle.str().c_str());
      profiletitle << "_down";
      crosschecktitle << "_down";
      h_truth_fit_up->SetName(profiletitle.str().c_str());
      h_truth_fit_crosscheck_up->SetName(crosschecktitle.str().c_str());

      vector<TF1*> sectionFunc; sectionFunc.resize(nSec);
      vector<TFitResultPtr> sectionFuncPtr; sectionFuncPtr.resize(nSec);

      ostringstream histotitle; histotitle << ";orbit number; vertex " << type[n] << " position [cm]";
      h_length_scale->SetTitle(histotitle.str().c_str());
      h_length_scale->SetMarkerSize(0.5);
      h_length_scale->GetXaxis()->SetNdivisions(505);
      h_length_scale->GetYaxis()->SetTitleOffset(h_length_scale->GetYaxis()->GetTitleOffset()*0.7);
      if(type[n]=="X")
        h_length_scale->GetXaxis()->SetRangeUser(BEGINX,ENDX);
      else
        h_length_scale->GetXaxis()->SetRangeUser(BEGINY,ENDY);
//       if(type[n]=="X")
//         h_length_scale->GetXaxis()->SetRangeUser(193000000,202000000);
//       else
//         h_length_scale->GetXaxis()->SetRangeUser(203000000,211000000);
//      h_length_scale->GetYaxis()->SetRangeUser(0.00,0.15);
      h_length_scale->Draw("COLZ");

#ifdef __CINT__
      CMSText(1,1,1,string("#Delta")+type[n]+string(" length scale"),"","pp, #sqrt{s}=2.76 TeV");
#endif
      //FIT EACH SECTION
      TCanvas* canFit = new TCanvas;
      canFit->Divide(TMath::Nint(nSec/2.),2);
      for (int i=0; i<nSec; i++)
        {
          int binStartNotSkipped,binStart, binEnd, helper;
          double x1,x2,xend;

          h_length_scale->GetBinXYZ(h_length_scale->FindBin(sectionBegin[i]),binStartNotSkipped,helper,helper); binStartNotSkipped++;
          h_length_scale->GetBinXYZ(h_length_scale->FindBin(sectionBegin[i]+skip),binStart,helper,helper); binStart++;
          h_length_scale->GetBinXYZ(h_length_scale->FindBin(sectionEnd[i]),binEnd,helper,helper); binEnd--;
          x1=h_length_scale->GetBinLowEdge(binStartNotSkipped);
          x2=h_length_scale->GetBinLowEdge(binStart);
          xend=h_length_scale->GetBinLowEdge(binEnd+1);

          if(binStart >= binEnd)
            {
              cerr << "MAJOR WARNING Chosen skipping value too large for section " << i << "(" << binStart << "," << binEnd << ")" << endl;
            }

          ostringstream funcTitle;
          funcTitle << "section" << type[n] << "Func_" << i;
          sectionFunc[i] = new TF1(funcTitle.str().c_str(),"gaus");
          sectionFunc[i]->SetLineWidth(2);
          sectionFunc[i]->SetLineColor(kRed);
          sectionFunc[i]->SetLineStyle(1);

          funcTitle << "_Prof";
          TH1D* helperProfile = h_length_scale->ProjectionY(funcTitle.str().c_str(),binStart,binEnd);
          canFit->cd(i+1);
          helperProfile->Draw();
          sectionFuncPtr[i] = helperProfile->Fit(sectionFunc[i],"QS");


          if(Int_t(sectionFuncPtr[i]) !=0)
            {
              cerr << " !!! MAJOR WARNING." << endl
                   << "in section " << i << " fit did not converge: " << gMinuit->fCstatu.Data() << endl;
            }

          sectionFunc[i]->SetLineWidth(2);
          sectionFunc[i]->Draw("SAME");

          sectionMean[i] = helperProfile->GetMean();
          sectionMeanE[i] = helperProfile->GetMeanError();

          if(x1<x2)
            {
              //can1->cd();
              TBox* box1 = new TBox(x1,0.1,x2,0.105);
              box1->SetFillColor(kRed);
              box1->SetFillStyle(3001);
              box1->DrawClone();
              TBox* box2 = new TBox(x2,0.1,xend,0.105);
              box2->SetFillColor(kGreen);
              box2->SetFillStyle(3001);
              box2->DrawClone();
            }
        }
      
//       //DETERMINE THE MEAN WHERE TRUTH IS AT NOMINAL POSITION -> now done below
//       double xw = 0;
//       double w = 0;
//       for(int i=0; i<nSec; i++)
//         {
//           if(sectionTruth[i]==70 || sectionTruth[i]==-70)
//             {
//               double weight = 1./pow(sectionFuncPtr[i]->ParError(1),2);
//               xw += sectionFuncPtr[i]->Parameter(1) * weight;
//               w += weight;
//               //cout << sectionFuncPtr[i]->Parameter(1) << " weight: " << weight << endl;
//             }
//         }
//       double sigma = sqrt(1./w);
//       double y0 = xw/w;
//       cout << "y0 = " << y0 << "+-" << sigma << endl;

      //CHECK CHI2 OPTIMISATION
      TCanvas* can3 = new TCanvas;
      sectionChi.resize(nSec);
      string drawoption("AL");
      TLegend* legchi = new TLegend(0.55,0.5,0.85,0.9);
      for(int i=0; i<nSec; i++)
        {
          if(i<1 || i >8)
            continue;
          
          const int nSkipBins=10;
          ostringstream graphTitle;
          graphTitle << "section_" << type[n] << "_chi2_Graph_" << i;
          sectionChi[i] = (new TGraphErrors(0));
          sectionChi[i]->SetName(graphTitle.str().c_str());
          for (int skipBin=0; skipBin<nSkipBins; skipBin++)
            {
              int binStart, binEnd, helper;
              h_length_scale->GetBinXYZ(h_length_scale->FindBin(sectionBegin[i]),binStart,helper,helper); binStart++;
              h_length_scale->GetBinXYZ(h_length_scale->FindBin(sectionEnd[i]),binEnd,helper,helper); binEnd--;

              binStart += skipBin;

              if(binStart >= binEnd)
                continue;

              double x = double(h_length_scale->GetBinLowEdge(binStart) - h_length_scale->GetBinLowEdge(binStart-skipBin)) / 11246.;
              //cout << "skip bin: " << skipBin << "(" << binStart << ")" << endl;

              ostringstream funcTitle;
              funcTitle << "section" << type[n] << "Func_" << i << "_" << skipBin;

              TF1* helperFunc = new TF1(funcTitle.str().c_str(),"gaus");
              funcTitle << "_Prof";
              TH1D* helperProfile = h_length_scale->ProjectionY(funcTitle.str().c_str(),binStart,binEnd);
              TFitResultPtr helperPtr = helperProfile->Fit(helperFunc,"QSN");

              if(Int_t(helperPtr) !=0)
                {
                  cout << "fit failed" << endl;
                  cout << "skip bin: " << skipBin << "(" << binStart << ")" << endl;
                  continue;
                }
              
              double chi2 = helperPtr->Chi2()/double(helperPtr->Ndf());
              sectionChi[i]->SetPoint(sectionChi[i]->GetN(),x,chi2);
              //cout << skipBin << " " << x << " " << chi2 << endl;
            }
          //sectionChi[i]->Print("ALL");
          sectionChi[i]->SetTitle(";skip interval [s]; #chi^{2}/NDF");
          sectionChi[i]->GetYaxis()->SetRangeUser(0,6);
          sectionChi[i]->GetXaxis()->SetLimits(0,30);
          sectionChi[i]->SetLineWidth(2);
          sectionChi[i]->SetLineColor(i);
          sectionChi[i]->Draw(drawoption.c_str());
          drawoption = string("L");
          
          ostringstream legtext ; legtext << "Section " << i << " (" << sectionTruth[i] << " µm)";
          legchi->AddEntry(sectionChi[i],legtext.str().c_str(),"l");

        }
#ifdef __CINT__
      CMSText(1,1,1,string("#Delta")+type[n]+string(" length scale"),"","pp, #sqrt{s}=2.76 TeV");
      SetLegAtt(legchi);
#endif
      legchi->Draw("SAME");
      TLine* line = new TLine(skip/11246.,0,skip/11246.,2.5);
      line->SetLineWidth(2);
      line->SetLineStyle(2);
      line->Draw("SAME");
      can3->SaveAs((string("plots/vdm_length_scale_")+type[n]+string("_3_pp.pdf")).c_str());
          
      //Determine reference value y0 to subtract from plotting
      TGraph helperGraph(nSec);
      double y0=0;
      for (int i=0; i<nSec; i++)
        {
          double y = sectionFuncPtr[i]->Parameter(1);
          helperGraph.SetPoint(i,sectionTruth[i]*(type[n]=="X"?-1:1), y);
          y0 = helperGraph.Eval(0);
        }
      cout << "y0 = " << y0 << endl;

      //TRUTH VS TRACKER PLOT
      for (int i=0; i<nSec; i++)
        {
          ostringstream text;
          double size = 0.01;
          double y = sectionFuncPtr[i]->Parameter(1);
          double y_cc = sectionMean[i]; //just used for cross checking (cc) the gaussian fit
          double yum = (y-y0)*1e4; //cm -> µm => 1e-2 -> 1e-6 => 1e4
          double yum_cc = (y_cc-y0)*1e4; //cm -> µm => 1e-2 -> 1e-6 => 1e4
          double yumerror = (sectionFuncPtr[i]->ParError(1))*10000.;
          double yumerror_cc = sectionMeanE[i] * 10000;
          text << "#Delta" << type[n] << "_{Fit}=" << fixed << setprecision(1) << yum;
          TPaveText* txt = new TPaveText(sectionBegin[i],y+1.5*size,sectionEnd[i],y+2.5*size,"b t l");
          txt->SetTextFont(62);
          txt->SetFillStyle(0);
          txt->SetTextColor(kRed);
          txt->SetTextSize(0.04);
          txt->SetBorderSize(0);
          txt->AddText(text.str().c_str());
          txt->Draw("SAME");
          if(i>=1 && i<=4) //WARNING also setpoint needs to be changed
            {
              cout << "up " << i << " " << sectionTruth[i]*(type[n]=="X"?-1:1) << " " << yum << "+-" << yumerror << endl;
              h_truth_fit_up->SetPoint(i-1,sectionTruth[i]*(type[n]=="X"?-1:1), yum); // Coordinate Sys different z? X has to be inverted.
              h_truth_fit_up->SetPointError(i-1,0, yumerror);
              h_truth_fit_crosscheck_up->SetPoint(i-1,sectionTruth[i]*(type[n]=="X"?-1:1), yum_cc); // Coordinate Sys different z? X has to be inverted.
              h_truth_fit_crosscheck_up->SetPointError(i-1,0, yumerror_cc);
            }
          if(i>=5 && i<=8) //anti hysteresis //WARNING also setpoint needs to be changed
            {
              cout << "down " << i << " " << sectionTruth[i]*(type[n]=="X"?-1:1) << " " << yum << "+-" << yumerror << endl;
              h_truth_fit_down->SetPoint(i-5,sectionTruth[i]*(type[n]=="X"?-1:1), yum); // Coordinate Sys different z? X has to be inverted.
              h_truth_fit_down->SetPointError(i-5,0, yumerror);
              h_truth_fit_crosscheck_down->SetPoint(i-5,sectionTruth[i]*(type[n]=="X"?-1:1), yum_cc); // Coordinate Sys different z? X has to be inverted.
              h_truth_fit_crosscheck_down->SetPointError(i-5,0, yumerror_cc);
            }
        }
      canFit->SaveAs((string("plots/vdm_length_scale_")+type[n]+string("_Fits_pp.pdf")).c_str());
      
      TCanvas* can2 = new TCanvas;
      ostringstream titleup; titleup << ";#Delta" << type[n] << " (LHC) [#mum]; #Delta" << type[n] << " (CMS) [#mum]";
      h_truth_fit_up->SetTitle(titleup.str().c_str());
      h_truth_fit_up->SetMarkerSize(1.3);
      h_truth_fit_up->SetMarkerColor(kRed);
      h_truth_fit_up->SetLineColor(kRed);
      h_truth_fit_up->SetLineWidth(2);
      h_truth_fit_up->GetXaxis()->SetLimits(-400,400);
      h_truth_fit_up->GetYaxis()->SetRangeUser(-400,400);
      h_truth_fit_up->Draw("AP");
      TFitResultPtr fit_up = h_truth_fit_up->Fit("pol1","QS");
      TFitResultPtr fit_crosscheck_up = h_truth_fit_crosscheck_up->Fit("pol1","QNS");
      h_truth_fit_up->GetFunction("pol1")->SetLineWidth(2);
      h_truth_fit_up->GetFunction("pol1")->SetLineColor(kRed);
      h_truth_fit_down->SetMarkerColor(kBlue);
      h_truth_fit_down->SetMarkerStyle(25);
      h_truth_fit_down->SetMarkerSize(1.3);
      h_truth_fit_down->SetLineColor(kBlue);
      h_truth_fit_down->SetLineWidth(2);
      h_truth_fit_down->Draw("P");
      TFitResultPtr fit_down = h_truth_fit_down->Fit("pol1","QS");
      TFitResultPtr fit_crosscheck_down = h_truth_fit_crosscheck_down->Fit("pol1","QNS");
      h_truth_fit_down->GetFunction("pol1")->SetLineWidth(2);
      h_truth_fit_down->GetFunction("pol1")->SetLineColor(kBlue);
      TLegend* leg = new TLegend(0.22,0.72,0.6,0.82);
      ostringstream legup,legdown;
      legup   << "#Delta" << type[n] << " low-to-high (Slope:" << fixed << setprecision(3) << fit_up  ->Parameter(1) << " )";
      legdown << "#Delta" << type[n] << " high-to-low (Slope:" << fixed << setprecision(3) << fit_down->Parameter(1) << " )";
      leg->AddEntry(h_truth_fit_up  ,legup  .str().c_str(),"lp");
      leg->AddEntry(h_truth_fit_down,legdown.str().c_str(),"lp");
#ifdef __CINT__
      SetLegAtt(leg);
      CMSText(1,1,1,"","","pp, #sqrt{s}=2.76 TeV");
#endif
      leg->Draw("SAME");
      can2->SaveAs((string("plots/vdm_length_scale_")+type[n]+string("_2_pp.pdf")).c_str());

      double average = (fit_up->Parameter(1) + fit_down->Parameter(1)) / 2.;
      double average_cc = (fit_crosscheck_up->Parameter(1) + fit_crosscheck_down->Parameter(1)) / 2.;
      double stat = sqrt( pow(fit_up->Parameter(1)/2.,2) * pow(fit_down->ParError(1),2) + pow(fit_down->Parameter(1)/2.,2) * pow(fit_up->ParError(1),2));
      double sysupdown = fabs(fit_up->Parameter(1) - fit_down->Parameter(1))/ 2.;
      double sysfit = fabs(average_cc - average) / 2.;
      double sysskip = (type[n]=="X"?0.001:0.003);
      double sys = sqrt ( sysfit*sysfit + sysupdown*sysupdown + sysskip*sysskip);

      cout << endl << endl << endl;
      cout << fixed << setprecision(3)
           << "        Δ" << type[n] << endl
           << "--Correction Factor: " << average << endl
           << "up: " << fit_up->Parameter(1) << endl
           << "down: " << fit_down->Parameter(1) << endl
           << "--Stat: " << stat << endl
           << "--Sys Combined: " << sys << endl
           << "Sys. Up Down: " << sysupdown << endl
           << "Sys. Fitting: " << sysfit << endl
           << "Sys. Skipping: " << sysskip << endl;
      cout << endl << endl << endl;
    }

  can1->SaveAs((string("plots/vdm_length_scale")+string("_1_pp.pdf")).c_str());
  canFind->SaveAs((string("plots/vdm_length_scale")+string("_sections_pp.pdf")).c_str());
}
Esempio n. 19
0
void PrintCorFile(Int_t runNumber){





  Int_t num = gDirectory->GetListOfKeys()->GetSize();









  TString user =gSystem->Getenv("R00TLe_User");
  TString install =gSystem->Getenv("R00TLeInstall");





  ifstream InCorrectionsFile;
  stringstream ss1;

  ss1<<install<<"/prm/Corrections"<<runNumber<<".txt";

  InCorrectionsFile.open(ss1.str().c_str());
  if (!InCorrectionsFile.is_open()){
    cout<<"File not found"<<endl;
    return;
  }


  std::map<TString,Double_t> timingOffsetsFromFile;
  TString NameInFile;
  Double_t trash,T_Offset;
  while (true){
    InCorrectionsFile>>NameInFile>>trash>>trash>>T_Offset;
    if (InCorrectionsFile.eof()){
      break;
    }

    timingOffsetsFromFile[NameInFile]=T_Offset;
  }






  TF1 * aFunc = new TF1("aFunc","pol1");
  
  aFunc->SetParLimits(0,-20,20);
  aFunc->SetParLimits(1,0,2);

  for (int i=0;i<num;i++){
    TString name = gDirectory->GetListOfKeys()->At(i)->GetName();
    TGraphErrors* graph = (TGraphErrors*)gDirectory->Get(name);

    if (name[0]== 'S'||name[0]=='N'){
      TFitResultPtr result = graph->Fit("aFunc","QS");
      Int_t status = result;

      if (status == 0){
	
	printf("%s  %8.4lf  %8.4lf  %8.4lf\n",name.Data(),result->Value(1),result->Value(0),timingOffsetsFromFile[name]);
	//	cout<<name<<"  "<<result->Value(1)<<"  "<<result->Value(0)<<"  "<<timingOffsetsFromFile[name]<<endl;
      }
    }
    
  }


}
Esempio n. 20
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;
  }
  }
}
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";
}
Esempio n. 22
0
int ListMaxRes(int start=0,int num=1){


  const int NumOfFiles =60;

  if (start + num > NumOfFiles ){
    cout<<"Only have "<<NumOfFiles <<" files"<<endl;
  }
  
  std::string list[]={"FL3FG0d2w0run-0324--softwareCFD.root",
		      "FL3FG0d2w10run-0324--softwareCFD.root",
		      "FL3FG0d2w20run-0324--softwareCFD.root",
		      "FL3FG0d2w30run-0324--softwareCFD.root",
		      "FL3FG0d2w40run-0324--softwareCFD.root",
		      "FL3FG0d3w0run-0324--softwareCFD.root",
		      "FL3FG0d3w10run-0324--softwareCFD.root",
		      "FL3FG0d3w20run-0324--softwareCFD.root",
		      "FL3FG0d3w30run-0324--softwareCFD.root",
		      "FL3FG0d3w40run-0324--softwareCFD.root",
		      "FL3FG1d2w0run-0324--softwareCFD.root",
		      "FL3FG1d2w10run-0324--softwareCFD.root",
		      "FL3FG1d2w20run-0324--softwareCFD.root",
		      "FL3FG1d2w30run-0324--softwareCFD.root",
		      "FL3FG1d2w40run-0324--softwareCFD.root",
		      "FL3FG1d3w0run-0324--softwareCFD.root",
		      "FL3FG1d3w10run-0324--softwareCFD.root",
		      "FL3FG1d3w20run-0324--softwareCFD.root",
		      "FL3FG1d3w30run-0324--softwareCFD.root",
		      "FL4FG0d2w0run-0324--softwareCFD.root",
		      "FL4FG0d2w30run-0324--softwareCFD.root",
		      "FL4FG0d3w0run-0324--softwareCFD.root",
		      "FL4FG0d3w10run-0324--softwareCFD.root",
		      "FL4FG0d3w20run-0324--softwareCFD.root",
		      "FL4FG0d3w30run-0324--softwareCFD.root",
		      "FL4FG0d3w40run-0324--softwareCFD.root",
		      "FL4FG1d2w0run-0324--softwareCFD.root",
		      "FL4FG1d2w10run-0324--softwareCFD.root",
		      "FL4FG1d2w20run-0324--softwareCFD.root",
		      "FL4FG1d2w30run-0324--softwareCFD.root",
		      "FL4FG1d3w0run-0324--softwareCFD.root",
		      "FL4FG1d3w10run-0324--softwareCFD.root",
		      "FL4FG1d3w20run-0324--softwareCFD.root",
		      "FL4FG1d3w30run-0324--softwareCFD.root",
		      "FL4FG1d3w40run-0324--softwareCFD.root",
		      "FL5FG0d2w0run-0324--softwareCFD.root",
		      "FL5FG0d2w10run-0324--softwareCFD.root",
		      "FL5FG0d2w20run-0324--softwareCFD.root",
		      "FL5FG0d2w30run-0324--softwareCFD.root",
		      "FL5FG0d2w40run-0324--softwareCFD.root",
		      "FL5FG0d3w0run-0324--softwareCFD.root",
		      "FL5FG0d3w20run-0324--softwareCFD.root",
		      "FL5FG0d3w40run-0324--softwareCFD.root",
		      "FL5FG1d2w0run-0324--softwareCFD.root"};


  TCanvas *c = new TCanvas("c");
  c->cd(1);

  for (int i=start;i<start+num;i++){
    const char * stupid = list[i].c_str();
    TFile f(stupid);



    TH1F * h = new TH1F("h","h",100,0.1,0.6);

    TTree *flt = (TTree*)f.Get("flt");

    flt->Project("h","softTimes[0]-softTimes[1]+0.617706*GOE",
    		 "NumOfChannelsInEvent==2&&channels[0]==0&&abs(GOE)<0.6&&softwareCFDs[0]>0 && softwareCFDs[1]>0 && energies[0]>2600 && energies[0]<3600 &&energies[1]>2600&& energies[1]<3600");
    h->SetDirectory(0);



    TFitResultPtr p = h->Fit("gaus","QSN");
    int status = p;
    if (status==0)
      cout<<"The file is "<<stupid<<" "<<p->Value(2)*2.35*10000<<endl;
    
  }

  return 0;
}
Esempio n. 23
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");


}
Esempio n. 24
0
void Play()
{

    //gSystem->Load("libRooFit");
    //using namespace RooFit;

    TChain* S = new TChain("mjdTree");
    //Look at COPPI calibration data from Nov 2013
    S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001923.root");
    S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001924.root");
    S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001925.root");
    S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001926.root");
    S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001927.root");
    S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001928.root");
    S->Print();
    //S->Add("COPPIsA__run1131.root");
    
    TH1D *hc146 = new TH1D("hc146","Channel 146", 2000, 0, 800E3 );
    TH1D *hc147 = new TH1D("hc147","Channel 147", 2000, 0, 800E3 );

   TCanvas* c1 = new TCanvas("c1","",1500,800);
   TCanvas* c2 = new TCanvas("c2","",1500,800);
   TCanvas* c3 = new TCanvas("c3","",1500,800);
   c1->Divide(1,2);
   c2->Divide(1,2);
   c3->Divide(1,2);
    
   // --- Find Peaks in Spectrum ---
   c1->cd(1);
   S->Draw("energy>>hc146","channel==146");
   c1->cd(2);
   S->Draw("energy>>hc147","channel==147");

      // we calibrate with 133Ba and 60Co so let's build TSpectrum and look for those peaks
      // let's focus on the highest intensity lines:
      // 30.973 0.628
      // 356.0129 0.6205
      // 30.625 0.34
      // 80.9979 0.329
      //
      // 1332.492 0.999826
      // 1173.228 0.9985
      // 8.26-8.33 0.0000136
      // 7.46-7.48 0.000098

   //Use a gaussian to fit each of the peaks.
   TF1* tgaus = new TF1("tgaus","gaus",0,900E3);
   
   c1->cd(1);
   TSpectrum *s = new TSpectrum(12);
   Int_t nfound = s->Search(hc146,3,"",0.05);
   vector<calData> x146; //TSpectrum guess
   printf("Found %d candidate peaks to fit in channel 146 spectrum:\n",nfound);
   TH1 *hb = s->Background(hc146,20,"same");
   TH1D* hc146bf = (TH1D*)hc146->Clone("hc146bf");
   hc146bf->Add(hb,-1);
   if (hb) c1->Update();
   c2->cd(1);
   hc146bf->Draw();;
   Float_t *xpeaks = s->GetPositionX();
   calData d;
   for (int i = 0; i < nfound; i++) {
      //printf("%f : %f \n",s->GetPositionX()[i],s->GetPositionY()[i]);
      d.adc=s->GetPositionX()[i];
      x146.push_back(d);
   }
   sort(x146.begin(),x146.end(),CompareByadc);
   for(std::vector<calData>::iterator it=x146.begin(); it!=x146.end(); ++it)
   {
      tgaus->SetParameter(1,(*it).adc);
      TFitResultPtr r = hc146bf->Fit(tgaus,"SQ+","",(*it).adc-0.02*((*it).adc),(*it).adc+0.02*((*it).adc));
      (*it).fadc=r->Parameter(1);
      (*it).efadc=r->ParError(1);
   }
   cout << " Ts X \t\t Fit X \t\t\t err(x) " << endl;
   for(int i = 0; i < nfound; i++)
   {
      printf("%f \t %f \t +/- \t %f \n",x146[i].adc,x146[i].fadc,x146[i].efadc);
   }
   
   c1->cd(2);
   nfound = s->Search(hc147,3,"",0.05);
   vector<calData> x147; //TSpectrum guess
   printf("Found %d candidate peaks to fit in channel 147 spectrum:\n",nfound);
   TH1 *hb147 = s->Background(hc147,20,"same");
   TH1D* hc147bf = (TH1D*)hc147->Clone("hc147bf");
   hc147bf->Add(hb147,-1);
   if (hb147) c1->Update();
   c2->cd(2);
   hc147bf->Draw();;
   xpeaks = s->GetPositionX();
   for (int i = 0; i < nfound; i++) {
      //printf("%f : %f \n",s->GetPositionX()[i],s->GetPositionY()[i]);
      d.adc=s->GetPositionX()[i];
      x147.push_back(d);
   }
   sort(x147.begin(),x147.end(),CompareByadc);
   for(std::vector<calData>::iterator it=x147.begin(); it!=x147.end(); ++it)
   {
      tgaus->SetParameter(1,(*it).adc);
      TFitResultPtr r = hc147bf->Fit(tgaus,"SQ+","",(*it).adc-0.02*((*it).adc),(*it).adc+0.02*((*it).adc));
      (*it).fadc=r->Parameter(1);
      (*it).efadc=r->ParError(1);
   }
   cout << " Ts X \t\t Fit X \t\t\t err(x) " << endl;
   for(int i = 0; i < nfound; i++)
   {
      printf("%f \t %f \t +/- \t %f \n",x147[i].adc,x147[i].fadc,x147[i].efadc);
   }

   // --- Estimate Intensities

   // --- Fit centroids of peaks with linear function

   // --- Build Calibration Curve

   // We calibrated with 133Ba and 60Co
   Float_t BaCoHG[] = {383.8485,356.01,302.8508,276.3989,80.9979,79.6142,53.1622}; 
   Float_t BaCo[] = {1332.492,1173.228,1332.492-511,1173-511,356.01,30.973}; 

   c3->cd(1);
   //channel 146 is high gain
   vector<Float_t> cELT(BaCoHG,BaCoHG+sizeof(BaCoHG)/sizeof(Float_t));
   TGraphErrors* cal146 = ExtractCalCurve(x146,cELT);
   cal146->Draw("AP");
   c3->cd(2);
   //channel 147 is normal gain
   vector<Float_t> cE(BaCo,BaCo+sizeof(BaCo)/sizeof(Float_t));
   TGraphErrors* cal147 = ExtractCalCurve(x147,cE);
   cal147->Draw("AP");
   
}
Esempio n. 25
0
void perform_smart_fit(TGraphErrors * gabscor, TF1 * fabscor) {

  int maxFitIter = 50;
  int fitIter = 0;
  vector<double> bestPars;
  double bestRChi2 = 0;
  do {
    //
    // do the fit, get the results and the parameters of the fitted function
    //

    TFitResultPtr fitResPtr = gabscor->Fit(fabscor,"RQ0S");
    vector<double> auxPars = fitResPtr.Get()->Parameters();

    //
    // compute the reduced chi2 of this fit and if it is the best fit so far
    // then save the parameters
    //
    double rchi2 = fitResPtr.Get()->Chi2()/ fitResPtr.Get()->Ndf();
    if (fitResPtr.Get()->Ndf() == 0) rchi2 = 0;
    if (rchi2 > 0 && (rchi2<bestRChi2 || bestRChi2==0)){
      bestRChi2 = rchi2;
      bestPars  = auxPars;
    }
    
    //
    // increment the counter
    //
    fitIter++;
  }while(( bestRChi2 > 2 || bestRChi2 == 0 ) && fitIter < maxFitIter);
  
  //
  // set the best parameters and chi2 to the fit function
  //

  TF1 * ffh = gabscor->GetFunction("fit");
  for (unsigned int np=0;np < bestPars.size() ; np++){
    ffh->SetParameter(np,bestPars[np]);
    fabscor->SetParameter(np,bestPars[np]);
  }
  fabscor->SetChisquare(bestRChi2 * fabscor->GetNDF());
  ffh->SetChisquare(bestRChi2 * fabscor->GetNDF());

  //
  // warn if the fit diverges at low pt
  //
  //if (fabscor->Integral(0,10) > 25)
  //cout << "\t***ERROR***, fit for histo " << gabscor->GetName() << " diverges at low pt (<10 GeV/c)" << endl;
  
  //
  // check for failed fits
  // a chi2 of zero is symptomatic of a failed fit.
  //
  
if (bestRChi2 < 0.001){
    cout<<"\t***ERROR***, FIT HAS FAILED for histo "<<gabscor->GetName()
        <<" which has a reduced chi2="<<bestRChi2
        <<" after "<<fitIter<<" iterations. "<<endl;
  }

  //
  // check for large reduced chi2's
  // above 10 is a plain error; between 5 and 10 is a warning
  //

 if (bestRChi2 > 5){
    if (bestRChi2 > 10)
      cout<<"\t***ERROR***,";
    else
      cout<<"\tWARNING,";

    cout<<" fit for histo "<<gabscor->GetName()
        <<" has a reduced chi2="<<bestRChi2
        <<" after "<<fitIter<<" iterations"<<endl;
  }
}
int main(int argc, char* argv[]) {
    
    
    // initialize globalArgs
    globalArgs.data_folder = " ";
    globalArgs.arg_pathToSetupFile = " ";
    globalArgs.results_folder = " ";
    globalArgs.save_all = 0;
    
    // Get paremeter from the command
    int opt =0;
    opt = getopt(argc, argv, optString);
    if(opt == -1){
        std::cerr <<  "There is no opption in the command! Type \"output -h\" for help." << std::endl;
        exit(EXIT_FAILURE);
    }
    
    while(opt != -1){
        switch(opt){
            case 'd':
                globalArgs.data_folder= optarg;
                //std::cout<<"-p option path= "<<globalArgs.arg_pathToData<<std::endl;
                break;
            case 'S':
                globalArgs.arg_pathToSetupFile = optarg;
                break;
            case 'o':
                globalArgs.results_folder = optarg;
                break;
            case 'a':
                globalArgs.save_all = 1;
                break;
            case 'h':
            case '?':
                std::cerr << "Usage: output -d pathToData -S pathToSetupFile -o pathToResultsFolder [-a]" << std::endl;
                std::cerr << "----------------------------------------------------------------------------------------------------"<<std::endl;
                std::cerr << " '-d'+'-S'+'-o' options are necessary!"<<std::endl;
                std::cerr << "-----------------------------------------------------------------------------------------------------"<<std::endl;
                std::cerr << " use '-a' option afterwards to save all the plots of the analysis to further check."<<std::endl;
                std::cerr << "-----------------------------------------------------------------------------------------------------"<<std::endl;
                std::cerr << "Example: ./output -d /Users/Analysis_waveforms/ov_scan_pde_H2014/ -S /Users/Analysis_waveforms/config_file.txt -o /Users/Analysis_waveforms/Plots/ [-a]"<<std::endl;
                exit(EXIT_FAILURE);
                break;
            default:
                break;
        }
        opt = getopt(argc, argv, optString);
    }
    
    
    if((strncmp(globalArgs.data_folder," ",1) == 0|| strncmp(globalArgs.arg_pathToSetupFile," ",1) == 0)){
        std::cerr << "ERROR: -d or -S option is not set! Both of them has to be set correctly!"<<std::endl;
        exit(EXIT_FAILURE);
    }
    
    if(strncmp(globalArgs.results_folder," ",1) == 0){
        std::cerr << "ERROR: -o option is not set! It has to be set up correctly!"<<std::endl;
        exit(EXIT_FAILURE);
    }
            
    ifstream setupFile(globalArgs.arg_pathToSetupFile);
    if(!setupFile){
        std::cerr << "Failure: could not open file: \"" << globalArgs.arg_pathToSetupFile << "\"." << std::endl;
        std::cerr << "Please check if the path is correct or not!" << std::endl;
        exit(EXIT_FAILURE);
    }
    
    ////////////////
    //Define thresholds
    ////////////////
    
    //in  nanoseconds
    const double reject_time = 4;
    vector <Double_t> reject_time_v;
    //used for AP, delayed x-talk and long tau fit
    
    
    //in percentage of pe
    const double after_pulse_th = 0.38;
    vector <Double_t> after_pulse_th_v;
    const double direct_xtalk_th = 1.17;
    vector <Double_t> direct_xtalk_th_v;
    const double xtalk_th = 0.85;
    vector <Double_t> xtalk_th_v;
    const double time_dist_th = 0.4;
    vector <Double_t> time_dist_th_v;
    
    ////////////////
    ////////////////
    
    //Read setup file:
    string s;
    vector <TString> vol_folders;
    Int_t data_size;

    while (true) {
        
        Double_t rt;
        Double_t ap;
        Double_t delay;
        Double_t imme;
        
        getline(setupFile, s);
        if (setupFile.eof()) break;
        
        const char* searchString = s.c_str();
        char volt [20];
        Int_t numfiles;
        
        if (s.find("#") == 0 || s=="") {
            continue; // Skip commented  or empty lines
        }
        
        //Find the voltages
        if(sscanf(searchString, "V || %s ||", volt)==1){
            vol_folders.push_back(volt);
            reject_time_v.push_back(reject_time);
            after_pulse_th_v.push_back(after_pulse_th);
            direct_xtalk_th_v.push_back(direct_xtalk_th);
            xtalk_th_v.push_back(xtalk_th);
            time_dist_th_v.push_back(time_dist_th);
        }
        
        if(sscanf(searchString, "V/th || %s ||", volt)==1){
            vol_folders.push_back(volt);
            getline(setupFile, s);
            const char* thresholds_string = s.c_str();
            sscanf(thresholds_string, "Rej_t: %lf, AP_th: %lf, Delay_th: %lf, Imm_th: %lf", &rt,&ap,&delay,&imme);
            reject_time_v.push_back(rt);
            after_pulse_th_v.push_back(ap);
            direct_xtalk_th_v.push_back(imme);
            xtalk_th_v.push_back(delay);
            time_dist_th_v.push_back(time_dist_th);
        }
        
        //Find data size
        if(sscanf(searchString, "Files at each voltage || %d ||", &numfiles)==1){
            data_size = numfiles;
        }
    }
    
    
    
    //Initialize variables
    const Int_t vol_size = vol_folders.size();
    
    int singleplot=0;
    Int_t Event=0;
    Char_t Category[15];
    TGraph* waveform = 0;
    Double_t Amp;
    Double_t V_meas;
    
    double pe = 0.07;
    int row = 0;
    int full_n_file = 0;
    int ap_n_file = 0;
    int xtalk_n_file = 0;
    int dxtalk_n_file = 0;
    int time_dist_n_file = 0;
    
    int direct_xtalk_pulse;
    Double_t direct_xtalk_pulse_cnt=0;
    int xtalk_pulse;
    Double_t xtalk_pulse_cnt = 0;
    int after_pulse;
    Double_t after_pulse_cnt=0;
    Double_t event_cnt = 0;
    double sig_max = 0;
    double time_of_max = 0;
    double sig_max_first = 0;
    double time_of_max_first = 0;
    int max_cnt = 0;
    int max_noise_cnt = 0;
    int max_found = 0;
    
    
    
    /*const char * Voltage="56.5V";
    int event=0;
    if (singleplot) {
        single_plot(Voltage,event);
    }*/
    
    
    //Create a root tree with the graph of the waveform of each event and
    //classify them
    TString filename = globalArgs.results_folder;
    filename.Append("noiseanalysis.root");
    
    TFile *hfile = 0;
    hfile = TFile::Open(filename,"RECREATE");
    
    
    TTree *tree = new TTree("T","Noise Analysis");
    tree->Branch("Event",&Event,"Event/I");
    tree->Branch("Category",Category,"Category/C");
    //Uncomment if every single waveform is desired to be saved by its own on the root file
    //tree->Branch("waveform","TGraph",&waveform);
    tree->Branch("V_meas",&V_meas,"V_meas/D"); //OV of the measurement
    
   
    TGraph* Correl_noise[4];
    Correl_noise[0] = new TGraph();
    Correl_noise[1] = new TGraph();
    Correl_noise[2] = new TGraph();
    Correl_noise[3] = new TGraph();
    TGraph *Expfit_longtau[vol_size];
    TGraph *Expfit_AP[vol_size];
    
    //Fiting functions of long tau and AP recharge
    TF1 *exp_longtau= new TF1("exptau","[0]*exp(-x/[1])",0,180 * ns);
    TF1 *exp= new TF1("exp","[0]*(1-exp(-x/[1]))+[2]*exp(-x/[3])",0,180 * ns);
    
    TCanvas* c1[vol_size];
    TCanvas* c2[vol_size];
    TCanvas* c3[vol_size];
    TCanvas* c4[vol_size];
    
    TMultiGraph *Cleanwaves[vol_size];
    TCanvas* expfit_longtau_c[vol_size];
    TCanvas* expfit_AP_c[vol_size];
    
    cout<<"////////////"<< endl;
    cout<<"****----->Voltage Breakdown calculation ***"<< endl;
    
   
    vector <Double_t> pe_volt;
    TGraph *Vbias_ver= new TGraph();
    
    
        //Change to not recalculate the pe
        //pe_volt.push_back(6.87435e-02);
        /*pe_volt.push_back( 1.20426e-01);
        pe_volt.push_back(1.75262e-01);
        pe_volt.push_back(2.30936e-01);
        pe_volt.push_back(2.87958e-01);*/
        //pe_volt.push_back( 3.44156e-01);
        //Double_t VBD=55.9006;
    
    //Calculate Voltage breakdown and value of pe
    for (int i=0; i<vol_size; i++) {
        pe_volt.push_back(Amplitude_calc(vol_folders.at(i).Data(), data_size));
        V_meas = vol_folders.at(i).Atof();
        Vbias_ver->SetPoint(i, pe_volt.at(i), V_meas);
    }
    
    TCanvas* ca= new TCanvas("Voltage Breakdown calculation","Voltage Breakdown calculation",100,100,900,700);
    Vbias_ver->SetTitle("Voltage Breakdown calculation");
    Vbias_ver->GetYaxis()->SetTitle("Bias Volatge [V]");
    Vbias_ver->GetYaxis()->SetTitleOffset(1.2);
    Vbias_ver->GetXaxis()->SetTitle("Mean peak amplitude [V]");
    Vbias_ver->Draw("AP*");
    ca->SetGrid();
    
    TPaveText * pv = new TPaveText(0.2,0.65,0.35,0.74,"brNDC");
    
    cout<<"////////////"<< endl;
    cout<<"****----->Voltage Breakdown fit ***"<< endl;
    
    TFitResultPtr fit = Vbias_ver->Fit("pol1","S");
    Double_t VBD= fit->Value(0);
    
    Char_t VBD_text[20];
    sprintf(VBD_text,"V_{BD} = %2.2f",VBD);
    pv->AddText(VBD_text);
    pv->Draw();
    
    if (globalArgs.save_all==1) ca->Write();
    
    cout<<"////////////"<< endl;
    cout<<"****----->Noise analysis ***"<< endl;
    cout<<"////////////"<< endl;
    
    /////////////////
    // Loop over all Voltages measured
    /////////////////
    for (int i=0; i<vol_size; i++) {
        
        //Important to reinitialize, the value color* = kOrange-11 is used to plot axis of TGraph()
        
        int color1 = kOrange-11;
        int color2 = kOrange-11;
        int color3 = kOrange-11;
        int color4 = kOrange-11;
        
        direct_xtalk_pulse_cnt = 0;
        xtalk_pulse_cnt = 0;
        after_pulse_cnt = 0;
        event_cnt = 0; //Events on the Voltage measured
        
        cout<<"****----->Voltage analyzed: "<< vol_folders.at(i) << endl;
        
        
        //Define amplitude measured at which OV
        
        Double_t pe = pe_volt.at(i);
        
        V_meas = vol_folders.at(i).Atof()-VBD;
        
        //Define canvases to save and check results
        
        Char_t canvas_title[40];
        sprintf(canvas_title,"Direct CrossTalk OV = %2.2f V",V_meas);
        c1[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700);
        sprintf(canvas_title,"Delayed CrossTalk OV = %2.2f V",V_meas);
        c2[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700);
        sprintf(canvas_title,"After Pulse OV = %2.2f V",V_meas);
        c3[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700);
        sprintf(canvas_title,"Clean OV = %2.2f V",V_meas);
        c4[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700);
        
        Cleanwaves[i]=new TMultiGraph();
        
        sprintf(canvas_title,"Exponential fit, #tau_l OV = %2.2f V",V_meas);
        expfit_longtau_c[i] = new TCanvas(canvas_title,canvas_title,300,100,900,500);
        sprintf(canvas_title,"Exponential fit OV = %2.2f V",V_meas);
        expfit_AP_c[i] = new TCanvas(canvas_title,canvas_title,300,100,900,500);
        
        Expfit_longtau[i]= new TGraph();
        Expfit_AP[i]= new TGraph();
        
        //loop over every measurement on a folder
        for (int j=0; j<data_size; j++) {
            
            Char_t datafilename[200];
            Char_t datashortfilename[100];
            
            sprintf(datafilename,"%s%s/C1H%05i.csv",globalArgs.data_folder,vol_folders.at(i).Data(),j);
            sprintf(datashortfilename,"%s_C1H%05i",vol_folders.at(i).Data(),j);
            //Get the data of a single file:
            waveform = new TGraph(datafilename,"%lg %lg","/t;,");
            if (waveform->IsZombie()) continue;
            
            waveform->SetName(datashortfilename);
            waveform->SetTitle("");
            
            Int_t ROWS_DATA = waveform->GetN();
            Double_t *time = waveform->GetX();
            Double_t *volts = waveform->GetY();
            
            Amp = waveform->GetY()[0];
            
            
            /////////////////////////////////////////////////////
            // Data filtering into the different type of events
            // direct x-talk  AP   delayed x-talk
            /////////////////////////////////////////////////////
            after_pulse = 0;
            xtalk_pulse = 0;
            direct_xtalk_pulse = 0;
            sig_max = 0;
            max_cnt = 0;
            max_found = 0;
            
            /////////////////////////////////////////////////////
            // direct x-talk
            for (row = 0; row < ROWS_DATA; row++) {
                if ((time[row]>0 * ns)&(volts[row] > direct_xtalk_th_v.at(i) * pe)) {// time larger 0ns
                    direct_xtalk_pulse++;
                }
            }
            
            /////////////////////////////////////////////////////
            // after-pulse threshold
            for (row = 0; row < ROWS_DATA; row++) {
                if ((time[row]>reject_time_v.at(i)*ns)&(volts[row] > after_pulse_th_v.at(i) * pe)) {// time larger 4ns and ap_th
                    after_pulse++;
                }
            }
            
            /////////////////////////////////////////////////////
            // delayed x-talk
            for (row = 0; row < ROWS_DATA; row++) {
                if ((time[row]>reject_time_v.at(i)*ns)&(volts[row] > xtalk_th_v.at(i) * pe)) {// time larger 4ns and larger xtalk_th
                    xtalk_pulse++;
                }
            }
            
            
            /////////////////////////////////////////////////////////////////////
            // Detect peaks in data after 4ns, count the number of maxima and
            // measure the time of arrival of first maxima, used later for AP exp fit
            /////////////////////////////////////////////////////////////////////
            max_noise_cnt = 0;
            for (row = 0; row < ROWS_DATA; row++) {
                if (time[row] > reject_time_v.at(i)*ns) {// time larger 4ns
                    if (volts[row] > sig_max) {
                        sig_max = volts[row];        // set the max
                        time_of_max = time[row];    // time max
                        max_noise_cnt++;                   // set the histeresis cnt
                    }else if (max_noise_cnt > 0) max_noise_cnt--;  //  count down if no new max is reached
                    // decide if real max or only noise, threshold has to be reached in case of a real max
                    if (max_noise_cnt>2 && sig_max > time_dist_th_v.at(i) * pe) {
                        max_cnt++;
                        if (max_cnt == 1) {
                            sig_max_first = sig_max;  // sig max
                            time_of_max_first = time_of_max; // time max
                            max_found = 1;
                            //printf("First max found: sig=%f  time=%f ns max_noise_cnt=%d\n", sig_max, time_of_max / ns, max_noise_cnt);
                        }
                        
                        //printf("Max number is: %d   cnt=%d\n", max_cnt, max_noise_cnt);
                    }
                } // 4ns
            } //loop over time
            
            bool clean = true; //The pulse is clean until the contrary can be demonstrated
            char graph_title[50];
            
            //Check for imm x-talk and plot
            if (direct_xtalk_pulse > 0){
                direct_xtalk_pulse_cnt++;
                sprintf(Category,"ImmCrosstalk");
                c1[i]->cd();
                
                //Set graph color, and counting to draw axis and title
                color1=color1+2;
                if (color1>kOrange+110) {
                    color1=kOrange-8;
                }else if (color1>kOrange+109){
                    color1=kOrange-7;
                }
                waveform->SetLineColor(color1);
                waveform->SetMarkerColor(color1);
                
                //Format the graph
                sprintf(graph_title,"Direct CrossTalk OV = %2.2f V",V_meas);
                waveform = format_graph(waveform,graph_title,2.5*pe);
                
                if (color1>kOrange-8) {
                    waveform->Draw("SAME");
                }else{
                    waveform->Draw("AL");
                    c1[i]->SetGrid();
                }
                clean = false;
            }
            
            // only delayed x-talk
            if (xtalk_pulse > 0 && direct_xtalk_pulse == 0){
                xtalk_pulse_cnt++;
                sprintf(Category,"DelCrosstalk");
                c2[i]->cd();
                
                //Set graph color, and counting to draw axis and title
                color2=color2+2;
                if (color2>kOrange+110) {
                    color2=kOrange-8;
                }else if (color2>kOrange+109){
                    color2=kOrange-7;
                }
                waveform->SetLineColor(color2);
                waveform->SetMarkerColor(color2);
                
                //Format the graph
                sprintf(graph_title,"Delayed cross-talk OV = %2.2f V",V_meas);
                waveform = format_graph(waveform,graph_title,1.2*pe);

                if (color2>kOrange-8) {
                    waveform->Draw("SAME");
                }else{
                    waveform->Draw("AL");
                    c2[i]->SetGrid();
                }
                clean = false;
            }
            
            //  Only after pulse
            if (after_pulse > 0 && xtalk_pulse == 0 && direct_xtalk_pulse == 0){
                after_pulse_cnt++;
                sprintf(Category,"AfterPulse");
                c3[i]->cd();
                
                //Set graph color, and counting to draw axis and title
                color3=color3+2;
                if (color3>kOrange+110) {
                    color3=kOrange-8;
                }else if (color3>kOrange+109){
                    color3=kOrange-7;
                }
                waveform->SetLineColor(color3);
                waveform->SetMarkerColor(color3);
                
                //Format the graph
                sprintf(graph_title,"After pulse OV = %2.2f V",V_meas);
                waveform = format_graph(waveform,graph_title,1.2*pe);
                
                if (color3>kOrange-8) {
                    waveform->Draw("SAME");
                }else{
                    waveform->Draw("AL");
                    c3[i]->SetGrid();
                }
                
                clean = false;
                
                //Fill for the exponential fit
                Expfit_AP[i]->SetPoint(after_pulse_cnt-1,time_of_max,sig_max);
            }
            
            // Only clean graphs for the sample
            if (clean){
                sprintf(Category,"Clean");
                
                if (color4 < 860 && j <100) { //Max 100 clean graphs on the plot
                    Cleanwaves[i]->Add(waveform);
                    c4[i]->cd();
                    
                    //Set graph color, and counting to draw axis and title
                    color4=color4+2;
                    if (color4>kOrange+110) {
                        color4=kOrange-8;
                    }else if (color4>kOrange+109){
                        color4=kOrange-7;
                    }
                    waveform->SetLineColor(color4);
                    waveform->SetMarkerColor(color4);
                    
                    //Format the graph
                    sprintf(graph_title,"Clean pulse OV = %2.2f V",V_meas);
                    waveform = format_graph(waveform,graph_title,1.2*pe);
                    
                    if (color4>kOrange-8) {
                        waveform->Draw("SAME");
                    }else{
                        waveform->Draw("AL");
                        c4[i]->SetGrid();
                    }
                }
                
                
            }
            
            tree->Fill();
            
            Event ++;//Total number of events analyzed on the run
            if (Event%500==0) {
                cout<<"****----->Events analyzed:"<< Event << endl;
            }
            
            event_cnt++;
            
            
        }
        
        cout<<"////////////"<< endl;
        cout<<"****----->Long tau fit ***"<< endl;
        expfit_longtau_c[i]->cd();
        Cleanwaves[i]->Draw("AP*");
        // Fit parameters and limits to calculate slow component of the pulse
        exp_longtau->SetParameter(0,pe*0.2);
        exp_longtau->SetParLimits(0,0.05*pe,0.5*pe);
        exp_longtau->SetParameter(1,80*ns);
        exp_longtau->SetParLimits(1,4*ns,200*ns);
        Cleanwaves[i]->Fit("exptau","","",reject_time_v.at(i)*ns,60*ns); // Fit boundaries for the slow component of the pulse
        Double_t amp0 = exp_longtau->GetParameter(0);
        Double_t tau = exp_longtau->GetParameter(1);
        if (globalArgs.save_all==1) expfit_longtau_c[i]->Write();
        
        c4[i]->cd();
        TF1* exp_tau_plot =(TF1*) exp_longtau->Clone();
        exp_tau_plot->Draw("SAME");//Draw fit-line over clean waveforms
        
        cout<<"////////////"<< endl;
        cout<<"****----->After pulse fit ***"<< endl;
        expfit_AP_c[i]->cd();
        Expfit_AP[i]->Draw("AP*");
        // Fit parameters and limits to calculate AP recharge
        exp->SetParameter(0,pe);
        exp->SetParLimits(0,0.5*pe,1.5*pe);
        exp->SetParameter(1,30*ns);
        exp->SetParLimits(1,4*ns,500*ns);
        exp->SetParameter(2,amp0);
        exp->FixParameter(2,amp0);
        exp->SetParameter(3,tau);
        exp->FixParameter(3,tau);
        Expfit_AP[i]->Fit("exp");
        if (globalArgs.save_all==1) expfit_AP_c[i]->Write();
        
        c3[i]->cd();
        TF1* exp_plot =(TF1*) exp->Clone();
        exp_plot->Draw("SAME"); //Draw fit-line over AP waveforms
        
        
        //Final result: Correlated noise
        Correl_noise[0]->SetPoint(i,V_meas,direct_xtalk_pulse_cnt/event_cnt*100);
        Correl_noise[1]->SetPoint(i,V_meas,after_pulse_cnt/event_cnt*100);
        Correl_noise[2]->SetPoint(i,V_meas,xtalk_pulse_cnt/event_cnt*100);
        Correl_noise[3]->SetPoint(i,V_meas,
                                  Correl_noise[0]->GetY()[i]+Correl_noise[1]->GetY()[i]+Correl_noise[2]->GetY()[i]);
        
        
        //Save/print reults:
        if (globalArgs.save_all==1){
            c1[i]->Write();
            c2[i]->Write();
            c3[i]->Write();
            c4[i]->Write();
        }
        
        sprintf(canvas_title,"%sImmcrosstalk_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data());
        c1[i]->Print(canvas_title,"pdf");
        sprintf(canvas_title,"%sDelcrosstalk_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data());
        c2[i]->Print(canvas_title,"pdf");
        sprintf(canvas_title,"%sAfterpulse_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data());
        c3[i]->Print(canvas_title,"pdf");
        sprintf(canvas_title,"%sClean_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data());
        c4[i]->Print(canvas_title,"pdf");
        
        
    }
    //Save TTree with hist of noise
    //Save each event with its OV and the noise classification
    tree->Write();
    
    //Create final plot of total correlated noise
    TCanvas* c5 = new TCanvas("Correlated Noise","Correlated Noise",100,100,900,700);
    
    Double_t tot_max_noise = TMath::MaxElement(Correl_noise[3]->GetN(),Correl_noise[3]->GetY());
    
    Correl_noise[3]->SetTitle("Correlated Noise");
    Correl_noise[3]->SetMarkerColor(kRed);
    Correl_noise[3]->SetLineColor(kRed);
    Correl_noise[3]->GetYaxis()->SetRangeUser(0,tot_max_noise+2);
    Correl_noise[3]->GetYaxis()->SetTitle("Noise [%]");
    Correl_noise[3]->GetXaxis()->SetTitle("OverVoltage [V]");
    Correl_noise[3]->Draw("ALP*");
    
    Correl_noise[0]->SetTitle("Direct Cross-Talk");
    Correl_noise[1]->SetTitle("After Pulse");
    Correl_noise[2]->SetTitle("Delayed Cross-Talk");
    Correl_noise[0]->SetLineColor(kBlue);
    Correl_noise[1]->SetLineColor(kOrange+7);
    Correl_noise[2]->SetLineColor(kGreen+2);
    Correl_noise[0]->SetMarkerColor(kBlue);
    Correl_noise[1]->SetMarkerColor(kOrange+7);
    Correl_noise[2]->SetMarkerColor(kGreen+2);
    Correl_noise[0]->Draw("LP*");
    Correl_noise[1]->Draw("LP*");
    Correl_noise[2]->Draw("LP*");
    
    TLegend* leg = new TLegend(0.15,0.65,0.47,0.87);
    leg->AddEntry(Correl_noise[3],"Total","lp");
    leg->AddEntry(Correl_noise[0],"Direct Cross-Talk","lp");
    leg->AddEntry(Correl_noise[1],"After Pulse","lp");
    leg->AddEntry(Correl_noise[2],"Delayed Cross-Talk","lp");
    leg->Draw();
    
    
    c5->SetGrid();
    TString final_plot_name = globalArgs.results_folder;
    final_plot_name.Append("Correlated Noise.pdf");
    c5->Print(final_plot_name,"pdf");
    c5->Write();
    
    delete hfile;
    
    return 0;

}
Esempio n. 27
0
	double ex[8] = {0.0075, 0.0025, 0.005, 0.005, 0.005, 0.0075, 0.0075, 0.02};
	double ey[8] = {0., 0., 0., 0., 0., 0., 0., 0.};
	double ez[8] = {0., 0., 0., 0., 0., 0., 0., 0.};
	double eyy[8] = {0., 0., 0., 0., 0., 0., 0., 0.};
	double ezz[8] = {0., 0., 0., 0., 0., 0., 0., 0.};

	TF1 *f1 = new TF1("f1", "gaus", 1, 3);
   	//TF1 *f1 = new TF1("f1","[0]*exp(-0.5*((x-[1])/[2])**2) + (1-[0])*exp(-0.5*((x-[1])/[3])**2)",1,3);
	//f1->SetParameters(40, 5e-05, 3e-2);

	TCanvas * d = new TCanvas("d","d", 600, 600);
	d->Divide(3,3);
	d->cd(1);
	gPad->SetLogy(1);
	h0->Draw();
	TFitResultPtr r = h0->Fit("f1", "S");
	z[0] = r->Parameter(1);
	ez[0] = r->ParError(1);
	y[0] = r->Parameter(2);
	ey[0] = r->ParError(2);
	zz[0] = r->Parameter(1);
	ezz[0] = r->ParError(1);
	yy[0] = r->Parameter(3);
	eyy[0] = r->ParError(3);
	
	d->cd(2);
	gPad->SetLogy(1);
	h1->Draw();
	r = h1->Fit("f1","S");
	z[1] = r->Parameter(1);
	ez[1] = r->ParError(1);
Esempio n. 28
0
void getMassPlot(TString function){
  if(filename == "") throw runtime_error("No input file provided");
	ifstream infile(filename);
	string line;
	bool start_read = false;
	while(getline(infile, line)){
		if(Contains(line, "---")){
			start_read = true;
		}else if(start_read){
			istringstream iss(line);
			topmass = 0; xsec = 0; xlumi = 0; sys = 0; stat = 0; 
			iss >> topmass >> xsec >> stat >> sys >> xlumi; 
			//err = TMath::Sqrt(stat*stat + sys*sys + xlumi*xlumi);
			err = stat;
			vtopmass.push_back(topmass);
			vxsec.push_back(xsec);
			vlumi.push_back(xlumi);
			vsys.push_back(sys);
			vstat.push_back(stat);
			verr.push_back(err);
			vmerr.push_back(0.);
		}
	}
	infile.close();

  TCanvas* c = new TCanvas("c", "Graph", 200, 10, 700, 500);

	g  = new TGraph(TVectorD(vtopmass.size(),&vtopmass[0]), TVectorD(vxsec.size(), &vxsec[0]) ); 
  ge = new TGraphErrors( TVectorD(vtopmass.size(),&vtopmass[0]), TVectorD(vxsec.size(), &vxsec[0]), TVectorD(vmerr.size(), &vmerr[0]), TVectorD(verr.size(), &verr[0]));
	xs = vxsec[0];
  g->SetMarkerStyle(20);
  ge->SetFillStyle(3002); ge->SetFillColor(4);
  mg->SetTitle("13 TeV, >=1btag, L = 2223 pb^{-1}; top-quark mass (GeV); ttbar cross-section (pb)");
  mg->Add(ge);
  mg->Add(g);
  mg->Draw("a1P");

	float e0 = 0; float p0 = 0; float p1 = 0; float p2 = 0;
  TFitResultPtr f;
  if(function == "lin"){
    TF1* fuf = new TF1("flin",func,165,180,1);
    f = g->Fit("flin", "s", "", 165, 180);
    p0 = f->Parameter(0); e0 = f->ParError(0);// "xs*(1+k(x-x0))" // xs --> sigma_tt(172.5), x0 = 172.5 GeV, x = m_top
    DrawTLatex(0.85, 0.88, 0.035, 33, TString("Fit: #sigma_{t#bar{t}}(13TeV,m_{top}) = #sigma_{t#bar{t}}(13TeV,172.5 GeV)*(1+k(m_{top}-172.5 GeV))"));
    DrawTLatex(0.65, 0.80, 0.035, 33, TString(Form("k = %2.5f #pm %1.5f (%1.2f%)", p0, e0, TMath::Abs(e0/p0*100))));
  }
  if(function == "pol"){
    f = g->Fit("pol2", "s", "", 165, 180);
    p0 = f->Parameter(0); p1 = f->Parameter(1); p2 = f->Parameter(2);
    DrawTLatex(0.55, 0.88, 0.035, 33, Form("Fit: #sigma_{t#bar{t}}(13TeV,m_{top}) = a m_{top}^{2} + b m_{top} + c"));
    DrawTLatex(0.75, 0.83, 0.035, 33, Form("a=%4.3f (pb/GeV)^{2}\n,  b=%4.3f (pb/GeV)\n,  c=%4.3f pb", p2,p1,p0));
  }
  if(function == "exp"){
    f = g->Fit("expo", "s", "", 165, 180);
    p0 = f->Parameter(0); p1 = f->Parameter(1);
    DrawTLatex(0.65, 0.88, 0.035, 33, Form("Fit: exp(a+bm_{top})      a=%4.3f     b=%4.3f GeV^{-1}", p0, p1));
 }


  mg->GetYaxis()->SetLimits(740,860); mg->SetMinimum(740); mg->SetMaximum(860);
  mg->GetXaxis()->SetLimits(165,180);

  c->Update();
  TString outputdir = "/mnt_pool/fanae105/user/juanr/TOP13TeV/TopCode/TopMassPlots/";
  c->Print(outputdir+"top_mass_"+function+".pdf","pdf");
  c->Print(outputdir+"top_mass_"+function+".png","png");
  delete c;
}
void ExtractTrackBasedTiming(TString fileName = "hd_root.root", int runNumber = 10390, TString variation = "default", bool verbose = false,TString prefix = ""){

   // set "prefix" in case you want to ship the txt files elsewhere...
   cout << "Performing Track Matched timing fits for File: " << fileName.Data() << " Run: " << runNumber << " Variation: " << variation.Data() << endl;

   ExtractTrackBasedTimingNS::thisFile = TFile::Open( fileName , "UPDATE");
   if (ExtractTrackBasedTimingNS::thisFile == 0) {
      cout << "Unable to open file " << fileName.Data() << "...Exiting" << endl;
      return;
   }

   //We need the existing constants, The best we can do here is just read them from the file.
   vector<double> sc_tdc_time_offsets;
   vector<double> sc_fadc_time_offsets;
   vector<double> tof_tdc_time_offsets;
   vector<double> tof_fadc_time_offsets;
   vector<double> tagm_tdc_time_offsets;
   vector<double> tagm_fadc_time_offsets;
   vector<double> tagh_tdc_time_offsets;
   vector<double> tagh_fadc_time_offsets;
   vector<double> tagh_counter_quality;

   double sc_t_base_fadc, sc_t_base_tdc;
   double tof_t_base_fadc, tof_t_base_tdc;
   double bcal_t_base_fadc, bcal_t_base_tdc;
   double tagm_t_base_fadc, tagm_t_base_tdc;
   double tagh_t_base_fadc, tagh_t_base_tdc;
   double fdc_t_base_fadc, fdc_t_base_tdc;
   double fcal_t_base;
   double cdc_t_base;
   double RF_Period;

   cout << "Grabbing CCDB constants..." << endl;
   // Base times
   GetCCDBConstants1("/CDC/base_time_offset" ,runNumber, variation, cdc_t_base);
   GetCCDBConstants1("/FCAL/base_time_offset",runNumber, variation, fcal_t_base);
   GetCCDBConstants1("/PHOTON_BEAM/RF/beam_period",runNumber, variation, RF_Period);
   GetCCDBConstants2("/FDC/base_time_offset" ,runNumber, variation, fdc_t_base_fadc, fdc_t_base_tdc);
   GetCCDBConstants2("/BCAL/base_time_offset" ,runNumber, variation, bcal_t_base_fadc, bcal_t_base_tdc);
   GetCCDBConstants2("/PHOTON_BEAM/microscope/base_time_offset" ,runNumber, variation, tagm_t_base_fadc, tagm_t_base_tdc);
   GetCCDBConstants2("/PHOTON_BEAM/hodoscope/base_time_offset" ,runNumber, variation, tagh_t_base_fadc, tagh_t_base_tdc);
   GetCCDBConstants2("/START_COUNTER/base_time_offset" ,runNumber, variation, sc_t_base_fadc, sc_t_base_tdc);
   GetCCDBConstants2("/TOF/base_time_offset" ,runNumber, variation, tof_t_base_fadc, tof_t_base_tdc);
   // Per channel
   //GetCCDBConstants("/BCAL/TDC_offsets"    ,runNumber, variation, bcal_tdc_offsets);
   //GetCCDBConstants("/FCAL/timing_offsets" ,runNumber, variation, fcal_adc_offsets);
   GetCCDBConstants("/START_COUNTER/adc_timing_offsets" ,runNumber, variation, sc_fadc_time_offsets);
   GetCCDBConstants("/START_COUNTER/tdc_timing_offsets" ,runNumber, variation, sc_tdc_time_offsets);
   GetCCDBConstants("/PHOTON_BEAM/microscope/fadc_time_offsets" ,runNumber, variation, tagm_fadc_time_offsets,3);// Interested in 3rd column
   GetCCDBConstants("/PHOTON_BEAM/microscope/tdc_time_offsets"  ,runNumber, variation, tagm_tdc_time_offsets,3);
   GetCCDBConstants("/PHOTON_BEAM/hodoscope/fadc_time_offsets"  ,runNumber, variation, tagh_fadc_time_offsets,2);// Interested in 2nd column
   GetCCDBConstants("/PHOTON_BEAM/hodoscope/tdc_time_offsets"   ,runNumber, variation, tagh_tdc_time_offsets,2);
   GetCCDBConstants("/PHOTON_BEAM/hodoscope/counter_quality"    ,runNumber, variation, tagh_counter_quality,2);
   GetCCDBConstants("/TOF/adc_timing_offsets",runNumber, variation, tof_fadc_time_offsets);
   GetCCDBConstants("/TOF/timing_offsets",runNumber, variation, tof_tdc_time_offsets);

   cout << "CDC base times = " << cdc_t_base << endl;
   cout << "FCAL base times = " << fcal_t_base << endl;
   cout << "FDC base times = " << fdc_t_base_fadc << ", " << fdc_t_base_tdc << endl;
   cout << "BCAL base times = " << bcal_t_base_fadc << ", " << bcal_t_base_tdc << endl;
   cout << "SC base times = " << sc_t_base_fadc << ", " << sc_t_base_tdc << endl;
   cout << "TOF base times = " << tof_t_base_fadc << ", " << tof_t_base_tdc << endl;
   cout << "TAGH base times = " << tagh_t_base_fadc << ", " << tagh_t_base_tdc << endl;
   cout << "TAGM base times = " << tagm_t_base_fadc << ", " << tagm_t_base_tdc << endl;

   cout << endl;
   cout << "RF_Period = " << RF_Period << endl;
   cout << endl;

   cout << "Done grabbing CCDB constants...Entering fits..." << endl;

   // Do our final step in the timing alignment with tracking

   //When the RF is present we can try to simply pick out the correct beam bucket for each of the runs
   //First just a simple check to see if we have the appropriate data
   bool useRF = false;
   TH1I *testHist = ExtractTrackBasedTimingNS::Get1DHistogram("HLDetectorTiming", "TAGH_TDC_RF_Compare","Counter ID 001");
   if (testHist != NULL){ // Not great since we rely on channel 1 working, but can be craftier later.
      cout << "Using RF Times for Calibration" << endl;
      useRF = true;
   }
   ofstream outFile;
   TH2I *thisHist; 
   thisHist = ExtractTrackBasedTimingNS::Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGM - SC Target Time");
   if (useRF) thisHist = ExtractTrackBasedTimingNS::Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGM - RFBunch Time");
   if (thisHist != NULL){
      //Statistics on these histograms are really quite low we will have to rebin and do some interpolation
      outFile.open(prefix + "tagm_tdc_timing_offsets.txt", ios::out | ios::trunc);
      outFile.close(); // clear file
      outFile.open(prefix + "tagm_adc_timing_offsets.txt", ios::out | ios::trunc);
      outFile.close(); // clear file
      int nBinsX = thisHist->GetNbinsX();
      int nBinsY = thisHist->GetNbinsY();
      TH1D * selectedTAGMOffset = new TH1D("selectedTAGMOffset", "Selected TAGM Offset; Column; Offset [ns]", nBinsX, 0.5, nBinsX + 0.5);
      TH1I * TAGMOffsetDistribution = new TH1I("TAGMOffsetDistribution", "TAGM Offset; TAGM Offset [ns]; Entries", 500, -250, 250);
      for (int i = 1 ; i <= nBinsX; i++){ 
         TH1D *projY = thisHist->ProjectionY("temp", i, i);
         // Scan over the histogram
         //chose the correct number of bins based on the histogram
         float nsPerBin = (projY->GetBinCenter(projY->GetNbinsX()) - projY->GetBinCenter(1)) / projY->GetNbinsX();
         float timeWindow = 3; //ns (Full Width)
         int binWindow = int(timeWindow / nsPerBin);
         double maxEntries = 0;
         double maxMean = 0;
         for (int j = 1 ; j <= projY->GetNbinsX();j++){
            int minBin = j;
            int maxBin = (j + binWindow) <= projY->GetNbinsX() ? (j + binWindow) : projY->GetNbinsX();
            double sum = 0, nEntries = 0;
            for (int bin = minBin; bin <= maxBin; bin++){
               sum += projY->GetBinContent(bin) * projY->GetBinCenter(bin);
               nEntries += projY->GetBinContent(bin);
               if (bin == maxBin){
                  if (nEntries > maxEntries) {
                     maxMean = sum / nEntries;
                     maxEntries = nEntries;
                  }
               } 
            }
         }
         //In the case there is RF, our job is to pick just the number of the correct beam bunch, so that's really all we need.
         if(useRF) {
            int beamBucket = int((maxMean / RF_Period) + 0.5); // +0.5 to handle rounding correctly
            selectedTAGMOffset->SetBinContent(i, beamBucket);
            TAGMOffsetDistribution->Fill(beamBucket);
         }
         else{
            selectedTAGMOffset->SetBinContent(i, maxMean);
            TAGMOffsetDistribution->Fill(maxMean);
         }
      }
      double meanOffset = TAGMOffsetDistribution->GetMean();
      // This might be in units of beam bunches, so we need to convert
      if (useRF) meanOffset *= RF_Period;
      if (verbose) {
         cout << "Dumping TAGM results...\n=======================================" << endl;
         cout << "TAGM mean Offset = " << meanOffset << endl;
         cout << "fADC Offsets" << endl;
      }

      outFile.open(prefix + "tagm_adc_timing_offsets.txt", ios::out);
      //for (int i = 1 ; i <= nBinsX; i++){
      // Loop over rows
      if (verbose) cout << "Column\tRow\tvalueToUse\toldValue\tmeanOffset\tTotal" << endl;
      for (unsigned int column = 1; column <= 102; column++){
         int index = GetCCDBIndexTAGM(column, 0);
         double valueToUse = selectedTAGMOffset->GetBinContent(index);
         if (useRF) valueToUse *= RF_Period;

         //if (valueToUse == 0) valueToUse = meanOffset;
         outFile << "0 " << column << " " << valueToUse + tagm_fadc_time_offsets[index-1] - meanOffset<< endl;
         if (verbose) printf("0\t%i\t%.3f\t\t%.3f\t\t%.3f\t\t%.3f\n", column, valueToUse, tagm_fadc_time_offsets[index-1], meanOffset, 
               valueToUse + tagm_fadc_time_offsets[index-1] - meanOffset);
         if (column == 9 || column == 27 || column == 81 || column == 99){
            for (unsigned int row = 1; row <= 5; row++){
               index = GetCCDBIndexTAGM(column, row);
               valueToUse = selectedTAGMOffset->GetBinContent(index);
               if (useRF) valueToUse *= RF_Period;
               //if (valueToUse == 0) valueToUse = meanOffset;
               outFile << row << " " << column << " " << valueToUse + tagm_fadc_time_offsets[index-1] - meanOffset<< endl;
               if (verbose) printf("%i\t%i\t%.3f\t\t%.3f\t\t%.3f\t\t%.3f\n", row, column, valueToUse, tagm_fadc_time_offsets[index-1], meanOffset,
                     valueToUse + tagm_fadc_time_offsets[index-1] - meanOffset);
            }
         }
      }
      outFile.close();

      if (verbose) {
         cout << "TDC Offsets" << endl;
         cout << "Column\tRow\tvalueToUse\toldValue\tmeanOffset\tTotal" << endl;
      }
      outFile.open(prefix + "tagm_tdc_timing_offsets.txt", ios::out);
      //for (int i = 1 ; i <= nBinsX; i++){
      // Loop over rows
      for (unsigned int column = 1; column <= 102; column++){
         int index = GetCCDBIndexTAGM(column, 0);
         double valueToUse = selectedTAGMOffset->GetBinContent(index);
         if (useRF) valueToUse *= RF_Period;
         //if (valueToUse == 0) valueToUse = meanOffset;
         outFile << "0 " << column << " " << valueToUse + tagm_tdc_time_offsets[index-1] - meanOffset << endl;
         if (verbose) printf("0\t%i\t%.3f\t\t%.3f\t\t%.3f\t\t%.3f\n", column, valueToUse, tagm_tdc_time_offsets[index-1], meanOffset,
               valueToUse + tagm_tdc_time_offsets[index-1] - meanOffset);
         if (column == 9 || column == 27 || column == 81 || column == 99){
            for (unsigned int row = 1; row <= 5; row++){
               index = GetCCDBIndexTAGM(column, row);
               valueToUse = selectedTAGMOffset->GetBinContent(index);
               if (useRF) valueToUse *= RF_Period;
               //if (valueToUse == 0) valueToUse = meanOffset;
               outFile << row << " " << column << " " << valueToUse + tagm_tdc_time_offsets[index-1] - meanOffset << endl;
               if (verbose) printf("%i\t%i\t%.3f\t\t%.3f\t\t%.3f\t\t%.3f\n", row, column, valueToUse, tagm_tdc_time_offsets[index-1], meanOffset,
                     valueToUse + tagm_tdc_time_offsets[index-1] - meanOffset);
            }
         }
      }
      outFile.close();
      outFile.open(prefix + "tagm_base_time.txt", ios::out);
      if (verbose) {
         printf("TAGM ADC Base = %f - (%f) = %f\n", tagm_t_base_fadc, meanOffset, tagm_t_base_fadc - meanOffset);
         printf("TAGM TDC Base = %f - (%f) = %f\n", tagm_t_base_tdc, meanOffset, tagm_t_base_tdc - meanOffset);
      }
      outFile << tagm_t_base_fadc - meanOffset << " " << tagm_t_base_tdc - meanOffset << endl;
      outFile.close();

   }

   thisHist = ExtractTrackBasedTimingNS::Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGH - SC Target Time");
   if (useRF) thisHist = ExtractTrackBasedTimingNS::Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGH - RFBunch Time");
   if (thisHist != NULL) {
      outFile.open(prefix + "tagh_tdc_timing_offsets.txt", ios::out | ios::trunc);
      outFile.close(); // clear file
      outFile.open(prefix + "tagh_adc_timing_offsets.txt", ios::out | ios::trunc);
      outFile.close(); // clear file

      // Setup histogram for determining the most probable change in offset for each F1TDC slot
      // This is needed to account for the occasional uniform shift in offsets of the 32 counters in a slot
      const int NtdcSlots = 8;
      TH1I * tdcDist[NtdcSlots];
      for (int i = 1; i <= NtdcSlots; i++) {
         stringstream ss; ss << i;
         TString s = ss.str();
         double range = 500.0; double width = 0.1;
         int Nbins = range/width;
         double low = -0.5*range - 0.5*width;
         double high = 0.5*range - 0.5*width;
         tdcDist[i-1] = new TH1I("TAGHOffsetDistribution_"+s, "TAGH Offset (slot "+s+"); TAGH Offset [ns]; Entries", Nbins, low, high);
      }

      int nBinsX = thisHist->GetNbinsX();
      TH1D * selectedTAGHOffset = new TH1D("selectedTAGHOffset", "Selected TAGH Offset; ID; Offset [ns]", nBinsX, 0.5, nBinsX + 0.5);
      for (int i = 1 ; i <= nBinsX; i++) {
         TH1D *projY = thisHist->ProjectionY("temp", i, i);
         // Scan over histogram to find mean offset in timeWindow with largest integral
         // Choose the correct number of bins based on the histogram
         double nsPerBin = (projY->GetBinCenter(projY->GetNbinsX()) - projY->GetBinCenter(1)) / projY->GetNbinsX();
         double timeWindow = 2.0; // ns (Full Width)
         int binWindow = int(timeWindow / nsPerBin);

         double maxEntries = 0;
         double maxMean = 0;
         for (int j = 1; j <= projY->GetNbinsX(); j++) {
            int minBin = j;
            int maxBin = (j + binWindow) <= projY->GetNbinsX() ? (j + binWindow) : projY->GetNbinsX();
            double sum = 0; 
            double nEntries = 0;
            for (int bin = minBin; bin <= maxBin; bin++) {
               sum += projY->GetBinContent(bin) * projY->GetBinCenter(bin);
               nEntries += projY->GetBinContent(bin);
               if (bin == maxBin) {
                  if (nEntries > maxEntries) {
                     maxMean = sum / nEntries;
                     maxEntries = nEntries;
                  }
               }
            }
         }

         if (tagh_counter_quality[i-1] == 0.0) {
            selectedTAGHOffset->SetBinContent(i, 0);
            continue;
         }
         int tdc_slot = GetF1TDCslotTAGH(i);
         if (useRF) {
            int beamBucket;
            if (maxMean >= 0) beamBucket = int((maxMean / RF_Period) + 0.5); // +0.5 to handle rounding correctly
            else beamBucket = int((maxMean / RF_Period) - 0.5);
            selectedTAGHOffset->SetBinContent(i, beamBucket);
            if (maxEntries != 0.0) tdcDist[tdc_slot - 1]->Fill(beamBucket);
         } else {
            selectedTAGHOffset->SetBinContent(i, maxMean);
            if (maxEntries != 0.0) tdcDist[tdc_slot - 1]->Fill(maxMean);
         }
      }
      // Most probable change in offset or beam bucket per F1TDC slot
      double mpDelta[NtdcSlots];
      for (int i = 1; i <= NtdcSlots; i++) {
         int mpBin = tdcDist[i-1]->GetMaximumBin();
         mpDelta[i-1] = (mpBin > 0) ? tdcDist[i-1]->GetBinCenter(mpBin) : 0.0;
         if (useRF) mpDelta[i-1] *= RF_Period;
         if (verbose) {
            cout << "TAGH most probable Offset = " << i << ", " << mpDelta[i-1] << endl;
         }
      }

      if (verbose) {
         cout << "Dumping TAGH results...\n=======================================" << endl;
         cout << "Type\tChannel\tvalueToUse\toldValue\tmpDelta\tTotal" << endl;
      }

      double limit = 2.5; // ns
      double ccdb_sum = 0.0;
      for (int i = 1; i <= nBinsX; i++) ccdb_sum += tagh_tdc_time_offsets[i-1];
      double c1_tdcOffset = 0.0;
      outFile.open(prefix + "tagh_tdc_timing_offsets.txt");
      for (int i = 1; i <= nBinsX; i++) {
         if (tagh_counter_quality[i-1] == 0.0) {
            outFile << i << " " << 0 << endl;
            continue;
         }
         int tdc_slot = GetF1TDCslotTAGH(i);
         double delta = selectedTAGHOffset->GetBinContent(i);
         if (useRF) delta *= RF_Period;
         if (ccdb_sum > 0.0 && fabs(delta - mpDelta[tdc_slot-1]) > limit) {
            delta = mpDelta[tdc_slot-1];
         }
         double ccdb = tagh_tdc_time_offsets[i-1];
         double offset = ccdb + delta;
         if (i == 1) c1_tdcOffset = offset;
         offset -= c1_tdcOffset;
         outFile << i << " " << offset << endl;
         if (verbose) printf("TDC\t%i\t%.3f\t\t%.3f\t\t%.3f\t\t%.3f\n", i, delta, ccdb, mpDelta[tdc_slot-1], offset);
      }
      outFile.close();

      ccdb_sum = 0.0;
      for (int i = 1; i <= nBinsX; i++) ccdb_sum += tagh_fadc_time_offsets[i-1];
      double c1_adcOffset = 0.0;
      outFile.open(prefix + "tagh_adc_timing_offsets.txt");
      for (int i = 1; i <= nBinsX; i++) {
         if (tagh_counter_quality[i-1] == 0.0) {
            outFile << i << " " << 0 << endl;
            continue;
         }
         int tdc_slot = GetF1TDCslotTAGH(i);
         double delta = selectedTAGHOffset->GetBinContent(i);
         if (useRF) delta *= RF_Period;
         if (ccdb_sum > 0.0 && fabs(delta - mpDelta[tdc_slot-1]) > limit) {
            delta = mpDelta[tdc_slot-1];
         }
         double ccdb = tagh_fadc_time_offsets[i-1];
         double offset = ccdb + delta;
         if (i == 1) c1_adcOffset = offset;
         offset -= c1_adcOffset;
         outFile << i << " " << offset << endl;
         if (verbose) printf("ADC\t%i\t%.3f\t\t%.3f\t\t%.3f\t\t%.3f\n", i, delta, ccdb, mpDelta[tdc_slot-1], offset);
      }
      outFile.close();

      outFile.open(prefix + "tagh_base_time.txt");
      outFile << tagh_t_base_fadc - c1_adcOffset << " " << tagh_t_base_tdc - c1_tdcOffset << endl;
      if (verbose) {
         printf("TAGH ADC Base = %f - (%f) = %f\n", tagh_t_base_fadc, c1_adcOffset, tagh_t_base_fadc - c1_adcOffset);
         printf("TAGH TDC Base = %f - (%f) = %f\n", tagh_t_base_tdc, c1_tdcOffset, tagh_t_base_tdc - c1_tdcOffset);
      }
      outFile.close();
   }

   // We can use the RF time to calibrate the SC time (Experimental for now)
   double meanSCOffset = 0.0; // In case we change the time of the SC, we need this in this scope
   if(useRF){
      TH1F * selectedSCSectorOffset = new TH1F("selectedSCSectorOffset", "Selected TDC-RF offset;Sector; Time", 30, 0.5, 30.5);
      TH1F * selectedSCSectorOffsetDistribution = new TH1F("selectedSCSectorOffsetDistribution", "Selected TDC-RF offset;Time;Entries", 100, -3.0, 3.0);
      TF1* f = new TF1("f","pol0(0)+gaus(1)", -3.0, 3.0);
      for (int sector = 1; sector <= 30; sector++){
         TH1I *scRFHist = ExtractTrackBasedTimingNS::Get1DHistogram("HLDetectorTiming", "SC_Target_RF_Compare", Form("Sector %.2i", sector));
         if (scRFHist == NULL) continue;
         //Do the fit
         TFitResultPtr fr = scRFHist->Fit("pol0", "SQ", "", -2, 2);
         double p0 = fr->Parameter(0);

         f->FixParameter(0,p0);
         f->SetParLimits(2, -2, 2);
         f->SetParLimits(3, 0, 2);
         f->SetParameter(1, 10);
         f->SetParameter(2, scRFHist->GetBinCenter(scRFHist->GetMaximumBin()));
         f->SetParameter(3, 0);

         fr = scRFHist->Fit(f, "SQ", "", -2, 2);
         double SCOffset = fr->Parameter(2);
         selectedSCSectorOffset->SetBinContent(sector, SCOffset);
         selectedSCSectorOffsetDistribution->Fill(SCOffset);
      }
      // Now write out the offsets
      meanSCOffset = selectedSCSectorOffsetDistribution->GetMean();
      if (verbose){
         cout << "Dumping SC results...\n=======================================" << endl;
         cout << "SC mean Offset = " << meanSCOffset << endl;
         cout << "TDC Offsets" << endl;
         cout << "Sector\toldValue\tValueToUse\tmeanOffset\tTotal" << endl;
      }
      outFile.open(prefix + "sc_tdc_timing_offsets.txt");
      for (int sector = 1; sector <= 30; sector++){
         outFile << sc_tdc_time_offsets[sector-1] + selectedSCSectorOffset->GetBinContent(sector) - meanSCOffset << endl;
         if (verbose) printf("%i\t%.3f\t\t%.3f\t\t%.3f\t\t%.3f\n",sector, sc_tdc_time_offsets[sector-1], selectedSCSectorOffset->GetBinContent(sector), meanSCOffset,
               sc_tdc_time_offsets[sector-1] + selectedSCSectorOffset->GetBinContent(sector) - meanSCOffset);
      }
      outFile.close();
      if (verbose){
         cout << "ADC Offsets" << endl;
         cout << "Sector\tvalueToUse\toldValue\tmeanOffset\tTotal" << endl;
      }
      outFile.open(prefix + "sc_adc_timing_offsets.txt");
      for (int sector = 1; sector <= 30; sector++){
         outFile << sc_fadc_time_offsets[sector-1] + selectedSCSectorOffset->GetBinContent(sector) - meanSCOffset << endl;
         if (verbose) printf("%i\t%.3f\t\t%.3f\t\t%.3f\t\t%.3f\n",sector,sc_fadc_time_offsets[sector-1], selectedSCSectorOffset->GetBinContent(sector), meanSCOffset,
               sc_fadc_time_offsets[sector-1] + selectedSCSectorOffset->GetBinContent(sector) - meanSCOffset);
      }
      outFile.close();

      outFile.open(prefix + "sc_base_time.txt");
      outFile << sc_t_base_fadc - meanSCOffset << " " << sc_t_base_tdc - meanSCOffset << endl;
      if (verbose) {
         printf("SC ADC Base = %f - (%f) = %f\n", sc_t_base_fadc, meanSCOffset, sc_t_base_fadc - meanSCOffset);
         printf("SC TDC Base = %f - (%f) = %f\n", sc_t_base_tdc, meanSCOffset, sc_t_base_tdc - meanSCOffset);
      }
      outFile.close();
   }

   TH1I *this1DHist = ExtractTrackBasedTimingNS::Get1DHistogram("HLDetectorTiming", "TRACKING", "TOF - RF Time");
   if(this1DHist != NULL){
      //Gaussian
      Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
      TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 1.5, maximum + 1.5);
      float mean = fr->Parameter(1);
      outFile.open(prefix + "tof_base_time.txt");
      if (verbose) {
         printf("TOF ADC Base = %f - (%f) - (%f) = %f\n", tof_t_base_fadc, mean, meanSCOffset, tof_t_base_fadc - mean - meanSCOffset);
         printf("TOF TDC Base = %f - (%f) - (%f) = %f\n", tof_t_base_tdc, mean, meanSCOffset, tof_t_base_tdc - mean - meanSCOffset);
      }
      outFile << tof_t_base_fadc - mean - meanSCOffset<< " " << tof_t_base_tdc - mean - meanSCOffset<< endl;
      outFile.close();
   }

   this1DHist = ExtractTrackBasedTimingNS::Get1DHistogram("HLDetectorTiming", "TRACKING", "BCAL - RF Time");
   if(this1DHist != NULL){
      //Gaussian
      Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
      TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 5, maximum + 5);
      float mean = fr->Parameter(1);
      outFile.open(prefix + "bcal_base_time.txt");
      if (verbose) {
         printf("BCAL ADC Base = %f - (%f) - (%f) = %f\n", bcal_t_base_fadc, mean, meanSCOffset, bcal_t_base_fadc - mean - meanSCOffset);
         printf("BCAL TDC Base = %f - (%f) - (%f) = %f\n", bcal_t_base_tdc, mean, meanSCOffset, bcal_t_base_tdc - mean - meanSCOffset);
      }
      outFile << bcal_t_base_fadc - mean - meanSCOffset << " " << bcal_t_base_tdc - mean - meanSCOffset << endl; // TDC info not used
      outFile.close();
   }

   this1DHist = ExtractTrackBasedTimingNS::Get1DHistogram("HLDetectorTiming", "TRACKING", "FCAL - RF Time");
   if(this1DHist != NULL){
      //Gaussian
      Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
      TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 5, maximum + 5);
      float mean = fr->Parameter(1);
      outFile.open(prefix + "fcal_base_time.txt");
      if (verbose) {
         printf("FCAL ADC Base = %f - (%f) - (%f) = %f\n",fcal_t_base, mean, meanSCOffset, fcal_t_base - mean - meanSCOffset);
      }
      outFile << fcal_t_base - mean - meanSCOffset<< endl; 
      outFile.close();
   }

   this1DHist = ExtractTrackBasedTimingNS::Get1DHistogram("HLDetectorTiming", "TRACKING", "Earliest CDC Time Minus Matched SC Time");
   if(this1DHist != NULL){
      //Gaussian
      Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
      TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 15, maximum + 10);
      float mean = fr->Parameter(1);
      outFile.open(prefix + "cdc_base_time.txt");
      if (verbose) {
         printf("CDC ADC Base = %f - (%f) - (%f) = %f\n",cdc_t_base, mean, meanSCOffset, cdc_t_base - mean - meanSCOffset);
      }
      outFile << cdc_t_base - mean - meanSCOffset << endl;
      outFile.close();
   }

   // We want to account for any residual difference between the cathode and anode times.
   double FDC_ADC_Offset = 0.0, FDC_TDC_Offset = 0.0; 
   this1DHist = ExtractTrackBasedTimingNS::Get1DHistogram("HLDetectorTiming", "FDC", "FDCHit Cathode time;1");
    if(this1DHist != NULL){
        Int_t firstBin = this1DHist->FindFirstBinAbove( 1 , 1); // Find first bin with content above 1 in the histogram
        for (int i = 0; i <= 16; i++){
            if ((firstBin + i) > 0) this1DHist->SetBinContent((firstBin + i), 0);
        }
        //Fit a gaussian to the left of the main peak
        Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
        TF1 *f = new TF1("f", "gaus");
        f->SetParameters(100, maximum, 20);
        //this1DHist->Rebin(2);
        TFitResultPtr fr = this1DHist->Fit(f, "S", "", maximum - 10, maximum + 7); // Cant fix value at end of range
        double mean = fr->Parameter(1);
        float sigma = fr->Parameter(2);
        FDC_ADC_Offset = mean;
        delete f;
    }

    this1DHist = ExtractTrackBasedTimingNS::Get1DHistogram("HLDetectorTiming", "FDC", "FDCHit Wire time;1");
    if(this1DHist != NULL){
        Int_t firstBin = this1DHist->FindLastBinAbove( 1 , 1); // Find first bin with content above 1 in the histogram
        for (int i = 0; i <= 25; i++){
            if ((firstBin + i) > 0) this1DHist->SetBinContent((firstBin + i), 0);
        }
        //Fit a gaussian to the left of the main peak
        Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
        TF1 *f = new TF1("f", "gaus");
        f->SetParameters(100, maximum, 20);
        TFitResultPtr fr = this1DHist->Fit(f, "S", "", maximum - 10, maximum + 5); // Cant fix value at end of range
        double mean = fr->Parameter(1);
        float sigma = fr->Parameter(2);
        FDC_TDC_Offset = mean;
        delete f;
    }
    double FDC_ADC_TDC_Offset = FDC_ADC_Offset - FDC_TDC_Offset;

   this1DHist = ExtractTrackBasedTimingNS::Get1DHistogram("HLDetectorTiming", "TRACKING", "Earliest Flight-time Corrected FDC Time");
   if(this1DHist != NULL){
      //Landau
      Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
      TFitResultPtr fr = this1DHist->Fit("landau", "S", "", maximum - 2.5, maximum + 4);
      float MPV = fr->Parameter(1);
      outFile.open(prefix + "fdc_base_time.txt");
      if (verbose) {
         printf("FDC ADC Base = %f - (%f) - (%f) - (%f) = %f\n",fdc_t_base_fadc, MPV, meanSCOffset, FDC_ADC_TDC_Offset, fdc_t_base_fadc - MPV - meanSCOffset - FDC_ADC_TDC_Offset);
         printf("FDC TDC Base = %f - (%f) - (%f) = %f\n",fdc_t_base_tdc, MPV, meanSCOffset, fdc_t_base_tdc - MPV - meanSCOffset);
      }
      outFile << fdc_t_base_fadc - MPV - meanSCOffset - FDC_ADC_TDC_Offset << " " << fdc_t_base_tdc - MPV - meanSCOffset << endl;
      outFile.close();
   }

   ExtractTrackBasedTimingNS::thisFile->Write();
   return;
}
Esempio n. 30
0
// ----------------------------------
//======= Doing real fit and producing Fit/RMS resolution histograms =======
void projectAndFit(TH2F* th2, TH1F*& hFit, TH1F*& hRMS,int tailSign,string name, bool variableBinning,bool wait){
  TCanvas* canv = new TCanvas("tmp","tmp",500,500); canv->cd();
  //static double sigma;


  int xBins = th2->GetNbinsX();
  //cout << "xBins: " << xBins << endl; 



  //for resolution vs pt
  if(variableBinning){
    hFit = new TH1F("tmp","tmp",xBins,th2->GetXaxis()->GetXbins()->GetArray());
    hRMS = new TH1F("tmp2","tmp2",xBins,th2->GetXaxis()->GetXbins()->GetArray());
  }else{
    //for resolution vs eta
    hFit = new TH1F("tmp","tmp",xBins,th2->GetBinLowEdge(1),th2->GetBinLowEdge(xBins+1));
    hRMS = new TH1F("tmp2","tmp2",xBins,th2->GetBinLowEdge(1),th2->GetBinLowEdge(xBins+1));
  }


  for(int i=1;i<=xBins; i++){
    cout << "i,xLeft: " << i << " , " << th2->GetBinLowEdge(i) << endl;
    TH1D* proj = th2->ProjectionY("prova",i,i+1);
    if(proj->GetEntries()<20){
      //cout << "N entries < 20. Should I continue? " << endl; Wait();
      hRMS->SetBinContent(i,0);
      hRMS->SetBinError(i,0);
      hFit->SetBinContent(i,0);
      hFit->SetBinError(i,0);
      delete proj;
      continue;
    }
    double rms = proj->GetRMS();

    double tmpMean;
    double tmpSigma;


    // quick fit with standard gauss
    double leftBound,rightBound;
    if(tailSign<0){
      leftBound = -1.5*rms;
      rightBound = +1.0*rms;
      cout << "negative tailSign gives: " << leftBound << " , " << rightBound << endl;
    } else if(tailSign>0){
      leftBound = -1.0*rms;
      rightBound = +1.5*rms;
      cout << "positive tailSign gives: " << leftBound << " , " << rightBound << endl;
    }else{
      leftBound = -1.0*rms;
      rightBound = +1.0*rms;
      cout << "null tailSign gives: " << leftBound << " , " << rightBound << endl;
    }
    
    TF1* f1 = new TF1("f1","gaus",leftBound,rightBound);
    TFitResultPtr r = proj->Fit(f1,"S M R L");   
    proj->Draw(); gPad->Update(); 
    stringstream outputName;
    if(i<10)      outputName << name << "_raw_bin_" << "0" << i ; else      outputName << name << "_bin" << i ;
    //printCanvas(canv,outputName.str(),1);    
    
    if(wait) Wait();
    tmpMean = r->Parameter(1);
    tmpSigma = r->Parameter(2);    

    double xMin,xMax;
    xMin = tmpMean - tmpSigma*5.;
    xMax = tmpMean + tmpSigma*5.;



    RooRealVar x("x","x",xMin,xMax) ;

    double meanRangeMin;
    double meanRangeMax;
    if(tmpMean<0){
      meanRangeMin = 1.6*tmpMean;
      meanRangeMax = 0.1*tmpMean;
    }else{
      meanRangeMin = 0.1*tmpMean;
      meanRangeMax = 1.6*tmpMean;
    }

    RooRealVar meanRoo("mean","mean of gaussian",tmpMean,meanRangeMin,meanRangeMax) ;
    RooRealVar sigmaRoo("sigma","width of gaussian",tmpSigma,tmpSigma*0.5,tmpSigma*1.5); 

    RooRealVar a("a","a",3.,2.,10.);
    RooRealVar aDx("aDx","aDx",3.,2.,10.);
    RooRealVar n("n","n",5.,0.,10.);   
    RooRealVar nDx("nDx","nDx",5.,0.,10.);   

    if(tailSign!=0){
      if(tailSign<0){
	a.setVal(1); a.setMin(0.5); a.setMax(3.);
      }else{
	aDx.setVal(1); aDx.setMin(0.5); aDx.setMax(3.);
      }
    }


    RooDoubleCB func1("cb","cb PDF",x,meanRoo,sigmaRoo,a,n,aDx,nDx) ;
    RooPlot* xframe = x.frame(Title("Gaussian p.d.f.")) ;
    
    RooDataHist  dh("dh","dh",x,Import(*proj));
    func1.fitTo(dh);
    dh.plotOn(xframe);
    func1.plotOn(xframe) ;
    //

    xframe->Draw(); gPad->Update();
    stringstream outputName2; 
    if(i<10)      outputName2 << name << "_bin" << "0" << i ; else      outputName2 << name << "_bin" << i ;
    //printCanvas(canv,outputName2.str(),1);    
    if(wait) Wait();
    
    tmpMean = meanRoo.getVal();
    tmpSigma = sigmaRoo.getVal();
 
    double sigma;
    double sigmaErr;
    sigma= sigmaRoo.getVal();
    sigmaErr = sigmaRoo.getError();     

    /*
    proj->SetAxisRange(-5*sigma,5*sigma);
    rms = proj->GetRMS();
    double rmsErr = proj->GetRMSError();
    hFit->SetBinContent(i,sigma);
    hFit->SetBinError(i,sigmaErr);
    hRMS->SetBinContent(i,rms);
    hRMS->SetBinError(i,rmsErr);
    delete proj;
    */


    // ---- NEW IMPLEMENTATION
    double fullIntegral = proj->Integral(0,proj->GetNbinsX()+1);
    //double fullIntegral = proj->Integral();
    //double fullAverage = proj->GetMean();
    double step = proj->GetBinWidth(1);;
    int peakBin = proj->FindBin(tmpMean);

    //double range2nd(0.954);
    double range2nd(0.90);


    //
    bool found68(false);
    double range68(0), uncert68(0.);
    double range95(0), uncert95(0.);
    for(int j=0; j<proj->GetNbinsX()/2 ; j++){
      if((peakBin-j)<1 || (peakBin+j) > proj->GetNbinsX()) break;
      double fraction = proj->Integral(peakBin-j,peakBin+j)/fullIntegral;
      if(fraction>0.682 && !found68){ //2sigma range
	found68=true;
	range68 = step*(2*j+1)*0.5;
	double averageBinContent = (proj->GetBinContent(peakBin-j) + proj->GetBinContent(peakBin+j))/2.0 ; 
	uncert68 = sqrt(0.682*(1-0.682)/fullIntegral)/(averageBinContent/step/fullIntegral);
      }
      if(fraction>range2nd){ //3sigma range
	range95 = step*(2*j+1)*0.5;
	double averageBinContent = (proj->GetBinContent(peakBin-j) + proj->GetBinContent(peakBin+j))/2.0 ; 
	uncert95 = sqrt(range2nd*(1-range2nd)/fullIntegral)/(averageBinContent/step/fullIntegral);
	break;
      }
    }


    // --- OLD IMPLEMENTATION
    /*
    double fullIntegral = proj->Integral();
    double step = sigma/20.;
    //
    double range68(0);
    for(int j=2; j<20000;j++){
      xMin = tmpMean - step*j; 
      xMax = tmpMean + step*j;  
      proj->SetAxisRange(xMin,xMax);
      double fraction = proj->Integral()/fullIntegral;
      if(fraction>0.682){ //2sigma range
	range68 = step*j;
	break;
      }
    }
    //
    double range95(0);
    for(int j=2; j<20000;j++){
      xMin = tmpMean - step*j; 
      xMax = tmpMean + step*j;  
      proj->SetAxisRange(xMin,xMax);
      double fraction = proj->Integral()/fullIntegral;
      if(fraction>range2nd){ //2sigma range
	range95 = step*j;
	break;
      }
    }
    uncert68 = step;
    uncert95 = step;
    */




    //--------
    //hFit->SetBinContent(i,sigma);
    //hFit->SetBinError(i,sigmaErr);
    hFit->SetBinContent(i,range68);
    hFit->SetBinError(i,uncert68);
    hRMS->SetBinContent(i,range95);
    hRMS->SetBinError(i,uncert95);
    delete proj;


    
  }
  hFit->SetDirectory(gROOT);
  hRMS->SetDirectory(gROOT);
  delete canv;
  //hFit->Draw();gPad->Update(); Wait();
}