Esempio n. 1
0
double extractLimitAtQuantile(TString inFileName, TString plotName, double d_quantile ){
	TFile *f = TFile::Open(inFileName);
	TF1 *expoFit = new TF1("expoFit","[0]*exp([1]*(x-[2]))", rMin, rMax);
	TGraphErrors *limitPlot_ =  new TGraphErrors();

/* 	bool done = false; */
	if (_debug > 0) std::cout << "Search for upper limit using pre-computed grid of p-values" << std::endl;

	readAllToysFromFile(limitPlot_, f, d_quantile ); 
	f->Close();
	limitPlot_->Sort();
	double minDist=1e3;
	int n= limitPlot_->GetN();
	cout<<" Number of points in limitPlot_ : "<<n<<endl;
	if(n<=0) return 0;

	clsMin.first=0;
	clsMin.second=0;
	clsMax.first=0;
	clsMax.second=0;

	limit = 0; limitErr = 0;
	for (int i = 0; i < n; ++i) {
		double x = limitPlot_->GetX()[i], y = limitPlot_->GetY()[i]; //, ey = limitPlot_->GetErrorY(i);
		if (fabs(y-clsTarget) < minDist) { limit = x; minDist = fabs(y-clsTarget); }
	}
	int ntmp =0;
	for (int j = 0; j < n; ++j) {
		int i = n-j-1;
		double x = limitPlot_->GetX()[i], y = limitPlot_->GetY()[i], ey = limitPlot_->GetErrorY(i);
		if (y-3*ey >= clsTarget && ntmp<=2) { 
			rMin = x; clsMin = CLs_t(y,ey); 
			ntmp ++ ;
		}
	}
	ntmp =0;
	for (int i = 0; i < n; ++i) {
		double x = limitPlot_->GetX()[i], y = limitPlot_->GetY()[i], ey = limitPlot_->GetErrorY(i);
		if (y+3*ey <= clsTarget && ntmp<=2) {
		       	rMax = x; clsMax = CLs_t(y,ey);
			ntmp ++ ;
		}
	}
	if((clsMin.first==0 and clsMin.second==0) )
	{
		rMin = limitPlot_->GetX()[0]; clsMin=CLs_t(limitPlot_->GetY()[0], limitPlot_->GetErrorY(0)); 
	}
	if((clsMax.first==0 and clsMax.second==0))
	{
		rMax = limitPlot_->GetX()[n-1]; clsMax=CLs_t(limitPlot_->GetY()[n-1], limitPlot_->GetErrorY(n-1));
	}

	if (_debug > 0) std::cout << " after scan x ~ " << limit << ", bounds [ " << rMin << ", " << rMax << "]" << std::endl;
	limitErr = std::max(limit-rMin, rMax-limit);
	expoFit->SetRange(rMin,rMax);
	//expoFit.SetRange(limitPlot_->GetXaxis()->GetXmin(),limitPlot_->GetXaxis()->GetXmax());
	//expoFit->SetRange(1.7,2.25);

	if (limitErr < std::max(rAbsAccuracy_, rRelAccuracy_ * limit)) {
		if (_debug > 1) std::cout << "  reached accuracy " << limitErr << " below " << std::max(rAbsAccuracy_, rRelAccuracy_ * limit) << std::endl;
/* 		done = true;  */
	}

	//if (!done) { // didn't reach accuracy with scan, now do fit
	if (1) { // didn't reach accuracy with scan, now do fit
		if (_debug) {
			std::cout << "\n -- HybridNew, before fit -- \n";
			std::cout << "Limit: r" << " < " << limit << " +/- " << limitErr << " [" << rMin << ", " << rMax << "]\n";

			std::cout<<"rMin="<<rMin<<" clsMin="<<clsMin.first<<",  rMax="<<rMax<<" clsMax="<<clsMax.first<<endl;
		}

		expoFit->FixParameter(0,clsTarget);
		expoFit->SetParameter(1,log(clsMax.first/clsMin.first)/(rMax-rMin));
		expoFit->SetParameter(2,limit);
		double rMinBound, rMaxBound; expoFit->GetRange(rMinBound, rMaxBound);
		limitErr = std::max(fabs(rMinBound-limit), fabs(rMaxBound-limit));
		int npoints = 0; 
		for (int j = 0; j < limitPlot_->GetN(); ++j) { 
			if (limitPlot_->GetX()[j] >= rMinBound && limitPlot_->GetX()[j] <= rMaxBound) npoints++; 
		}
		for (int i = 0, imax = 0; i <= imax; ++i, ++npoints) {
			limitPlot_->Sort();
			limitPlot_->Fit(expoFit,(_debug <= 1 ? "QNR EX0" : "NR EXO"));
			if (_debug) {
				std::cout << "Fit to " << npoints << " points: " << expoFit->GetParameter(2) << " +/- " << expoFit->GetParError(2) << std::endl;
			}

			// only when both  "cls+3e<0.05 and cls-3e>0.05" are satisfied, we require below ...
			//	if ((rMin < expoFit->GetParameter(2))  && (expoFit->GetParameter(2) < rMax) && (expoFit->GetParError(2) < 0.5*(rMaxBound-rMinBound))) { 
			// sanity check fit result
			limit = expoFit->GetParameter(2);
			limitErr = expoFit->GetParError(2);
			if (limitErr < std::max(rAbsAccuracy_, rRelAccuracy_ * limit)) break;
			//	}
		} 
	}

	if (limitPlot_) {
		TCanvas *c1 = new TCanvas("c1","c1");
		limitPlot_->Sort();
		limitPlot_->SetLineWidth(2);
		double rMinBound, rMaxBound; expoFit->GetRange(rMinBound, rMaxBound);
		if(bPlotInFittedRange){
			limitPlot_->GetXaxis()->SetRangeUser(rMinBound, rMaxBound);
			limitPlot_->GetYaxis()->SetRangeUser(0.5*clsTarget, 1.5*clsTarget);
		}
		limitPlot_->Draw("AP");
		expoFit->Draw("SAME");
		TLine line(limitPlot_->GetX()[0], clsTarget, limitPlot_->GetX()[limitPlot_->GetN()-1], clsTarget);
		line.SetLineColor(kRed); line.SetLineWidth(2); line.Draw();
		line.DrawLine(limit, 0, limit, limitPlot_->GetY()[0]);
		line.SetLineWidth(1); line.SetLineStyle(2);
		line.DrawLine(limit-limitErr, 0, limit-limitErr, limitPlot_->GetY()[0]);
		line.DrawLine(limit+limitErr, 0, limit+limitErr, limitPlot_->GetY()[0]);
		limitPlot_->SetTitle(";#mu;CLs");
		c1->Print(plotName+".gif");
		c1->Print(plotName+".root");

		if(_debug)limitPlot_->Print("v");
	}

	std::cout << "\n -- Hybrid New -- \n";
	if(limit<0) { limit=0; cout<<"  WARNING: fitted limit <0,   need more toys and more points of signal strength"<<endl; }
	std::cout << "Limit: r" << " < " << limit << " +/- " << limitErr << " @ " << (1-clsTarget) * 100 << "% CL\n";
	return limit;
}
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;
}
void UpsilonMassFit_PolWeights(int iSpec = 3, int PutWeight=1)
{

  double PtCut=4;

  //minbias integrated, |y|<1.2 and |y|\in[1.2,2.4], centrality [0,10][10,20][20,100]%,  pt [0,6.5], [6.5, 10] [10,20]

  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameFillColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadBorderSize(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetOptTitle(1); // at least most of the time
  gStyle->SetOptStat(1); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(1); // set to 1 only if you want to display fit results

  //==================================== Define Histograms====================================================
  ofstream dataFile(Form("Eff_Upsilon.txt"));
  
  TH1D *diMuonsInvMass_Gen = new TH1D("diMuonsInvMass_Gen","diMuonsInvMass_Gen", 100,8.0,12.0);
  TH1D *diMuonsPt_Gen = new TH1D("diMuonsPt_Gen","diMuonsPt_Gen", 100,0,30);
  //Rapidity Gen
  TH1D *diMuonsRap_Gen0 = new TH1D("diMuonsRap_Gen0","diMuonsRap_Gen0", 100,-5,5);
  TH1D *diMuonsRap_Gen1 = new TH1D("diMuonsRap_Gen1","diMuonsRap_Gen1", 100,-5,5);
  TH1D *diMuonsRap_Gen2 = new TH1D("diMuonsRap_Gen2","diMuonsRap_Gen2", 100,-5,5);
  TH1D *diMuonsRap_Gen3 = new TH1D("diMuonsRap_Gen3","diMuonsRap_Gen3", 100,-5,5);
  TH1D *diMuonsRap_Gen4 = new TH1D("diMuonsRap_Gen4","diMuonsRap_Gen4", 100,-5,5);
  TH1D *diMuonsRap_Gen5 = new TH1D("diMuonsRap_Gen5","diMuonsRap_Gen5", 100,-5,5);
  ////Rapidity Reco
  TH1D *diMuonsRap_Rec0 = new TH1D("diMuonsRap_Rec0","diMuonsRap_Rec0", 100,-5,5);
  diMuonsRap_Rec0->SetLineColor(2);
  TH1D *diMuonsRap_Rec1 = new TH1D("diMuonsRap_Rec1","diMuonsRap_Rec1", 100,-5,5);
  diMuonsRap_Rec1->SetLineColor(2);
  TH1D *diMuonsRap_Rec2 = new TH1D("diMuonsRap_Rec2","diMuonsRap_Rec2", 100,-5,5);
  diMuonsRap_Rec2->SetLineColor(2);
  TH1D *diMuonsRap_Rec3 = new TH1D("diMuonsRap_Rec3","diMuonsRap_Rec3", 100,-5,5);
  diMuonsRap_Rec3->SetLineColor(2);
  TH1D *diMuonsRap_Rec4 = new TH1D("diMuonsRap_Rec4","diMuonsRap_Rec4", 100,-5,5);
  diMuonsRap_Rec4->SetLineColor(2);
  TH1D *diMuonsRap_Rec5 = new TH1D("diMuonsRap_Rec5","diMuonsRap_Rec5", 100,-5,5);
  diMuonsRap_Rec5->SetLineColor(2);
  TH1D *Bin_Gen = new TH1D("Bin_Gen","Bin_Gen", 40,0,40);

  //==============================================Define AccEff Stuff here===========================================
  // Pt bin sizes
  int Nptbin=1;
  double pt_bound[100] = {0};
  if(iSpec == 1) { 
    Nptbin = 5;
    pt_bound[0] = 0;
    pt_bound[1] = 20.0;
    pt_bound[2] = 0.0;
    pt_bound[3] = 6.5;
    pt_bound[4] = 10.0;
    pt_bound[5] = 20.0;
   

    pt_bound[6] = 30.0;
    pt_bound[7] = 35;
    pt_bound[8] = 40;
    pt_bound[9] = 45;
    pt_bound[10] = 50;
  }
  
  if(iSpec == 2) { 
    Nptbin = 2;
    pt_bound[0] = 0.0; 
    pt_bound[1] = 1.2; 
    pt_bound[2] = 2.4; 
    
    pt_bound[3] = 0.0; 
    pt_bound[4] = 0.8; 
    pt_bound[5] = 1.8; 
    //pt_bound[7] = 2.0; 
    pt_bound[6] = 2.4; 
  
  }
  
  
  if(iSpec == 3) {
    Nptbin = 3;
    //for plots
    pt_bound[0] = 0.0;//0
    pt_bound[1] = 4.0;//10
    pt_bound[2] = 8.0;//20
    pt_bound[3] = 40.0;//100
   

    //pt_bound[4] = 16.0;//50
    //pt_bound[5] = 20.0;//100
    //pt_bound[6] = 24.0;
    //pt_bound[7] = 32.0;
    //pt_bound[8] = 40.0;
    //pt_bound[9] = 40.0;
  }
  //X Axis error on Eff graph 
  double PT[100], DelPT[100], mom_err[100];
  for (Int_t ih = 0; ih < Nptbin; ih++) {
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = pt_bound[ih+1] - pt_bound[ih];
    mom_err[ih] = DelPT[ih]/2.0;
  }
  
  double genError, recError;
  double gen_pt[100]={0}, gen_ptError[100]={0}; 
  double rec_pt[100]={0}, rec_ptError[100]={0}; 
  double Eff_cat_1[100]={0},Err_Eff_cat_1[100]={0};  
  
  // Histogram arrays
  TH1D *diMuonsInvMass_GenA[10][1000];
  TH1D *diMuonsInvMass_RecA[10][1000];
  TH1D *diMuonsPt_GenA[10][1000];
  TH1D *diMuonsPt_RecA[10][1000];
  char nameGen[10][500], nameRec[10][500], nameGenPt[10][500], nameRecPt[10][500];
 
  
  for (int ifile = 0; ifile <= 5; ifile++) {
    for (Int_t ih = 0; ih < Nptbin; ih++) {
      sprintf(nameGen[ifile],"DiMuonMassGen_pt_%d_%d",ih,ifile);
      sprintf(nameRec[ifile],"DiMuonMassRec_pt_%d_%d",ih,ifile);

      sprintf(nameGenPt[ifile],"DiMuonPtGen_pt_%d_%d",ih,ifile);
      sprintf(nameRecPt[ifile],"DiMuonPtRec_pt_%d_%d",ih,ifile);
      
      diMuonsInvMass_GenA[ifile][ih]= new TH1D(nameGen[ifile],nameGen[ifile],  100,8.0,12.0); //for eff Gen;
      diMuonsInvMass_GenA[ifile][ih]->Sumw2();
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerStyle(7);
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_GenA[ifile][ih]->SetLineColor(4);

      diMuonsInvMass_RecA[ifile][ih] = new TH1D(nameRec[ifile],nameRec[ifile], 100,8.0,12.0); //for eff Rec;
      diMuonsInvMass_RecA[ifile][ih]->Sumw2();
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerStyle(8);
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_RecA[ifile][ih]->SetLineColor(4);


      diMuonsPt_GenA[ifile][ih]= new TH1D(nameGenPt[ifile],nameGenPt[ifile],  100,0,40); //for eff Gen;
      diMuonsPt_RecA[ifile][ih]= new TH1D(nameRecPt[ifile],nameRecPt[ifile],  100,0,40); //for eff Rec;
    }
  }
  
  //===========================================Input Root File============================================================
  char fileName[10][500];
  //0.0380228 	0.0480769 	0.0293255 	0.0125156 	0.00336587 	0.00276319*2/5 = 0.001105276
  //Scales
  double scale[10]={0};  
  scale[0]=(6.8802); // pT [0-3]
  scale[1]=(8.6995); // pT [3-6]
  scale[2]=(5.3065); // pT [6-9]
  scale[3]=(2.2647); // pT [9-12] 
  scale[4]=(3.0453); // pT [12-15] 
  scale[5]=(1.0000); // pT [15-30]
  
  sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03_N.root");
  sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36_N.root");
  sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69_N.root");
  sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912_N.root");
  sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215_N.root");
  sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530_N.root");



  //double scale[10]={0};  
  //scale[0]=(0.0380228/0.001105276);
  //scale[1]=(0.0480769/0.001105276);
  //scale[2]=(0.0293255/0.001105276);
  //scale[3]=(0.0125156/0.001105276);
  //scale[4]=(0.00336587/0.001105276);
  //scale[5]=(0.001105276/0.001105276);
   //34.55 , 43.70 , 26.65 , 11.37 , 3.05 , 1
  //sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03.root");
  //sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36.root");
  //sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69.root");
  //sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912.root");
  //sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215.root");
  //sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530.root");
  
  TFile *infile;
  TTree *tree;
  TTree *gentree;
  
  //===========File loop ======================
  
  for(int ifile =0; ifile<=5; ifile++){
    
    infile=new TFile(fileName[ifile],"R");
    tree=(TTree*)infile->Get("SingleMuonTree");
    gentree=(TTree*)infile->Get("SingleGenMuonTree");
    
    //Event variables
    int eventNb,runNb,lumiBlock, gbin, rbin;
    //Jpsi Variables
    Double_t JpsiMass,JpsiPt,JpsiPx,JpsiPy,JpsiPz,JpsiRap, JpsiCharge,JpsiE;
    Double_t JpsiVprob;
    //2.) muon variables RECO                                                                       
    double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt,muPosP,muPosPhi;
    double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt,muNegP,muNegPhi;
    //(1).Positive Muon                                     
    double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
    int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
    bool muPos_matches,muPos_tracker;
    //(2).Negative Muon                                     
    double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
    int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
    bool muNeg_matches,muNeg_tracker;
    //Gen Level variables
    //Gen JPsi Variables
    double GenJpsiMass, GenJpsiPt, GenJpsiRap;
    double GenJpsiPx, GenJpsiPy, GenJpsiPz, GenJpsiE;
   
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;

    //Event variables
    tree->SetBranchAddress("eventNb",&eventNb);
    tree->SetBranchAddress("runNb",&runNb);
    tree->SetBranchAddress("lumiBlock",&lumiBlock);
    
    //Jpsi Variables
    tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
    tree->SetBranchAddress("JpsiMass",&JpsiMass);
    tree->SetBranchAddress("JpsiPt",&JpsiPt);
    tree->SetBranchAddress("JpsiPx",&JpsiPx);
    tree->SetBranchAddress("JpsiPy",&JpsiPy);
    tree->SetBranchAddress("JpsiPz",&JpsiPz);
    tree->SetBranchAddress("JpsiRap",&JpsiRap);
    tree->SetBranchAddress("JpsiVprob",&JpsiVprob);
    tree->SetBranchAddress("rbin",&rbin);
    
    //muon variable
    tree->SetBranchAddress("muPosPx",&muPosPx);
    tree->SetBranchAddress("muPosPy",&muPosPy);
    tree->SetBranchAddress("muPosPz",&muPosPz);
    tree->SetBranchAddress("muPosEta",&muPosEta);
    tree->SetBranchAddress("muPosPhi",&muPosPhi);
    tree->SetBranchAddress("muNegPx", &muNegPx);
    tree->SetBranchAddress("muNegPy",    &muNegPy);
    tree->SetBranchAddress("muNegPz",    &muNegPz);
    tree->SetBranchAddress("muNegEta",    &muNegEta);
     tree->SetBranchAddress("muNegPhi", &muNegPhi);

    //1). Positive Muon
    tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
    tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
    tree->SetBranchAddress("muPos_dz", &muPos_dz);
    tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
    tree->SetBranchAddress("muPos_found", &muPos_found);
    tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
    tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
    tree->SetBranchAddress("muPos_matches", &muPos_matches);
    tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
    tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);  
    
    //2). Negative Muon                                                                            
    tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
    tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
    tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
    tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
    tree->SetBranchAddress("muNeg_found", &muNeg_found);
    tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
    tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
    tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
    tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
    tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
    



//====================================Gen Variables=========================================================
    //Gen Jpsi Variables
    gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
    gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
    gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
    gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
    gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
    gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
    gentree->SetBranchAddress("gbin",&gbin);
    //muon variable
    gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
    gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
    gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
    gentree->SetBranchAddress("GenmuPosEta",    &GenmuPosEta);
     gentree->SetBranchAddress("GenmuPosPhi",    &GenmuPosPhi);
    gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
    gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
    gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
    gentree->SetBranchAddress("GenmuNegEta",    &GenmuNegEta);
    gentree->SetBranchAddress("GenmuNegPhi",    &GenmuNegPhi);

    //====================================================== Gen tree loop ================================================
    int NAccep=0;
    int nGenEntries=gentree->GetEntries();
    cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ========="<<endl;
    //dataFile<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ====="<<endl;
    
    
    for(int i=0; i< nGenEntries; i++)  {	    
      gentree->GetEntry(i);
      
      if(i%1000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl; 
      }
      
      bool GenPosIn=0, GenNegIn=0,GenPosPass=0,GenNegPass=0;

      GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
      GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 
      
      GenJpsiE= TMath::Sqrt( GenJpsiPx*GenJpsiPx+GenJpsiPy*GenJpsiPy+GenJpsiPz*GenJpsiPz + 9.46*9.46);


      
      //============================ calculate Pol weight ========================================================================================= //
      Float_t w1,w2,w3,w4,w5;
      // this is the beam energy: 2760GeV->/2->1380GeV each beam
      // the mp=0.938272 is the mass of the proton, as we are looking at p+p collisions
      double E=1380; double pz = sqrt(E*E - 0.938272*0.938272);
      TLorentzVector h1; // beam 1
      TLorentzVector h2; // beam 2
     
      TLorentzVector genJpsi;    // generated upsilon (mother of the single muons) --> if you look at jpsi-> genJpsi (prompt or non-prompt)
      TLorentzVector genMuPlus,genMuMinus; // generator positive muon (charge=+1)
      
      //int mp;
      Float_t cosThetaStarHel; // cosTheta in the Helicity frame
      Float_t cosThetaStarCS;  // cosTheta in the Collins-Soper frame
      TVector3 zCS;             // collins-soper variable

      // put the coordinates of the parent in a TLorentzVector
      // ATTENTION: the last coordinate is the MASS of the parent, which in this case, since it's about Upsilon, it's 9.46
      // when you'll do this for Jpsi, this value has to change to m_jpsi=3.097
      genJpsi.SetPxPyPzE(GenJpsiPx, GenJpsiPy, GenJpsiPz, GenJpsiE); 
      TLorentzRotation boost(-genJpsi.BoostVector()); // boost it
   
      // put the muon in a LorentzVector
      genMuPlus.SetPtEtaPhiM(GenmuPosPt, GenmuPosEta, GenmuPosPhi, 0.106);
      genMuPlus *= boost; // boost it
      
      //genMuMinus.SetPtEtaPhiM(GenmuNegPt, GenmuNegEta, GenmuNegPhi, 0.106);
      //genMuMinus *= boost; // boost it


      //and get the cosTheta in the helicity frame
      cosThetaStarHel = genMuPlus.Vect().Dot(genJpsi.Vect())/(genMuPlus.Vect().Mag()*genJpsi.Vect().Mag());
     
      //int genMuCharge = 1;
      //int mp = genMuCharge>0 ? 0 : 1;
      //cout << genMuCharge << "     " << mp << endl;


      h1.SetPxPyPzE(0,0,pz,E);  // TLorentzVector for beam 1
      h2.SetPxPyPzE(0,0,-pz,E); //  TLorentzVector for beam 2
      h1*=boost;
      h2*=boost;
      // calculate cosTheta CS

      zCS = ( h1.Vect().Unit() - h2.Vect().Unit() ).Unit();
      cosThetaStarCS = genMuPlus.Vect().Dot(zCS)/genMuPlus.Vect().Mag();

      // setup the weights
      w1 = 1;
      w2 = 1 + cosThetaStarHel*cosThetaStarHel;
      w3 = 1 - cosThetaStarHel*cosThetaStarHel;
      w4 = 1 + cosThetaStarCS*cosThetaStarCS;
      w5 = 1 - cosThetaStarCS*cosThetaStarCS;
      

      //w5=1; 

      // cout<<" gen "<<w2<<"   "<<w3<<"  "<<w4<<"  "<<w5<<endl;

      //==============================================================================================================================================//


    
      diMuonsInvMass_Gen->Fill(GenJpsiMass);
      diMuonsPt_Gen->Fill(GenJpsiPt);
 
      if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
      if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}
  

    
      if(GenPosIn && GenNegIn ) NAccep++;
      
      if(GenPosIn==1 && GenmuPosPt>PtCut ) {GenPosPass=1;}
      if(GenNegIn==1 && GenmuNegPt>PtCut ) {GenNegPass=1;}

      double GenCenWeight=0,GenWeight=0;
      GenCenWeight=FindCenWeight(gbin);
      Bin_Gen->Fill(gbin);
      GenWeight=GenCenWeight*scale[ifile];
      if(PutWeight==0){GenWeight=1;}

      if(GenPosIn && GenNegIn){
	if(ifile==0){diMuonsRap_Gen0->Fill(GenJpsiRap);}
	if(ifile==1){diMuonsRap_Gen1->Fill(GenJpsiRap);}
	if(ifile==2){diMuonsRap_Gen2->Fill(GenJpsiRap);}
	if(ifile==3){diMuonsRap_Gen3->Fill(GenJpsiRap);}
	if(ifile==4){diMuonsRap_Gen4->Fill(GenJpsiRap);}
	if(ifile==5){diMuonsRap_Gen5->Fill(GenJpsiRap);}
      }
 

      for (Int_t ih = 0; ih < Nptbin; ih++) {
	//adding pT of all pt bins to see diss is cont
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 ) && (GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsPt_GenA[ifile][ih]->Fill(GenJpsiPt,GenWeight*w5);}
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 )&&(GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
	if(iSpec == 2)  if((GenPosPass==1 && GenNegPass==1) &&  (GenJpsiPt<20.0) && (TMath::Abs(GenJpsiRap) > pt_bound[ih] && TMath::Abs(GenJpsiRap) <=pt_bound[ih+1] )){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
	if(iSpec == 3)  if( (GenPosPass==1 && GenNegPass==1) && (GenJpsiPt < 20.0) &&  (TMath::Abs(GenJpsiRap)<2.4 ) && (gbin>=pt_bound[ih] && gbin<pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
      

      }

    }//gen loop end
    
    cout<<" accepted no "<< NAccep<<endl;
    //dataFile<<" accepted no "<< NAccep<<endl;
     
    //   new TCanvas;
    //diMuonsInvMass_Gen->Draw();
    //gPad->Print("plots/diMuonsInvMass_Gen.png");
    
    //new TCanvas;
    //diMuonsPt_Gen->Draw();
    //gPad->Print("plots/diMuonsPt_Gen.png");
  
    //new TCanvas;
    //diMuonsRap_Gen0->Draw();
    //sprintf(PlotName,"plots/diMuonsRap_Gen_%d.pdf",ifile);   
    //gPad->Print(PlotName);
    
    //new TCanvas;
    //Bin_Gen->Draw();
    //gPad->Print("plots/Bin_Gen.png");
    
  

    //=============== Rec Tree Loop ==============================================================================
    
    int nRecEntries=tree->GetEntries();
    cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
    //dataFile<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<<endl;
    
    for(int i=0; i<nRecEntries; i++)  {	    
      tree->GetEntry(i);
      if(i%100000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
	cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<endl; 
      }
      
      bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
      muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
      muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
      muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
      muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 
    
      
      JpsiE= TMath::Sqrt(JpsiPx*JpsiPx+JpsiPy*JpsiPy+JpsiPz*JpsiPz + JpsiMass*JpsiMass);
      //============================ calculate Pol weight rec ========================================================================================= //
      Float_t w1=0,w2=0,w3=0,w4=0,w5=0;
      double E=1380; double pz = sqrt(E*E - 0.938272*0.938272);
      TLorentzVector h1; // beam 1
      TLorentzVector h2; // beam 2
      
      TLorentzVector Jpsi;    
      TLorentzVector MuPlus;       
      Float_t cosThetaStarHel; // cosTheta in the Helicity frame
      Float_t cosThetaStarCS;  // cosTheta in the Collins-Soper frame
      TVector3 zCS;             // collins-soper variable
      
      Jpsi.SetPxPyPzE(JpsiPx, JpsiPy, JpsiPz, JpsiE); 
      TLorentzRotation boost(-Jpsi.BoostVector()); // boost it
      
      // put the muon in a LorentzVector
      MuPlus.SetPtEtaPhiM(muPosPt, muPosEta, muPosPhi, 0.106);
      MuPlus *= boost; // boost it
      //and get the cosTheta in the helicity frame
      cosThetaStarHel = MuPlus.Vect().Dot(Jpsi.Vect())/(MuPlus.Vect().Mag()*Jpsi.Vect().Mag());
      h1.SetPxPyPzE(0,0,pz,E);  // TLorentzVector for beam 1
      h2.SetPxPyPzE(0,0,-pz,E); //  TLorentzVector for beam 2
      h1*=boost;
      h2*=boost;
      zCS = ( h1.Vect().Unit() - h2.Vect().Unit() ).Unit();
      cosThetaStarCS = MuPlus.Vect().Dot(zCS)/MuPlus.Vect().Mag();
      // setup the weights
      w1 = 1;
      w2 = 1 + cosThetaStarHel*cosThetaStarHel;
      w3 = 1 - cosThetaStarHel*cosThetaStarHel;
      w4 = 1 + cosThetaStarCS*cosThetaStarCS;
      w5 = 1 - cosThetaStarCS*cosThetaStarCS;
      


      //w5=1;
      //cout<<" rec "<<w2<<"   "<<w3<<"  "<<w4<<"  "<<w5<<endl; 
      //================================================== Pol weights  ===============================================================================//
      
      if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
      if(IsAccept(muNegPt, muNegEta)){NegIn=1;}



      if(muPos_found > 10 && muPos_pixeLayers > 0 && muPos_nchi2In < 4.0 && muPos_dxy < 3 && muPos_dz < 15 && muPos_nchi2Gl < 20 &&  muPos_arbitrated==1 && muPos_tracker==1){PosPass=1;}	  
      
      if(muNeg_found >10 && muNeg_pixeLayers >0 && muNeg_nchi2In <4.0 && muNeg_dxy < 3 && muNeg_dz < 15 && muNeg_nchi2Gl < 20 && muNeg_arbitrated==1 && muNeg_tracker==1){NegPass=1;}

      // cout<<muPos_matches<<"  "<<muNeg_matches<<endl;
      
      if((muPosPt > PtCut && muNegPt > PtCut) && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1 )  &&   (PosPass==1 && NegPass==1)){AllCut=1;}
    
      double RecCenWeight=0,RecWeight=0;
      RecCenWeight=FindCenWeight(rbin);
      RecWeight=RecCenWeight*scale[ifile];
      if(PutWeight==0){RecWeight=1;}
     
      if(i%100000==0){
	cout<<" eff loop for reco "<<endl;
      }
      
      if(AllCut==1){
	if(ifile==0){diMuonsRap_Rec0->Fill(JpsiRap);}
	if(ifile==1){diMuonsRap_Rec1->Fill(JpsiRap);}
	if(ifile==2){diMuonsRap_Rec2->Fill(JpsiRap);}
	if(ifile==3){diMuonsRap_Rec3->Fill(JpsiRap);}
	if(ifile==4){diMuonsRap_Rec4->Fill(JpsiRap);}
	if(ifile==5){diMuonsRap_Rec5->Fill(JpsiRap);}
      }

      //Eff loop for reco
      if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {
	for (Int_t ih = 0; ih < Nptbin; ih++) {
	  //to see cont reco pT
	  if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap) < 2.4) && (JpsiPt>pt_bound[ih] && JpsiPt<=pt_bound[ih+1])) {diMuonsPt_RecA[ifile][ih]->Fill(JpsiPt,RecWeight*w5);}
	  
	  if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap)<2.4 ) && (JpsiPt > pt_bound[ih] && JpsiPt <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass, RecWeight*w5);}
	  if(iSpec == 2) if( (AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) > pt_bound[ih] && TMath::Abs(JpsiRap) <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight*w5);}
	  if(iSpec == 3) if((AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) < 2.4) && (rbin>=pt_bound[ih] &&  rbin < pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight*w5);}
	



	}
      }
    }
  
    /*
    new TCanvas;
    if(ifile==0){diMuonsRap_Gen0->Draw();new TCanvas; diMuonsRap_Rec0->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen0.png");}
    if(ifile==1){diMuonsRap_Gen1->Draw();new TCanvas; diMuonsRap_Rec1->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen1.png");}
    if(ifile==2){diMuonsRap_Gen2->Draw();new TCanvas; diMuonsRap_Rec2->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen2.png");}
    if(ifile==3){diMuonsRap_Gen3->Draw();new TCanvas; diMuonsRap_Rec3->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen3.png");}
    if(ifile==4){diMuonsRap_Gen4->Draw();new TCanvas; diMuonsRap_Rec4->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen4.png");}
    if(ifile==5){diMuonsRap_Gen5->Draw();new TCanvas; diMuonsRap_Rec5->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen5.png");}
    */
  }  // file loop ends 

  ///////////////////////////////////////////////////////////////////

  cout<< " adding "<<endl;
  TH1D *diMuonsInvMass_RecA1[100];
  TH1D *diMuonsInvMass_GenA1[100];
  TH1D *diMuonsPt_GenA1[100];
  TH1D *diMuonsPt_RecA1[100];
  TF1 *backfun_1;
  char namePt_1B[500];//for bkg func
 
  for(Int_t ih = 0; ih < Nptbin; ih++){
    diMuonsInvMass_RecA1[ih] = diMuonsInvMass_RecA[0][ih];
    diMuonsInvMass_GenA1[ih] = diMuonsInvMass_GenA[0][ih];
    diMuonsPt_GenA1[ih] = diMuonsPt_GenA[0][ih];
    diMuonsPt_RecA1[ih] = diMuonsPt_RecA[0][ih];
    
    for (int ifile = 1; ifile <= 5; ifile++) {
      diMuonsInvMass_RecA1[ih]->Add(diMuonsInvMass_RecA[ifile][ih]);
      diMuonsInvMass_GenA1[ih]->Add(diMuonsInvMass_GenA[ifile][ih]);     
      
      diMuonsPt_GenA1[ih]->Add(diMuonsPt_GenA[ifile][ih]); 
      diMuonsPt_RecA1[ih]->Add(diMuonsPt_RecA[ifile][ih]); 
    }
  }
  
  //===========================Fitting===================================================================//
  // Fit ranges
  double mass_low, mass_high;
  double MassUpsilon, WeidthUpsilon;
  
  // Low mass range upsilon width 54 KeV
  MassUpsilon = 9.46; WeidthUpsilon = 0.055;
  //MassUpsilon = 9.46; WeidthUpsilon = 0.068;
  mass_low = 9.0; mass_high = 10.0;  // Fit ranges
  
  // Fit Function crystall ball
  TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,8.0,12.0,6);
  GAUSPOL->SetParNames("Yield (#Upsilon)","BinWidth","Mean","Sigma","#alpha","n");
  GAUSPOL->SetParameter(2, MassUpsilon);
  GAUSPOL->SetParameter(3, WeidthUpsilon);
  //GAUSPOL->SetParLimits(3, 0.1*WeidthUpsilon,2.0*WeidthUpsilon);
  GAUSPOL->SetParameter(4, 1.0);
  GAUSPOL->SetParameter(5, 20.0);
  GAUSPOL->SetLineWidth(2.0);
  GAUSPOL->SetLineColor(2);




  //=====================Loop for eff===========================================================
  double GenNo[100]={0};
  double Eff[100]={0};
  double GenError[100]={0};
  double RecError[100]={0};
  double errEff_cat_S1[100]={0};
  double errEff_cat_S2[100]={0};
  double errEff_cat_S1_1[100]={0},errEff_cat_S1_2[100]={0};
  double errEff_cat_S2_1[100]={0},errEff_cat_S2_2[100]={0};
  char PlotName[500],PlotName1[500], PlotName2[500]; 
  char GPlotName[500],GPlotName1[500], GPlotName2[500];

  for (Int_t ih = 0; ih < Nptbin; ih++) {
   
    cout<<" no of gen dimuons from diMuons Pt histo    "<<diMuonsPt_GenA1[ih]->Integral(1,100)<<endl;
    cout<<" no of gen dimuons from diMuons Mass histo  "<<diMuonsInvMass_GenA1[ih]->Integral(1,100)<<endl;
    

    //from pT histogram
    //gen_pt[ih] =diMuonsPt_GenA1[ih]->IntegralAndError(1,100,genError);
   
    gen_pt[ih] = diMuonsInvMass_GenA1[ih]->IntegralAndError(1,100,genError);
    gen_ptError[ih]= genError;
    
    if(iSpec==1) sprintf(PlotName,"plots/DiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(PlotName,"plots/DiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(PlotName,"plots/DiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(PlotName1,"plots/DiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(PlotName1,"plots/DiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(PlotName1,"plots/DiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(PlotName2,"plots/DiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(PlotName2,"plots/DiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(PlotName2,"plots/DiMuonMass_CentBin_%d.eps",ih);
 

    //giving inetial value for crystall ball fourth parameter 
    diMuonsInvMass_RecA1[ih]->Rebin(2);
    GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[ih]->Integral(0,50));
    GAUSPOL->FixParameter(1, diMuonsInvMass_RecA1[ih]->GetBinWidth(1));
    
    new TCanvas; 
    diMuonsInvMass_RecA1[ih]->Fit("GAUSPOL","LLMERQ", "", mass_low, mass_high);
   
    double UpsilonMass = GAUSPOL->GetParameter(2);
    double UpsilonWidth = GAUSPOL->GetParameter(3);
   
    double UpsilonYield = GAUSPOL->GetParameter(0);
    double UpsilonYieldError = GAUSPOL->GetParError(0);
 
    double par[20];
    GAUSPOL->GetParameters(par);
    sprintf(namePt_1B,"pt_1B_%d",ih);
    backfun_1 = new TF1(namePt_1B, Pol2, mass_low, mass_high, 3);
    backfun_1->SetParameters(&par[4]);
   

    double MassLow=(UpsilonMass-3*UpsilonWidth);
    double MassHigh=(UpsilonMass+3*UpsilonWidth);
    
    int binlow =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassLow);
    int binhi =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassHigh);
    double binwidth=diMuonsInvMass_RecA1[ih]->GetBinWidth(1);
        
    //yield by function 
    //rec_pt[ih] = UpsilonYield;
    //rec_ptError[ih]= UpsilonYieldError;

    cout<<"Rec diMuons from Pt histo "<<diMuonsPt_RecA1[ih]->Integral(1,100)<<endl;  
    cout<<"Rec dimuons from mass "<<diMuonsInvMass_RecA1[ih]->Integral(1,100)<<endl; 
    

      
    //from pT histo
    //rec_pt[ih]=diMuonsPt_RecA1[ih]->IntegralAndError(1, 100,recError);

    //yield by histogram integral
    rec_pt[ih] = diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError);
    rec_ptError[ih]= recError;
  
    //Cal eff 
    Eff_cat_1[ih] = rec_pt[ih]/gen_pt[ih]; 
  
    //calculate error on eff
    GenNo[ih]=gen_pt[ih];
    Eff[ih]= Eff_cat_1[ih];
    GenError[ih]=gen_ptError[ih];
    RecError[ih]=rec_ptError[ih];
    //error    
    errEff_cat_S1_1[ih]= ( (Eff[ih] * Eff[ih]) /(GenNo[ih] * GenNo[ih]) );
    errEff_cat_S1_2[ih]= (RecError[ih] * RecError[ih]);
    errEff_cat_S1[ih]= (errEff_cat_S1_1[ih] * errEff_cat_S1_2[ih]);
   

    errEff_cat_S2_1[ih]= ( (1 - Eff[ih])* (1 - Eff[ih]) ) / ( GenNo[ih] * GenNo[ih]);
    errEff_cat_S2_2[ih]= (GenError[ih] * GenError[ih] ) - ( RecError[ih] * RecError[ih] );


    errEff_cat_S2[ih]=errEff_cat_S2_1[ih]*errEff_cat_S2_2[ih];
   

    Err_Eff_cat_1[ih]=sqrt(errEff_cat_S1[ih] + errEff_cat_S2[ih]);
   
    //error for no weights
    //Err_Eff_cat_1[ih]= Eff_cat_1[ih]*TMath::Sqrt(gen_ptError[ih]*gen_ptError[ih]/(gen_pt[ih]*gen_pt[ih]) + rec_ptError[ih]*rec_ptError[ih]/(rec_pt[ih]* rec_pt[ih]));

    cout<<"Upsilon Yield by integral of histo:  "<< diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError) <<"  error "<< rec_ptError[ih]<<endl; 
    cout<<"UpsilonYield by Gauss yield det:     "<< UpsilonYield << " UpsilonWidth "<< UpsilonWidth<<" UpsilonMass "<<UpsilonMass <<endl;
    cout<<"Upsilon Yield by Function integral:  "<< GAUSPOL->Integral(MassLow,MassHigh)/binwidth <<endl;
    cout<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    //dataFile<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    cout<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    dataFile<<"ih " <<ih<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    if(iSpec==1) sprintf(GPlotName,"plots/GenDiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(GPlotName,"plots/GenDiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(GPlotName,"plots/GenDiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(GPlotName1,"plots/GenDiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(GPlotName1,"plots/GenDiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(GPlotName1,"plots/GenDiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(GPlotName2,"plots/GenDiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(GPlotName2,"plots/GenDiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(GPlotName2,"plots/GenDiMuonMass_CentBin_%d.eps",ih);
       
    backfun_1->SetLineColor(4);
    backfun_1->SetLineWidth(1);
    //backfun_1->Draw("same");
    gPad->Print(PlotName);
    gPad->Print(PlotName1);
    gPad->Print(PlotName2);

    new TCanvas;
    diMuonsInvMass_GenA1[ih]->Draw();
    gPad->Print(GPlotName);
    gPad->Print(GPlotName1);
    gPad->Print(GPlotName2);


    //new TCanvas;
    //diMuonsPt_GenA1[ih]->Draw();
    //new TCanvas;
    //diMuonsPt_RecA1[ih]->Draw();
 
}
  dataFile.close();

  TGraphErrors *Eff_Upsilon = new TGraphErrors(Nptbin, PT, Eff_cat_1, mom_err,Err_Eff_cat_1);
  Eff_Upsilon->SetMarkerStyle(21);
  Eff_Upsilon->SetMarkerColor(2);
  Eff_Upsilon->GetYaxis()->SetTitle("Reco Eff");
 
  if(iSpec==1) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon pT (GeV/c^{2})");
  if(iSpec==2) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon rapidity");
  if(iSpec==3) Eff_Upsilon->GetXaxis()->SetTitle("bin");
   Eff_Upsilon->GetYaxis()->SetRangeUser(0,1.0);

  TLegend *legend_GP = new TLegend( 0.50,0.79,0.80,0.89);
  legend_GP->SetBorderSize(0);
  legend_GP->SetFillStyle(0);
  legend_GP->SetFillColor(0);
  legend_GP->SetTextSize(0.032);
  legend_GP->AddEntry(Eff_Upsilon,"PythiaEvtGen + HydjetBass", "P");
  
  new TCanvas;
  Eff_Upsilon->Draw("AP");
  legend_GP->Draw("Same");
    
  if(iSpec==1){ gPad->Print("plots/Eff_Upsilon_Pt.pdf");gPad->Print("plots/Eff_Upsilon_Pt.png");gPad->Print("plots/Eff_Upsilon_Pt.eps");}
  if(iSpec==2){ gPad->Print("plots/Eff_Upsilon_Rap.pdf");gPad->Print("plots/Eff_Upsilon_Rap.png");  gPad->Print("plots/Eff_Upsilon_Rap.eps");}
  if(iSpec==3){ gPad->Print("plots/Eff_Upsilon_Cent.pdf");gPad->Print("plots/Eff_Upsilon_Cent.png"); gPad->Print("plots/Eff_Upsilon_Cent.eps"); }

}
void absolute_eff()
{

	//	TString inputpath = "/afs/cern.ch/work/s/shuai/public/diboson/trees/productionv12/fullrange/";
	TString inputpath = "/afs/cern.ch/work/m/mwang/public/EDBR/trees/productionv1_0319/fullrange";
	TString cut = "absolute_efficiency";
	vector<TString> dataSamples;
	vector<TString> bkgSamples;
	vector<TString> sigSamples;


	bool weightedeff = true;
	bool isZZChannel = false;
	/*
	   double lepCut=0.0;   // 0->ele 1->mu
	   double nxjCut=1.0;  // -1 means you take both single and double jet
	   double nsubjCut=1.0; // The cut is nsubj21 < than this 
	 */

	//for eff lumi doesnt matter
	//double lumi = 19538.85;// for SingleMu2012
	//double lumi = 19531.85;// for singleEle2012
	double lumi=1;

	//system("rm -rf SignalEffPlots");   
	system("mkdir -p SignalEffPlots_Wprime");
	ofstream outFile("SignalEffPlots_Wprime/efficiencies_MCSig.txt");
	//outFile<<"Mass	EE1JHP	MM1JHP	EE1JLP	MM1JLP	EE2J	MM2J"<<endl;
	/*
	dataSamples.push_back("SingleMu_Run2012A-22Jan2013_xwh");
	dataSamples.push_back("SingleMu_Run2012B-22Jan2013_xwh");
	dataSamples.push_back("SingleMu_Run2012C-22Jan2013_xwh");
	dataSamples.push_back("SingleMu_Run2012D-22Jan2013_xwh");
	dataSamples.push_back("SingleElectron_Run2012A-22Jan2013_xwh");
	dataSamples.push_back("SingleElectron_Run2012B-22Jan2013_xwh");
	dataSamples.push_back("SingleElectron_Run2012C-22Jan2013_xwh");
	dataSamples.push_back("SingleElectron_Run2012D-22Jan2013_xwh");
	*/
	bkgSamples.push_back("TTBARpowheg_xwh");
	bkgSamples.push_back("SingleTopBarTWchannel_xwh");
	bkgSamples.push_back("SingleTopTWchannel_xwh");
	bkgSamples.push_back("SingleTopBarSchannel_xwh" );
	bkgSamples.push_back("SingleTopSchannel_xwh");
	bkgSamples.push_back("SingleTopBarTchannel_xwh");
	bkgSamples.push_back("SingleTopTchannel_xwh");                
	bkgSamples.push_back("SingleTop_xwh");                      
	bkgSamples.push_back("WW_xwh");
	bkgSamples.push_back("WZ_xwh");
	bkgSamples.push_back("ZZ_xwh");
	bkgSamples.push_back("VV_xwh");
	bkgSamples.push_back("WJetsPt100_xwh");
	bkgSamples.push_back("WJetsPt180_xwh");
	bkgSamples.push_back("DYJets_xwh");

	sigSamples.push_back("MWp_600_bb_xwh");
	sigSamples.push_back("MWp_700_bb_xwh");	  	
	sigSamples.push_back("MWp_800_bb_xwh");
	sigSamples.push_back("MWp_900_bb_xwh");
	sigSamples.push_back("MWp_1000_bb_xwh");	
	sigSamples.push_back("MWp_1100_bb_xwh");
	sigSamples.push_back("MWp_1200_bb_xwh");
	sigSamples.push_back("MWp_1300_bb_xwh");
	sigSamples.push_back("MWp_1400_bb_xwh");
	sigSamples.push_back("MWp_1500_bb_xwh");
	sigSamples.push_back("MWp_1600_bb_xwh");
	sigSamples.push_back("MWp_1700_bb_xwh");
	sigSamples.push_back("MWp_1800_bb_xwh");
	sigSamples.push_back("MWp_1900_bb_xwh");
	sigSamples.push_back("MWp_2000_bb_xwh");
	sigSamples.push_back("MWp_2100_bb_xwh");
	sigSamples.push_back("MWp_2200_bb_xwh");
	sigSamples.push_back("MWp_2300_bb_xwh");
	sigSamples.push_back("MWp_2400_bb_xwh");
	sigSamples.push_back("MWp_2500_bb_xwh");
	sigSamples.push_back("MWp_2600_bb_xwh");
	sigSamples.push_back("MWp_2700_bb_xwh");
	sigSamples.push_back("MWp_2800_bb_xwh");
	sigSamples.push_back("MWp_2900_bb_xwh");
	sigSamples.push_back("MWp_3000_bb_xwh"); 

	const int nCat=6;//ENu1JHP, MNu1JHP, ENu1JLP, MNu1JLP, ENu2J, MNu2J
	const int ndata = dataSamples.size();
	const int nbkg  = bkgSamples.size();
	const int nsig  = sigSamples.size();

	double SigEff[nsig][nCat];
	double SigNgen[nsig][nCat];
	int isig=0;
	int iCat=0;

	for(int i=0;i<nsig;i++)
	{
		for(int j=0;j<nCat;j++)
		{
			SigNgen[i][j]=0.0;
		}
	}

	//order of categories:EE1JHP, MM1JHP, EE1JLP, MM1JLP, EE2J, MM2J
	for(int iNJ=1;iNJ<=2;iNJ++)
	{
		double nxjCut=double(iNJ);

		for(int iPur=1;iPur>=0;iPur--)
		{
			if(iNJ==2&&iPur==0)continue;//for 2 jet only do the first loop
			double purCut=double(iPur);
			for(int ilep=0;ilep<2;ilep++)
			{
				double lepCut=double(ilep);


				std::vector<double> sig_effs, sig_masses;
				cout<<"NJets="<<iNJ<<"   "<<(ilep==0? "ELE" : "MU")<<"   "<<(iPur==0 ? "LP" : "HP")<<endl;
				cout<<"data samples "<<ndata<<"  bkg samples "<<nbkg<<"  signal samples "<<nsig<<endl;	

				TH1F * h1 = new TH1F (cut,cut,ndata+nbkg+nsig,0,ndata+nbkg+nsig);
				TH1F * h1b = new TH1F ("Efficiency","Efficiency",nsig,550,550+100*nsig);
				//h1->GetYaxis()->SetRangeUser(0,1);
				h1->SetBit(TH1::kCanRebin);
				h1->SetStats(0);
				gStyle->SetPaintTextFormat("1.4f");
				//h1->Sumw2();

				TCanvas * c1 = new TCanvas();	

				int indM=0;
				double startM=600.0; double step=100.0;
				//if(!isZZChannel){
				//	startM=600.0; 
				//	step=100.0;
				//}
				isig=0;
				for(int i =0; i<ndata+nbkg+nsig; i++   )
				{
					TString filename;
					TString samplename;
					if(i<ndata) 
					{
						filename = "treeEDBR_"+dataSamples.at(i)+".root";
						samplename = dataSamples.at(i);//SingleMu_Run2012A_22Jan2013_xwh
						//if(!isZZChannel)
						samplename.Remove(samplename.Length()-4,4);//SingleMu_Run2012A_22Jan2013
						samplename.Remove(0,12);//2012A_22Jan2013
					}
					else if(i>=ndata&&i<(ndata+nbkg)) 
					{
						filename = "treeEDBR_"+bkgSamples.at(i-ndata)+".root";
						samplename = bkgSamples.at(i-ndata);//TTBAR_xwh
						//if(!isZZChannel)
						samplename.Remove(samplename.Length()-4,4);//TTBAR
					}
					else if(i>=(ndata+nbkg)) 
					{
						filename = "treeEDBR_"+sigSamples.at(i-ndata-nbkg)+".root";
						samplename = sigSamples.at(i-ndata-nbkg);//MWp_1000_bb_xwh
						samplename.Remove(samplename.Length()-4,4);//MWp_1000_bb
						//this removes "WW_inclusive_"
						//if(samplename.Contains("RSG"))samplename.Remove(4,13);//RSG_c0p2_M1500
						//if(samplename.Contains("BulkG"))samplename.Remove(6,13);//BulkG_c1p0_M1500
					}
				cout<<"\n\n----------------------"<<endl;
				cout<<filename<<endl;
				cout<<samplename<<endl;


				TFile *fp = new TFile(inputpath+"/"+filename);
				TTree * tree = (TTree *) fp->Get("SelectedCandidates");
				int entries = tree->GetEntries();
				cout<<"entries: "<<entries<<endl;

				double pass=0;
				double total=0;
				double crossSection=0;
				//gen events and crossSection
				int Ngen=0;
				double xsec=0;
				//btags
				double nbtagsL[99];
				double nbtagsM[99];
				double nbtagsT[99];
				double nbtagscleanL[99];
				double nbtagscleanM[99];
				double nbtagscleanT[99];
				//subjet and fatjet btags
				float nsubjetbtagL[99];
				float nsubjetbtagM[99];
				float nsubjetbtagT[99];
				float nfatjetbtagL[99];
				float nfatjetbtagM[99];
				float nfatjetbtagT[99];

				//to make cuts
				double met;
				double ptlep1[99];
				double philep1[99];
				double etalep1[99];
				double philep2[99];
				double etajet1[99];
				double phijet1[99];

				double ptZll[99];
				double phiZll[99];
				double ptZjj[99];
				double lep[99];
				double vtag[99];
				int    nCands;
				int    nXjets[99];
				int nLooseEle;
				int nLooseMu;
				//per event weight
				double TOTweight=-1;
				double HLTweight=-1;
				double PUweight=-1;
				double LumiWeight=-1;
				double GenWeight=-1;
				double region[99];
				double nsubj21[99];
				//cuts for electron, ww 
				double eleid_passConversionVeto[99];
				double eleid_numberOfLostHits[99];


				tree->SetBranchAddress("Ngen", &Ngen);
				tree->SetBranchAddress("xsec", &xsec);
				tree->SetBranchAddress("nLooseMu", &nLooseMu);
				tree->SetBranchAddress("nLooseEle",&nLooseEle);
				tree->SetBranchAddress("nbtagsL",nbtagsL);
				tree->SetBranchAddress("nbtagsM",nbtagsM);
				tree->SetBranchAddress("nbtagsT",nbtagsT);
				tree->SetBranchAddress("nbtagscleanL",nbtagscleanL);
				tree->SetBranchAddress("nbtagscleanM",nbtagscleanM);
				tree->SetBranchAddress("nbtagscleanT",nbtagscleanT);
				tree->SetBranchAddress("nsubjetbtagL",nsubjetbtagL);
				tree->SetBranchAddress("nsubjetbtagM",nsubjetbtagM);
				tree->SetBranchAddress("nsubjetbtagT",nsubjetbtagT);
				tree->SetBranchAddress("nfatjetbtagL",nfatjetbtagL);
				tree->SetBranchAddress("nfatjetbtagM",nfatjetbtagM);
				tree->SetBranchAddress("nfatjetbtagT",nfatjetbtagT);

				tree->SetBranchAddress("ptlep1", ptlep1);
				tree->SetBranchAddress("etalep1", etalep1);
				tree->SetBranchAddress("philep1", philep1);
				tree->SetBranchAddress("philep2", philep2);
				tree->SetBranchAddress("phijet1", phijet1);
				tree->SetBranchAddress("etajet1", etajet1);
				tree->SetBranchAddress("ptZll", ptZll);
				tree->SetBranchAddress("phiZll", phiZll);
				tree->SetBranchAddress("ptZjj", ptZjj);
				tree->SetBranchAddress("met", &met);
				tree->SetBranchAddress("nXjets", nXjets);
				tree->SetBranchAddress("lep", lep);
				tree->SetBranchAddress("vTagPurity", vtag);
				tree->SetBranchAddress("nCands", &nCands);

				tree->SetBranchAddress("weight", &TOTweight);
				tree->SetBranchAddress("HLTweight", &HLTweight);
				tree->SetBranchAddress("PUweight", &PUweight);
				tree->SetBranchAddress("LumiWeight", &LumiWeight);
				tree->SetBranchAddress("GenWeight", &GenWeight);
				tree->SetBranchAddress("region", region);
				tree->SetBranchAddress("nsubj21", nsubj21);

				tree->SetBranchAddress("eleid_passConversionVeto", eleid_passConversionVeto);
				tree->SetBranchAddress("eleid_numberOfLostHits", eleid_numberOfLostHits);

				bool filled = 0;
				for(int j=0;j<entries;j++)
				{
					tree->GetEntry(j);

					if(j==0)
					{
						total = Ngen;
						crossSection = xsec;
					}

					if(total==0)
					{//something wrong with this sample
						cout<<samplename<<"  has "<<Ngen<<" generated events. Skipping sample"<<endl;
						break;
					}

					//per event weight
					double actualWeight = TOTweight; //HLTweight*PUweight*LumiWeight*GenWeight*lumi;
					if(i<ndata) actualWeight =1; //for data
					//cout<<actualWeight<<endl;

					if(weightedeff==false)actualWeight=1;

					filled = 0;
					//if(nCands==0)continue;
					for(int ivec=0;ivec<nCands;ivec++)
					{
						double deltaR_LJ = deltaR(etalep1[ivec],philep1[ivec],etajet1[ivec],phijet1[ivec]);
						double deltaPhi_JMET = deltaPhi(phijet1[ivec],philep2[ivec]);
						double deltaPhi_JWL  = deltaPhi(phijet1[ivec],phiZll[ivec]);
						
						total += actualWeight;

						if(filled==0)//cout the event as pass if any candidate pass all the cuts
						{
							//make cuts
							if(lep[ivec]!=lepCut)continue;// 1 is for mu
							if(region[ivec]!=1)continue;// 1 is mjj signal region
							if(nXjets[ivec]!=nxjCut)continue;// 1 jet candidate
							//for nsubjtiness
							/*if(isZZChannel)
							  {
							  if(vtag[ivec]!=purCut&&iNJ!=2)continue;
							  }*/
							if(!isZZChannel)
							{
								//for nsubjtiness
								if(iPur==1&&nsubj21[ivec]<0.5);
								else if(iPur==0&&(nsubj21[ivec]>0.5&&nsubj21[ivec]<0.75));
								else if(nxjCut==2);
								else continue;
								////
								if((nLooseEle+nLooseMu)!=1)continue;
								//if(ptZll[ivec]<200)continue;
								//if(nbtagsM[ivec]!=0)continue; //b-tag veto
								if(nbtagscleanL[ivec]!=0)continue; // b-tag veto
								if(nsubjetbtagM[ivec]<2)continue; // subjet btag
								if(deltaR_LJ<1.57 || deltaPhi_JMET<2. || deltaPhi_JWL<2.)continue;

								if(lepCut==0)
								{
									if(met<80)continue;//for electron, use this cut
									//if(eleid_passConversionVeto[ivec]!=1)continue;
									//if(eleid_numberOfLostHits[ivec]!=0)continue;
								}


							}
							pass+=actualWeight;

							filled =1;
						}

					}//end of candidate loop

				}//end of tree loop

				double eff=0;

				//if(weightedeff==true)total = crossSection*lumi;

				if(total!=0)
				{
					eff = (double)pass/(double)total;

				}

				cout<<"crossSection: "<<crossSection<<" total: "<<total<<" pass: "******" eff: "<<eff<<endl;

				double BR_sf=1.0;

				if(samplename.Contains("MWp") || samplename.Contains("RSG") || samplename.Contains("WprimeWZ") )
				{
					int binToFill=h1b->FindBin(indM*step+startM);
					cout<<"Filling IndM="<<indM<<"  M="<<indM*step+startM<<"  Bin#"<<binToFill<<"  Eff="<<eff<<endl;

					if(samplename.Contains("bb") ||samplename.Contains("lvjj") )
					{
						BR_sf=1.0;
						if(samplename.Contains("RSG")&&samplename.Contains("PYTHIA"))
						{//taus are also in !
							BR_sf=2.0/3.0;
						}
					}//end if samplename.Contains("lljj")
					else 
					{
						cout<<"\nWARNING !!! Impossible to identify the process of the signal from the sample name: "<<samplename<<" -> assuming full chain llqq with l=e or mu ."<<endl;
						BR_sf=1.0;
					}

					h1b->SetBinContent(binToFill,eff/BR_sf);
					sig_masses.push_back(indM*step+startM);
					sig_effs.push_back(eff/BR_sf);
					indM++;

					cout<<"Array indexes: "<<isig<<"  "<<iCat<<endl;
					SigEff[isig][iCat]=eff/BR_sf;
					SigNgen[isig][iCat]=Ngen;//last entry will be used, should be ok because always the same 
					isig++;
					cout<<"isig="<<isig<<"    "<<"nsig="<<nsig<<endl;
				
					if(isig==nsig)iCat++;
				}//end if sample name is a signal sample name

				h1->Fill(samplename,eff);	
			}//end of sample loop

			c1->SetGridy(1);

			/// Here you choose the functional form of the efficiency.
			/// You have to be careful with the initial values of the parameters...
			bool fitEff=false;
			TF1 *fitFunc = 0;
			if(fitEff)
			{
				fitFunc = new TF1("fitPoly2","tanh([0]*(x-[1]))*([2]+[3]*x)",580,2550);
				fitFunc->SetLineColor(kRed);
				fitFunc->SetLineWidth(2);
				fitFunc->SetParameter(0,-0.002);
				fitFunc->SetParameter(1,300);
				fitFunc->SetParameter(2,-0.3);
				fitFunc->SetParameter(3,3E-5);
				fitFunc->SetLineColor(kRed);
				h1b->Fit(fitFunc,"R");

				cout<<"\n\nEff extrapolated at 2000 GeV: "<<fitFunc->Eval(2000.0)<<endl;
			}

			TString lepStr;
			if(lepCut==1)lepStr="MU";
			if(lepCut==0)lepStr="ELE";
			TString PurStr;
			if(iPur==1)PurStr="HP";
			if(iPur==0)PurStr="LP";
			if(nxjCut==2)PurStr="";

			TString SaveName="_"+lepStr+"_"+PurStr+"_";
			SaveName+=iNJ;
			SaveName+="J";
			//outFile<<SaveName<<endl;

			/// The original plot with efficiencies for both signals and backgrounds
			h1->SetTitle(cut);			
			h1->Draw();
			h1->Draw("TEXT0same");
			c1->SaveAs("SignalEffPlots/"+cut+SaveName+".png");

			/// The plot with signal efficiency and the fit.
			TCanvas *c2=new TCanvas("cFit","cFit",800,800);
			c2->cd();
			h1b->SetMarkerStyle(20);
			h1b->SetMinimum(0.0);
			h1b->SetMaximum(0.25);
			h1b->Draw("P");
			if(fitEff)fitFunc->Draw("Lsame");
			c2->SaveAs("SignalEffPlots_Wprime/efficiencyAndFit"+SaveName+".png");
			c2->SaveAs("SignalEffPlots_Wprime/efficiencyAndFit"+SaveName+".pdf");

			cout<<"data samples "<<ndata<<"  bkg samples "<<nbkg<<"  signal samples "<<nsig<<endl;	
			cout<<"\nEfficiencies for Lep="<<lepCut<<"  nXjets="<<nxjCut<<" : "<<endl;
			for(unsigned int im=0;im<sig_effs.size();im++)
			{
				cout<<"M="<<sig_masses.at(im)<<"  Eff="<<sig_effs.at(im)<<endl;
			}
		}//end of lepCut loop
	}//end of purity loop
}//end of nxjCut loop

/*
   for(int is =0; is<nsig; is++)
   {
   double MAss = 600+100*is;
   outFile<<MAss;
   for(int ic=0;ic<nCat; ic++)
   {
   outFile<<"		"<<SigEff[is][ic];
   }
   outFile<<endl;
   }
 */


/*
   for(int is =0; is<nsig; is++)
   {
   double MAss = 600+100*is;
   if(is<4)outFile<<"700";
   else if(is<8)outFile<<"1000";
   else if(is<12)outFile<<"1500";
   else outFile<<"2000"; 
   for(int ic=0;ic<nCat; ic++)
   {
   outFile<<"		"<<SigEff[is][ic];
   }
   outFile<<endl;

   }//end loop on samples


   TGraphErrors *grEff[4];
   for(int ic=0;ic<nCat; ic++){

   const  int nPmax=6;
   double width[nPmax]={0.0,40.0,80,120.0,160.0,200.0};
   double eff[4][nPmax], effErr[4][nPmax];

   string catLab="dummy";
   if(ic==0)catLab="EEHP";
   else if(ic==1)catLab="MMHP";
   else if(ic==2)catLab="EELP";
   else if(ic==3)catLab="MMLP";
   else catLab="dummyDUMMY";

//    int iP=0;
for(int is =0; is<nsig; is++)
{

double effTMP=SigEff[is][ic];
if(is==2)effTMP*=(10698.0/8024.0);//M1500 G80 has less processed events
if(is==10)effTMP*=(10692.0/5346.0);//M1500 G80 has less processed events
double errTMP=sqrt((effTMP*(1.0-effTMP))/SigNgen[is][ic]);
if(is<4){
eff[0][is]=effTMP;
effErr[0][is]=errTMP;
}
else if(is<8){
eff[1][is-4]=effTMP;
effErr[1][is-4]=errTMP;
}
else if(is<12){
eff[2][is-8]=effTMP;
effErr[2][is-8]=errTMP;
}
else {
eff[3][is-12]=effTMP;
effErr[3][is-12]=errTMP;
}

}//end loop on samples



grEff[0]=new TGraphErrors(4,width,eff[0],0,effErr[0]);
grEff[0]->SetName(("grEff_vs_Width_M700_"+catLab).c_str());
grEff[0]->SetMarkerSize(1.5);
grEff[0]->SetMarkerColor(kBlack);
grEff[0]->SetMarkerStyle(20);
grEff[0]->GetXaxis()->SetTitle("Natural Width [GeV]");
grEff[0]->GetYaxis()->SetTitle("Efficiency");

grEff[1]=new TGraphErrors(4,width,eff[1],0,effErr[1]);
grEff[1]->SetName(("grEff_vs_Width_M1000_"+catLab).c_str());
grEff[1]->SetMarkerSize(1.5);
grEff[1]->SetMarkerColor(kRed);
grEff[1]->SetMarkerStyle(21);
grEff[1]->GetXaxis()->SetTitle("Natural Width [GeV]");
grEff[1]->GetYaxis()->SetTitle("Efficiency");

grEff[2]=new TGraphErrors(4,width,eff[2],0,effErr[2]);
grEff[2]->SetName(("grEff_vs_Width_M1500_"+catLab).c_str());
grEff[2]->SetMarkerSize(1.8);
grEff[2]->SetMarkerColor(kBlue);
grEff[2]->SetMarkerStyle(22);
grEff[2]->GetXaxis()->SetTitle("Natural Width [GeV]");
grEff[2]->GetYaxis()->SetTitle("Efficiency");

grEff[3]=new TGraphErrors(4,width,eff[3],0,effErr[3]);
grEff[3]->SetName(("grEff_vs_Width_M2000_"+catLab).c_str());
grEff[3]->SetMarkerSize(1.5);
grEff[3]->SetMarkerColor(kGreen+3);
grEff[3]->SetMarkerStyle(24);
grEff[3]->GetXaxis()->SetTitle("Natural Width [GeV]");
grEff[3]->GetYaxis()->SetTitle("Efficiency");

grEff[0]->SetMaximum(0.25);
grEff[1]->SetMaximum(0.25);
grEff[2]->SetMaximum(0.25);
grEff[3]->SetMaximum(0.25);
grEff[0]->SetMinimum(0.0);
grEff[1]->SetMinimum(0.0);
grEff[2]->SetMinimum(0.0);
grEff[3]->SetMinimum(0.0);

TCanvas *cc=new TCanvas("canEffWidth",("CANVAS - EFF vs WIDTH - "+catLab).c_str(),900,900);
grEff[3]->Draw("AP");
grEff[0]->Draw("P");
grEff[1]->Draw("P");
grEff[2]->Draw("P");

TLegend *l1;
if(ic>1)l1=new TLegend(0.13,0.7,0.43,0.93);
else l1=new TLegend(0.13,0.25,0.43,0.45);
l1->SetFillColor(kWhite);
l1->SetHeader(catLab.c_str());
l1->AddEntry(grEff[0],"M=700 GeV","P");
l1->AddEntry(grEff[1],"M=1000 GeV","P");
l1->AddEntry(grEff[2],"M=1500 GeV","P");
l1->AddEntry(grEff[3],"M=2000 GeV","P");
l1->Draw();

cc->SaveAs(("can_eff_vs_width_"+catLab+".root").c_str());
cc->SaveAs(("can_eff_vs_width_"+catLab+".png").c_str());
delete cc;
delete l1;
//  delete[] grEff;
}//end lopp on categories

*/


for(int is =0; is<nsig; is++)
{
	//double MAss = 750+250*is;
	double MAss = 600+100*is;
	//if(is<6)
	outFile<<MAss;
	if(is==4)outFile<<"1000 (MWprime)";
	else if(is==9)outFile<<"1500 (MWprime)";
	else if(is==14)outFile<<"2000 (MWprime)";
	else if(is==19)outFile<<"2500 (MWprime)";
	else if(is==24)outFile<<"3000 (MWprime)";
	//else outFile<<"?????";

	for(int ic=0;ic<nCat; ic++)
	{
		outFile<<"		"<<SigEff[is][ic];
	}
	outFile<<endl;
}



}//end main
Esempio n. 5
0
void kees_gen() {
  gROOT->SetStyle("HALLA");
  TCanvas *cn = new TCanvas("cn");
  cn->Draw();
  cn->UseCurrentStyle();
  TH1F *frm = new TH1F("frm","",100,0.,10.);
  frm->GetXaxis()->SetTitle("Q^{2}  [GeV^{2}]");
  frm->GetYaxis()->SetTitle("G_{E}^{n}");
  frm->SetMinimum(-.02);
  frm->SetMaximum(0.1);
  frm->UseCurrentStyle();
  frm->Draw();
  frm->SetAxisRange(0.,5.,"X");

  TF1 *genf = new TF1("genf",genff,1.,10.,1);
  genf->SetLineColor(2);
  genf->SetLineStyle(2);
  genf->SetParameter(0,1.);
  genf->SetParameter(1,.3);
  genf->SetParameter(0,-0.632);
  // match to Madey point just below 1.5
  //  genf->SetParameter(0,.0411/genf->Eval(1.45));
  
  TMultiGraph* mgrDta = new TMultiGraph("Data","G_{E}^{n}");
  TLegend *legDta = new TLegend(.54,.6,.875,.90,"","brNDC");

  TMultiGraph* wgr = mgrDta;
  TLegend *wlg = legDta;

   // the data
  legDta->SetBorderSize(0); // turn off border
  legDta->SetFillStyle(0);
  
  datafile_t *f = datafiles;
  TGraph* gr=0;
  while ( f && f->filename ) {
    gr=OneGraph(f);
    if (gr) {
      if (f->lnpt) {
	mgrDta->Add(gr,f->lnpt);
	legDta->AddEntry(gr,f->label,f->lnpt);
      }
      else if (gr->GetMarkerStyle()>=20) {
	mgrDta->Add(gr,"p");
	legDta->AddEntry(gr,f->label,"p");
      }	
      else {
	mgrDta->Add(gr,"l");
	legDta->AddEntry(gr,f->label,"l");
      }
    }
    f++;
  }
    

  mgrDta->Draw("p");
  //  legDta->Draw();   don't draw the data legend
  
  TMultiGraph* mgrThry = new TMultiGraph("Theory","G_{E}^{n}");
  TLegend *legThry = new TLegend(.54,.6,.875,.9,"","brNDC");

  wgr = mgrThry;
  wlg = legThry;

  // the theory
  wlg->SetBorderSize(0); // turn off border
  wlg->SetFillStyle(0);
  
  f = theoryfiles1;
  gr=0;
  while ( f && f->filename ) {
    gr=OneGraph(f);
    if (gr) {
      TGraphAsymmErrors *egr = dynamic_cast<TGraphAsymmErrors*>(gr);
      if (egr && egr->GetN()>1 && egr->GetEYhigh() && egr->GetEYhigh()[1]>0) {
	gr = toerror_band(egr);
	gr->SetFillStyle(3000+f->style);
      }
      if (f->lnpt) {
	wgr->Add(gr,f->lnpt);
	wlg->AddEntry(gr,f->label,f->lnpt);
      }
      else if (gr->GetMarkerStyle()>=20) {
	wgr->Add(gr,"p");
	wlg->AddEntry(gr,f->label,"p");
      }	
      else {
	wgr->Add(gr,"l");
	wlg->AddEntry(gr,f->label,"l");
      }
    }
    f++;
  }

  genf->Draw("same");
  mgrThry->Draw("c");
  legThry->AddEntry(genf,"F_{2}/F_{1} #propto ln^{2}(Q^{2}/#Lambda^{2})/Q^{2}","l");
  legThry->Draw();

  // draw a line at 1
  cn->Modified();

  cn->Update();
  cn->SaveAs(Form("%s.eps",psfile));
  cn->SaveAs(Form("%s.root",psfile));
  gSystem->Exec(Form("./replace_symbols.pl %s.eps",psfile));
  // now an overlay, hopefully matching dimensions

  // remove everything but the graph
  cn->Update();
  TList *clist = cn->GetListOfPrimitives();
  TFrame* frame = cn->GetFrame();
  for (int i=0; i<clist->GetSize(); ) {
    if (clist->At(i) != frame) {
      clist->RemoveAt(i);
    } else i++;
  }
  // draw markers in the corners
  TMarker *mkr = new TMarker(frame->GetX1(),frame->GetY1(),2);
  mkr->Draw();
  mkr = new TMarker(frame->GetX2(),frame->GetY1(),2);
  mkr->Draw();
  mkr = new TMarker(frame->GetX1(),frame->GetY2(),2);
  mkr->Draw();
  mkr = new TMarker(frame->GetX2(),frame->GetY2(),2);
  mkr->Draw();
  frame->SetLineColor(10);
  cn->Update();

  datafile_t miller = { "figure_input/Miller/lattice.GEn.rtf","Miller",
			"[0]","[1]","[1]-[3]","[2]-[1]",0,0,1,3,"F" };

  gr = OneGraph(&miller);
  TGraphAsymmErrors* egr = dynamic_cast<TGraphAsymmErrors*>(gr);
  if (egr && egr->GetEYhigh() && egr->GetEYhigh()[egr->GetN()/2]>0) {
    gr = toerror_band(egr);
    gr->SetLineStyle(1);
    gr->SetFillColor(gr->GetLineColor());
    gr->SetFillStyle(3000+miller.style);
  }
  
  gr->Draw("F");

  cn->Update();
  cn->SaveAs("gen_Miller_Overlay.eps");
  cn->SaveAs("gen_Miller_Overlay.root");
  
}
Esempio n. 6
0
int compareL2L3Correction(const std::string& kalibri, const std::string& jetMETL2, const std::string& jetMETL3) {
//int compareL2L3Correction(const std::string& jetMETL2, const std::string& jetMETL3) {
    // -- Read calibration constants ---------------
    std::cout << "Reading calibration constants...\n";
    parmap corrKalibri  = readParameters(kalibri);
    parmap corrJetMETL2 = readParameters(jetMETL2);
    parmap corrJetMETL3 = readParameters(jetMETL3);
    if( (1 + corrKalibri.size() ) != ( corrJetMETL2.size() + corrJetMETL3.size() ) ) {
        std::cerr << "Linker Kompaktierer defekt. Kontaktieren Sie das Personal (68/111)." << std::endl;
        return 1;
    }


    // -- Global variables -------------------------
    std::vector<TF1*> fCorrKalibri(1+corrKalibri.size());
    std::vector<TF1*> fCorrJetMET(1+corrKalibri.size());
    TF1 * f = 0;
    char name[50];
    std::string outFileName = "comparisonL2L3_Summer08_IC5Calo.ps";
    bool printPar = false;


    // -- Create correction plots for JetMET -------
    std::cout << "Creating JetMET plots...\n";
    // L3 correction
    if( printPar ) std::cout << "  JetMETL3: " << std::flush;
    std::vector<double>& par = corrJetMETL3[0];
    f = new TF1("fJetMETL3",corrL3,par.at(2),par.at(3),4);
    for(int i = 0; i < 4; i++) {
        f->SetParameter(i,par.at(4+i));
        if( printPar ) std::cout << par.at(4+i) << " ";
    }
    if( printPar ) std::cout << "\n";
    fCorrJetMET.at(0) = f;

    // L2 correction
    for(unsigned int bin = 0; bin < corrJetMETL2.size(); bin++) {
        if( printPar ) std::cout << "  JetMETL2 " << bin << ": " << std::flush;
        par = corrJetMETL2[bin];
        sprintf(name,"fJetMETL2_%i",bin);
        f = new TF1(name,corrL2,par.at(2),par.at(3),3);
        sprintf(name,"Bin %i: %.3f <  #eta < %.3f",bin,par.at(0),par.at(1));
        f->SetTitle(name);
        for(int i = 0; i < 3; i++) {
            f->SetParameter(i,par.at(4+i));
            if( printPar ) std::cout << par.at(4+i) << " ";
        }
        if( printPar ) std::cout << "\n";
        fCorrJetMET.at(1+bin) = f;
    }

    // Nice plots
    for(unsigned i = 0; i < fCorrJetMET.size(); i++) {
        fCorrJetMET.at(i)->SetLineWidth(2);
        fCorrJetMET.at(i)->SetLineColor(4);
    }


    // -- Create correction plots for Kalibri ------
    std::cout << "Creating Kalibri plots...\n";
    int nTowerPar     = 0;
    int nJetPar       = 3;
    int nTrackPar     = 0;
    int nGlobalJetPar = 4;
    // Global correction
    if( printPar ) std::cout << "  Kalibri: " << std::flush;
    par = corrKalibri[0];
    f = new TF1("fKalibri_global",corrL3,par.at(2),par.at(3),4);
    for(int i = 0; i < nGlobalJetPar; i++) {
        f->SetParameter(i,par.at(4+nTowerPar+nJetPar+nTrackPar+i));
        if( printPar ) std::cout << par.at(4+nTowerPar+nJetPar+nTrackPar+i) << " ";
    }
//   f = new TF1("fKalibri_global",corrL3,4,2000,4);
//   f->SetParameter(0,0.998293);
//   f->SetParameter(1,5.43056);
//   f->SetParameter(2,3.3444);
//   f->SetParameter(3,2.39809);
    if( printPar ) std::cout << "\n";
    fCorrKalibri.at(0) = f;

    // Local correction
    double scale[3] = { 1., 0.1, 0.01 };
    for(unsigned int bin = 0; bin < corrKalibri.size(); bin++) {
        if( printPar ) std::cout << "  Kalibri " << bin << ": " << std::flush;
        par = corrKalibri[bin];
        sprintf(name,"fKalibri_%i",bin);
        f = new TF1(name,corrL2,par.at(2),par.at(3),3);
        sprintf(name,"Bin %i: %.3f <  #eta < %.3f",bin,par.at(0),par.at(1));
        f->SetTitle(name);
        for(int i = 0; i < nJetPar; i++) {
            f->SetParameter(i,scale[i]*par.at(4+nTowerPar+i));
            if( printPar ) std::cout << scale[i]*par.at(4+nTowerPar+i) << " ";
        }
        if( printPar ) std::cout << "\nDone";
        fCorrKalibri.at(1+bin) = f;
    }

    // Nice plots
    for(unsigned i = 0; i < fCorrKalibri.size(); i++) {
        fCorrKalibri.at(i)->SetLineWidth(2);
        fCorrKalibri.at(i)->SetLineColor(2);
    }


    // -- Writing plots to file --------------------
    std::cout << "Writing plots to file...\n";
    gROOT->ProcessLine(".x ./gStyleSettings.C");
    gStyle->SetOptStat(0);
    TPostScript * const ps = new TPostScript(outFileName.c_str(),111);
    TCanvas     * const c1 = new TCanvas("c1","",500,500);
    TH1F          * hFrame = new TH1F("hFrame",";p_{T} (GeV)",100,0,3000);
    c1->cd();
    c1->SetLogx(1);
    for(unsigned i = 0; i < fCorrKalibri.size(); i++) {
        if( i == 0 ) {
            hFrame->GetYaxis()->SetRangeUser(1.0,5.0);
            hFrame->GetYaxis()->SetTitle("L3 correction factor");
        }
        else {
            hFrame->GetYaxis()->SetRangeUser(0.5,2.0);
            hFrame->GetYaxis()->SetTitle("L2 correction factor");
        }
        hFrame->SetTitle(fCorrKalibri.at(i)->GetTitle());
        hFrame->Draw();
        fCorrKalibri.at(i)->Draw("same");
        fCorrJetMET.at(i)->Draw("same");

        TPaveText * t[3];
        double maxy = 0.86;
        double miny = maxy - 0.05*(1+fCorrKalibri.at(i)->GetNpar());
        t[0] = new TPaveText(0.3,miny,0.38,maxy,"NDC");
        sprintf(name,"   ");
        t[0]->AddText(name);
        t[1] = new TPaveText(0.38,miny,0.58,maxy,"NDC");
        sprintf(name,"#color[2]{Kalibri}");
        t[1]->AddText(name);
        t[2] = new TPaveText(0.58,miny,0.78,maxy,"NDC");
        sprintf(name,"#color[4]{JetMET}");
        t[2]->AddText(name);
        for(int p = 0; p < fCorrKalibri.at(i)->GetNpar(); p++) {
            sprintf(name,"b_{%i}:",p);
            t[0]->AddText(name);
            sprintf(name,"%.4f",fCorrKalibri.at(i)->GetParameter(p));
            t[1]->AddText(name);
            sprintf(name,"%.4f",fCorrJetMET.at(i)->GetParameter(p));
            t[2]->AddText(name);
        }
        for(int p = 0; p < 3; p++) {
            t[p]->SetBorderSize(0);
            t[p]->SetFillColor(0);
            t[p]->SetTextFont(42);
            t[p]->SetTextAlign(11);
            t[p]->Draw("same");
        }

        c1->Draw();
        ps->NewPage();
        for(int p = 0; p < 3; p++) {
            delete t[p];
        }
    }
    ps->Close();


    // -- Cleaning up ------------------------------
    for(unsigned int i = 0; i < fCorrKalibri.size(); i++) {
        delete fCorrKalibri.at(i);
        delete fCorrJetMET.at(i);
    }
    delete hFrame;
    delete c1;
    delete ps;

    std::cout << "Wrote file " << outFileName << ".\n";

    return 0;
}
Esempio n. 7
0
void FitDijetMass_Data() {

  
  TFile *inf  = new TFile("MassResults_ak7calo.root");
  TH1F *hCorMassDen     = (TH1F*) inf->Get("DiJetMass");
  hCorMassDen->SetXTitle("Corrected Dijet Mass (GeV)");
  hCorMassDen->SetYTitle("Events/GeV");
  hCorMassDen->GetYaxis()->SetTitleOffset(1.5);
  hCorMassDen->SetMarkerStyle(20);
  hCorMassDen->GetXaxis()->SetRangeUser(120.,900.);



  gROOT->ProcessLine(".L tdrstyle.C");
  setTDRStyle();
  tdrStyle->SetErrorX(0.5);
  tdrStyle->SetPadRightMargin(0.08);
  tdrStyle->SetLegendBorderSize(0);
  gStyle->SetOptFit(1111);
  tdrStyle->SetOptStat(0); 

  
  TCanvas* c2 = new TCanvas("c2","DijetMass", 500, 500);
  /////// perform 4 parameters fit
  TF1 *func = new TF1("func", "[0]*((1-x/7000.+[3]*(x/7000)^2)^[1])/(x^[2])", 
  100., 1000.);
  func->SetParameter(0, 1.0e+08);
  func->SetParameter(1, -1.23);
  func->SetParameter(2, 4.13);
  func->SetParameter(3, 1.0);

  func->SetLineColor(4);
  func->SetLineWidth(3);

  TVirtualFitter::SetMaxIterations( 10000 );
  TVirtualFitter *fitter;
  TMatrixDSym* cov_matrix;

  int fitStatus = hCorMassDen->Fit("func","LLI","",130.0, 800.0); // QCD fit
 
  TH1F *hFitUncertainty = hCorMassDen->Clone("hFitUncertainty");
  hFitUncertainty->SetLineColor(5);
  hFitUncertainty->SetFillColor(5);
  hFitUncertainty->SetMarkerColor(5);

  if (fitStatus == 0) {
    fitter = TVirtualFitter::GetFitter();
    double* m_elements = fitter->GetCovarianceMatrix();
    cov_matrix = new TMatrixDSym( func->GetNumberFreeParameters(),m_elements);
    cov_matrix->Print();
    double x, y, e;

    for(int i=0;i<hFitUncertainty->GetNbinsX();i++)
      {
	x = hFitUncertainty->GetBinCenter(i+1);
	y = func->Eval(x);
	e = QCDFitUncertainty( func, *cov_matrix, x);
	hFitUncertainty->SetBinContent(i+1,y);
	hFitUncertainty->SetBinError(i+1,e);
      }
  }

  hCorMassDen->Draw("ep");
  gPad->Update();
  TPaveStats *st = (TPaveStats*)hCorMassDen->FindObject("stats");
  st->SetName("stats1");
  st->SetX1NDC(0.3); //new x start position
  st->SetX2NDC(0.6); //new x end position
  st->SetTextColor(4);
  hCorMassDen->GetListOfFunctions()->Add(st);



  /////// perform 2 parameters fit
  TF1 *func2 = new TF1("func2", "[0]*(1-x/7000.)/(x^[1])", 100., 1000.);
  func2->SetParameter(0, 10000.);
  func2->SetParameter(1, 5.0);
  func2->SetLineWidth(3);

  fitStatus = hCorMassDen->Fit("func2","LLI","",130.0, 800.0); // QCD fit

  TH1F *hFitUncertainty2 = hCorMassDen->Clone("hFitUncertainty2");
  hFitUncertainty2->SetLineColor(kGray);
  hFitUncertainty2->SetFillColor(kGray);
  hFitUncertainty2->SetMarkerColor(kGray);

  if (fitStatus == 0) {
    fitter = TVirtualFitter::GetFitter();
    double* m_elements = fitter->GetCovarianceMatrix();
    cov_matrix = new TMatrixDSym( func2->GetNumberFreeParameters(),m_elements);
    cov_matrix->Print();
    double x, y, e;

    for(int i=0;i<hFitUncertainty2->GetNbinsX();i++)
      {
	x = hFitUncertainty2->GetBinCenter(i+1);
	y = func2->Eval(x);
	e = QCDFitUncertainty( func2, *cov_matrix, x);
	hFitUncertainty2->SetBinContent(i+1,y);
	hFitUncertainty2->SetBinError(i+1,e);
      }
  }

  hFitUncertainty->Draw("E3 same");
  hCorMassDen->Draw("ep sames");
  hFitUncertainty2->Draw("E3 same");
  hCorMassDen->Draw("ep sames");
  func2->Draw("same");
  c2->SetLogy(1);



/*
  

  TH1F *hCorMass     = hCorMassDen->Clone("hCorMass");


  for(int i=0; i<hCorMass->GetNbinsX(); i++){
    hCorMass->SetBinContent(i+1, hCorMassDen->GetBinContent(i+1) * hCorMassDen->GetBinWidth(i+1));
    hCorMass->SetBinError(i+1, hCorMassDen->GetBinError(i+1) * hCorMassDen->GetBinWidth(i+1));
  } 




  // Our observable is the invariant mass
  RooRealVar invMass("invMass", "Corrected dijet mass", 
		     100., 1000.0, "GeV");
  RooDataHist data( "data", "", invMass, hCorMass);

   //////////////////////////////////////////////




   // make QCD model
  RooRealVar p0("p0", "# events", 600.0, 0.0, 10000000000.);
  RooRealVar p1("p1","p1", 3.975, -10., 10.) ;  
  RooRealVar p2("p2","p2", 5.302, 4., 8.) ; 
  RooRealVar p3("p3","p3", -1.51, -100., 100.) ; 



//    // define QCD line shape
  RooGenericPdf qcdModel("qcdModel", "pow(1-@0/7000.+@3*(@0/7000.)*(@0/7000.),@1)*pow(@0/7000.,-@2)",
			 RooArgList(invMass,p1,p2,p3)); 

   // full model
   RooAddPdf model("model","qcd",RooArgList(qcdModel), RooArgList(p0)); 



   //plot sig candidates, full model, and individual componenets 

   //   __ _ _    
   //  / _(_) |_  
   // | |_| | __| 
   // |  _| | |_  
   // |_| |_|\__| 


 // Important: fit integrating f(x) over ranges defined by X errors, rather
  // than taking point at center of bin

   RooFitResult* fit = model.fitTo(data, Minos(kFALSE), Extended(kTRUE),
				   SumW2Error(kFALSE),Save(kTRUE), Range(130.,800.),
				   Integrate(kTRUE) );

   // to perform chi^2 minimization fit instead
   //    RooFitResult* fit = model.chi2FitTo(data, Extended(kTRUE), 
   // 				       Save(),Range(50.,526.),Integrate(kTRUE) );

   fit->Print();


   //plot data 
   TCanvas* cdataNull = new TCanvas("cdataNull","fit to dijet mass",500,500);
   RooPlot* frame1 = invMass.frame() ; 
   data.plotOn(frame1, DataError(RooAbsData::SumW2) ) ; 
   model.plotOn(frame1, LineColor(kBlue)) ; 
   model.plotOn(frame1, VisualizeError(*fit, 1),FillColor(kYellow)) ;   
   data.plotOn(frame1, DataError(RooAbsData::SumW2) ) ; 
   model.plotOn(frame1, LineColor(kBlue)) ; 
   model.paramOn(frame1, Layout(0.4, 0.85, 0.92)); 
   TPaveText* dataPave = (TPaveText*) frame1->findObject("model_paramBox");
   dataPave->SetY1(0.77);
   gPad->SetLogy();
   frame1->GetYaxis()->SetNoExponent();
   frame1->GetYaxis()->SetRangeUser(5E-2,5E+4);
   frame1->GetYaxis()->SetTitle("Events / bin");
   frame1->GetYaxis()->SetTitleOffset(1.35);
   frame1->SetTitle("fit to data with QCD lineshape");
   frame1->Draw() ;


    
    // S h o w   r e s i d u a l   a n d   p u l l   d i s t s
    // -------------------------------------------------------
    
   //// Construct a histogram with the residuals of the data w.r.t. the curve
   RooHist* hresid = frame1->residHist() ;
   // Create a new frame to draw the residual distribution and add the distribution to the frame
   RooPlot* frame2 = invMass.frame(Title("Residual Distribution")) ;
   frame2->addPlotable(hresid,"P") ;


    
   ///// Construct a histogram with the pulls of the data w.r.t the curve
   RooHist* hpull = frame1->pullHist() ;   
   //// Create a new frame to draw the pull distribution and add the distribution to the frame
   RooPlot* frame3 = invMass.frame(Title("Pull Distribution")) ;
   frame3->addPlotable(hpull,"P") ;


   TCanvas* cResidual = new TCanvas("cResidual","Residual Distribution",1000,500);
   cResidual->Divide(2) ;
   cResidual->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame2->Draw() ;
   cResidual->cd(2) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame3->Draw() ;
  
*/
}
Esempio n. 8
0
TF1 *fit(TTree *nt,TTree *ntMC,double ptmin,double ptmax, bool ispPb, int count){   
   //cout<<cut.Data()<<endl;
   //static int count=0;
   //count++;
   TCanvas *c= new TCanvas(Form("c%d",count),"",600,600);
   TH1D *h = new TH1D(Form("h%d",count),"",50,5,6);
   TH1D *hMC = new TH1D(Form("hMC%d",count),"",50,5,6);

   TString iNP="7.26667e+00*Gaus(x,5.10472e+00,2.63158e-02)/(sqrt(2*3.14159)*2.63158e-02)+4.99089e+01*Gaus(x,4.96473e+00,9.56645e-02)/(sqrt(2*3.14159)*9.56645e-02)+3.94417e-01*(3.74282e+01*Gaus(x,5.34796e+00,3.11510e-02)+1.14713e+01*Gaus(x,5.42190e+00,1.00544e-01))";
   TF1 *f = new TF1(Form("f%d",count),"[0]*([7]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[7])*Gaus(x,[1],[8])/(sqrt(2*3.14159)*[8]))+[3]+[4]*x+[5]*("+iNP+")");
   nt->Project(Form("h%d",count),"mass",Form("%s&&pt>%f&&pt<%f",seldata_2y.Data(),ptmin,ptmax));   
   ntMC->Project(Form("hMC%d",count),"mass",Form("%s&&pt>%f&&pt<%f",seldata_2y.Data(),ptmin,ptmax));   
   clean0(h);

   TH1D *hraw = new TH1D(Form("hraw%d",count),"",50,5,6);
   clean0(hraw);
   hraw = (TH1D*)h->Clone(Form("hraw%d",count));


   h->Draw();
   f->SetParLimits(4,-1000,0);
   f->SetParLimits(2,0.01,0.05);
   f->SetParLimits(8,0.01,0.05);
   f->SetParLimits(7,0,1);
   f->SetParLimits(5,0,1000);

   f->SetParameter(0,setparam0);
   f->SetParameter(1,setparam1);
   f->SetParameter(2,setparam2);
   f->SetParameter(8,setparam3);
   f->FixParameter(1,fixparam1);
   h->GetEntries();

   hMC->Fit(Form("f%d",count),"q","",5,6);
   hMC->Fit(Form("f%d",count),"q","",5,6);
   f->ReleaseParameter(1);
   hMC->Fit(Form("f%d",count),"L q","",5,6);
   hMC->Fit(Form("f%d",count),"L q","",5,6);
   hMC->Fit(Form("f%d",count),"L q","",5,6);
   hMC->Fit(Form("f%d",count),"L m","",5,6);

   f->FixParameter(1,f->GetParameter(1));
   f->FixParameter(2,f->GetParameter(2));
   f->FixParameter(7,f->GetParameter(7));
   f->FixParameter(8,f->GetParameter(8));
   
   h->Fit(Form("f%d",count),"q","",5,6);
   h->Fit(Form("f%d",count),"q","",5,6);
   f->ReleaseParameter(1);
   h->Fit(Form("f%d",count),"L q","",5,6);
   h->Fit(Form("f%d",count),"L q","",5,6);
   h->Fit(Form("f%d",count),"L q","",5,6);
   h->Fit(Form("f%d",count),"L m","",5,6);
   h->SetMarkerSize(0.8);
   h->SetMarkerStyle(20);
   cout <<h->GetEntries()<<endl;

   // function for background shape plotting. take the fit result from f
   TF1 *background = new TF1(Form("background%d",count),"[0]+[1]*x");
   background->SetParameter(0,f->GetParameter(3));
   background->SetParameter(1,f->GetParameter(4));
   background->SetParameter(2,f->GetParameter(5));
   background->SetParameter(3,f->GetParameter(6));
   background->SetLineColor(4);
   background->SetRange(5,6);
   background->SetLineStyle(2);
   
   // function for signal shape plotting. take the fit result from f
   TF1 *Bkpi = new TF1(Form("fBkpi%d",count),"[0]*("+iNP+")");
   Bkpi->SetParameter(0,f->GetParameter(5));
   Bkpi->SetLineColor(kGreen+1);
   Bkpi->SetFillColor(kGreen+1);
//   Bkpi->SetRange(5.00,5.28);
   Bkpi->SetRange(5.00,6.00);
   Bkpi->SetLineStyle(1);
   Bkpi->SetFillStyle(3004);

   // function for signal shape plotting. take the fit result from f
   TF1 *mass = new TF1(Form("fmass%d",count),"[0]*([3]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[3])*Gaus(x,[1],[4])/(sqrt(2*3.14159)*[4]))");
   mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(8));
   mass->SetParError(0,f->GetParError(0));
   mass->SetParError(1,f->GetParError(1));
   mass->SetParError(2,f->GetParError(2));
   mass->SetParError(7,f->GetParError(7));
   mass->SetParError(8,f->GetParError(8));
   mass->SetLineColor(2);
   mass->SetLineStyle(2);

//   cout <<mass->Integral(0,1.2)<<" "<<mass->IntegralError(0,1.2)<<endl;
   h->SetMarkerStyle(24);
   h->SetStats(0);
   h->Draw("e");
   h->SetXTitle("M_{B} (GeV/c^{2})");
   h->SetYTitle("Entries / (20 MeV/c^{2})");
   h->GetXaxis()->CenterTitle();
   h->GetYaxis()->CenterTitle();
   h->SetTitleOffset(1.5,"Y");
   h->SetAxisRange(0,h->GetMaximum()*1.2,"Y");
   Bkpi->Draw("same");
   background->Draw("same");   
   mass->SetRange(5,6);
   mass->Draw("same");
   mass->SetLineStyle(2);
   mass->SetFillStyle(3004);
   mass->SetFillColor(2);
   f->Draw("same");
   hraw->Draw("same");

   double yield = mass->Integral(5,6)/0.02;
   double yieldErr = mass->Integral(5,6)/0.02*mass->GetParError(0)/mass->GetParameter(0);


   // Draw the legend:)   
   TLegend *leg = myLegend(0.50,0.5,0.86,0.89);
   leg->AddEntry(h,"CMS Preliminary","");
   leg->AddEntry(h,"pPb #sqrt{s_{NN}} = 5.02 TeV","");
   leg->AddEntry(h,Form("%.0f < p_{T}^{B} < %.0f GeV/c",ptmin,ptmax),"");
   leg->AddEntry(h,"Data","pl");
   leg->AddEntry(f,"Fit","l");
   leg->AddEntry(mass,"Signal","f");
   leg->AddEntry(background,"Combinatorial Background","l");
   leg->AddEntry(Bkpi,"Non-prompt J/#psi","f");
   leg->Draw();
   TLegend *leg2 = myLegend(0.44,0.33,0.89,0.50);
   leg2->AddEntry(h,"B meson","");
   leg2->AddEntry(h,Form("M_{B} = %.2f #pm %.2f MeV/c^{2}",mass->GetParameter(1)*1000.,mass->GetParError(1)*1000.),"");
   leg2->AddEntry(h,Form("N_{B} = %.0f #pm %.0f", yield, yieldErr),"");
   leg2->Draw();

   if(ispPb)c->SaveAs(Form("../ResultsBplus/BMass-%d.pdf",count));
   else c->SaveAs(Form("../ResultsBplus_pp/BMass-%d.pdf",count));

   h->Write();
   hMC->Write();
   f->Write();
   background->Write();
   Bkpi->Write();
   mass->Write();
   hraw->Write();

   return mass;
}
void DrawCalibrationPlotsEE (
 			     Char_t* infile1 = "data_LC_20120131_ALPHA_test_prompt/SingleElectron_Run2011AB-WElectron-data_LC_20120131_ALPHA_test_prompt_EoPcaibEE_11032011_Z_R9_EE.root",
 			     Char_t* infile2 = "data_LC_20120131_ALPHA_test_prompt/Even_SingleElectron_Run2011AB-WElectron-data_LC_20120131_ALPHA_test_prompt_EoPcaibEE_11032011_Z_R9_EE.root",
 			     Char_t* infile3 = "data_LC_20120131_ALPHA_test_prompt/Odd_SingleElectron_Run2011AB-WElectron-data_LC_20120131_ALPHA_test_prompt_EoPcaibEE_11032011_Z_R9_EE.root",
 			     //Char_t* infile1 = "FT_R_42_V21B/WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_R9_EE.root",
 			     //Char_t* infile2 = "FT_R_42_V21B/Even_WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_R9_EE.root",
 			     //Char_t* infile3 = "FT_R_42_V21B/Odd_WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_R9_EE.root",
			     int evalStat = 1,
                             bool isMC=false,
			     Char_t* fileType = "png", 
			     Char_t* dirName = ".")
{

  bool  printPlots = false;

  /// by xtal

  int nbins = 250;

  /// Set style options
  gROOT->Reset();
  gROOT->SetStyle("Plain");

  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(11110); 
  gStyle->SetOptFit(0); 
  gStyle->SetFitFormat("6.3g"); 
  gStyle->SetPalette(1); 
 
  gStyle->SetTextFont(42);
  gStyle->SetTextSize(0.05);
  gStyle->SetTitleFont(42,"xyz");
  gStyle->SetTitleSize(0.05);
  gStyle->SetLabelFont(42,"xyz");
  gStyle->SetLabelSize(0.05);
  gStyle->SetTitleXOffset(0.8);
  gStyle->SetTitleYOffset(1.1);
  gROOT->ForceStyle();

  if ( !infile1 ) {
    cout << " No input file specified !" << endl;
    return;
  }


  if ( evalStat && (!infile2 || !infile3 )){
    cout << " No input files to evaluate statistical precision specified !" << endl;
    return;
  }

  cout << "Making calibration plots for: " << infile1 << endl;
  
  
  /// imput file with full statistic normlized to the mean in a ring

  TFile *f = new TFile(infile1);
  TH2F *hcmap[2];
  hcmap[0] = (TH2F*)f->Get("h_scale_map_EEM");
  hcmap[1] = (TH2F*)f->Get("h_scale_map_EEP");
    

  /// ring geometry for the endcap
  TH2F *hrings[2];
  hrings[0] = (TH2F*)hcmap[0]->Clone("hringsEEM");
  hrings[1] = (TH2F*)hcmap[0]->Clone("hringsEEP");
  hrings[0] ->Reset("ICMES");
  hrings[1] ->Reset("ICMES");
  hrings[0] ->ResetStats();
  hrings[1] ->ResetStats();

  FILE *fRing;
  fRing = fopen("macros/eerings.dat","r");
  int x,y,z,ir;
  while(fscanf(fRing,"(%d,%d,%d) %d \n",&x,&y,&z,&ir) !=EOF ) {
    if(z>0) hrings[1]->Fill(x,y,ir); 
    if(z<0) hrings[0]->Fill(x,y,ir);
  }

  TFile *f4 = TFile::Open("MCtruthIC_EE.root");
  TFile *f5 = TFile::Open("MCRecoIC_EE.root");

  TH2F *hcmapMcT_EEP = (TH2F*)f4->Get("h_scale_EEP");
  TH2F *hcmapMcT_EEM = (TH2F*)f4->Get("h_scale_EEM");
  TH2F *hcmapMcR_EEP = (TH2F*)f5->Get("h_scale_EEP");
  TH2F *hcmapMcR_EEM = (TH2F*)f5->Get("h_scale_EEM");
 
 
  ///--------------------------------------------------------------------------------
  ///--- Build the precision vs ring plot starting from the TH2F of IC folded and not
  ///--------------------------------------------------------------------------------

  char hname[100];
  char htitle[100];
  TH1F *hspread[2][50];
  TH1F* hspreadAll [40];

  TH2F* ICComparison [2];
  ICComparison[0] = (TH2F*) hcmapMcT_EEP->Clone("ICComparison_EEM");
  ICComparison[1] = (TH2F*) hcmapMcT_EEM->Clone("ICComparison_EEP");
  ICComparison[0]->Reset("ICMES");
  ICComparison[1]->Reset("ICMES");
  ICComparison[0]->ResetStats();
  ICComparison[1]->ResetStats();


  for (int k = 0; k < 2; k++){
         
    for (int iring = 0; iring < 40 ; iring++){
      if (k==0)
      {
       sprintf(hname,"hspreadAll_ring%02d",iring);
       hspreadAll[iring] = new TH1F(hname, hname, nbins,0.,2.);
       sprintf(hname,"hspreadEEM_MCTruth_ring%02d",iring);
       hspread[k][iring] = new TH1F(hname, hname, nbins,0.,2.);

      }
      else{ 
	
        sprintf(hname,"hspreadEEP_ring%02d",iring);
         hspread[k][iring] = new TH1F(hname, hname, nbins,0.,2.);
 
     }
    }
 }
  
 /// spread all distribution, spread for EE+ and EE- and comparison with the MC truth
  for (int k = 0; k < 2 ; k++){
    for (int ix = 1; ix < 101; ix++){
      for (int iy = 1; iy < 101; iy++){
	int iz = k;
	if (k==0) iz = -1;
	int mybin = hcmap[k] -> FindBin(ix,iy);
	int ring  = hrings[1]-> GetBinContent(mybin);
	float ic = hcmap[k]->GetBinContent(mybin);
        float ic2=0;
          if(k==0 && hcmapMcT_EEM->GetBinContent(mybin)!=0 && hcmapMcR_EEM->GetBinContent(mybin)!=0 ) ic2 = hcmapMcT_EEM->GetBinContent(mybin)/hcmapMcR_EEM->GetBinContent(mybin);
          else if(hcmapMcT_EEP->GetBinContent(mybin)!=0 && hcmapMcR_EEP->GetBinContent(mybin)!=0 ) ic2 = hcmapMcT_EEP->GetBinContent(mybin)/hcmapMcR_EEP->GetBinContent(mybin);
          
 	if ( ic>0 && ic2>0 )    {
	  hspread[k][ring]->Fill(ic);
          hspreadAll[ring]->Fill(ic);
          ICComparison[k]->Fill(ix,iy,ic/ic2);
	}
      }
    }
  }
  
  /// Graph Error for spread EE+ and EE-

  TGraphErrors *sigma_vs_ring[3];
  sigma_vs_ring[0] = new TGraphErrors();
  sigma_vs_ring[0]->SetMarkerStyle(20);
  sigma_vs_ring[0]->SetMarkerSize(1);
  sigma_vs_ring[0]->SetMarkerColor(kBlue+2);
  
  sigma_vs_ring[1] = new TGraphErrors();
  sigma_vs_ring[1]->SetMarkerStyle(20);
  sigma_vs_ring[1]->SetMarkerSize(1);
  sigma_vs_ring[1]->SetMarkerColor(kBlue+2);

  sigma_vs_ring[2] = new TGraphErrors();
  sigma_vs_ring[2]->SetMarkerStyle(20);
  sigma_vs_ring[2]->SetMarkerSize(1);
  sigma_vs_ring[2]->SetMarkerColor(kBlue+2);
 
  /// Graph for scale vs ring EE+, EE- and folded

  TGraphErrors *scale_vs_ring[3];
  scale_vs_ring[0] = new TGraphErrors();
  scale_vs_ring[0]->SetMarkerStyle(20);
  scale_vs_ring[0]->SetMarkerSize(1);
  scale_vs_ring[0]->SetMarkerColor(kBlue+2);

  scale_vs_ring[1] = new TGraphErrors();
  scale_vs_ring[1]->SetMarkerStyle(20);
  scale_vs_ring[1]->SetMarkerSize(1);
  scale_vs_ring[1]->SetMarkerColor(kBlue+2);

  scale_vs_ring[2] = new TGraphErrors();
  scale_vs_ring[2]->SetMarkerStyle(20);
  scale_vs_ring[2]->SetMarkerSize(1);
  scale_vs_ring[2]->SetMarkerColor(kBlue+2);
    
  
  TF1 *fgaus = new TF1("fgaus","gaus",-10,10);
  int np[3] = {0};

  /// Gaussian fit for EE+ and EE-

  for (int k = 0; k < 2 ; k++){
    for (int iring = 0; iring < 40; iring++){
      if (hspread[k][iring]-> GetEntries() == 0) continue;
      float e     = 0.5*hcmap[k]-> GetYaxis()->GetBinWidth(1);
      fgaus->SetParameter(1,1);
      fgaus->SetParameter(2,hspread[k][iring]->GetRMS());
      fgaus->SetRange(1-5*hspread[k][iring]->GetRMS(),1+5*hspread[k][iring]->GetRMS());
      hspread[k][iring]->Fit("fgaus","QR");
      sigma_vs_ring[k]-> SetPoint(np[k],iring,fgaus->GetParameter(2));
      sigma_vs_ring[k]-> SetPointError(np[k], e ,fgaus->GetParError(2));
      scale_vs_ring[k]-> SetPoint(np[k],iring,fgaus->GetParameter(1));
      scale_vs_ring[k]-> SetPointError(np[k],e,fgaus->GetParError(1));
      np[k]++;    
    }
  }
  
    for (int iring = 0; iring < 40; iring++){
      if (hspreadAll[iring]-> GetEntries() == 0) continue;
      float e     = 0.5*hcmap[0]-> GetYaxis()->GetBinWidth(1);
      fgaus->SetParameter(1,1);
      fgaus->SetParameter(2,hspreadAll[iring]->GetRMS());
      fgaus->SetRange(1-5*hspreadAll[iring]->GetRMS(),1+5*hspreadAll[iring]->GetRMS());
      hspreadAll[iring]->Fit("fgaus","QR");
      sigma_vs_ring[2]-> SetPoint(np[2],iring,fgaus->GetParameter(2));
      sigma_vs_ring[2]-> SetPointError(np[2], e ,fgaus->GetParError(2));
      scale_vs_ring[2]-> SetPoint(np[2],iring,fgaus->GetParameter(1));
      scale_vs_ring[2]-> SetPointError(np[2],e,fgaus->GetParError(1));
      np[2]++;    
    }

  /// Intercalibration constant vs phi
 
 /* TGraphErrors *IC_vs_phi[2];
  IC_vs_phi[0] = new TGraphErrors();
  IC_vs_phi[0]->SetMarkerStyle(20);
  IC_vs_phi[0]->SetMarkerSize(1);
  IC_vs_phi[0]->SetMarkerColor(kBlue+2);
  
  IC_vs_phi[1] = new TGraphErrors();
  IC_vs_phi[1]->SetMarkerStyle(20);
  IC_vs_phi[1]->SetMarkerSize(1);
  IC_vs_phi[1]->SetMarkerColor(kBlue+2);

  TH1F* Spread_vs_phi[2][360];
  
  for (int k = 0; k < 2; k++){
    for (int iphi = 0; iphi < 360 ; iphi++){
      if (k==0)
      {
       sprintf(hname,"hspread_vs_phi%02d_EEP",iphi);
       Spread_vs_phi[k][iphi] = new TH1F(hname, hname, nbins,0.,2.);

      }
      else{ 
        sprintf(hname,"hspread_vs_ring%02d_EEM",iphi);
        Spread_vs_phi[k][iphi] = new TH1F(hname, hname, nbins,0.,2.);}
     } 
   }
  

  for (int k = 0; k < 2 ; k++){
    for (int ix = 1; ix < 101; ix++){
      for (int iy = 1; iy < 101; iy++){
	float iphibin;
        if((atan2(iy-50.,ix-50.)-int(atan2(iy-50.,ix-50.)))*(360./(2.*3.14159)) <0.5) iphibin=floor(180.+atan2(iy-50.,ix-50.)*(360./(2.*3.14159)));
        else iphibin=ceil(180.+atan2(iy-50.,ix-50.)*(360./(2.*3.14159)));
       
        if(iphibin>359) iphibin=359;
	int mybin = hcmap[k] -> FindBin(ix,iy);
	float ic = hcmap[k]->GetBinContent(mybin);          
	if ( ic>0 )    {
	 Spread_vs_phi[k][iphibin] ->Fill(ic);
	}
      }
    }
  }
 
 int N[2]={0};
  for (int k = 0; k < 2 ; k++){
    for (int iphi = 0; iphi < 360; iphi++){
      if (Spread_vs_phi[k][iphi]-> GetEntries() == 0) continue;
      IC_vs_phi[k]-> SetPoint(N[k],iphi,Spread_vs_phi[k][iphi]->GetMean());
      IC_vs_phi[k]-> SetPointError(N[k],0,Spread_vs_phi[k][iphi]->GetRMS()/sqrt(Spread_vs_phi[k][iphi]->GetEntries()));

      N[k]++;    
    }
  }
  */

 ///----------------- Statistical Precision  and Residual --------------------

    TGraphErrors *statprecision_vs_ring[3];
    statprecision_vs_ring[0]  = new TGraphErrors();
    statprecision_vs_ring[0]->SetMarkerStyle(20);
    statprecision_vs_ring[0]->SetMarkerSize(1);
    statprecision_vs_ring[0]->SetMarkerColor(kRed+2);

    statprecision_vs_ring[1]  = new TGraphErrors();
    statprecision_vs_ring[1]->SetMarkerStyle(20);
    statprecision_vs_ring[1]->SetMarkerSize(1);
    statprecision_vs_ring[1]->SetMarkerColor(kRed+2);

    statprecision_vs_ring[2]  = new TGraphErrors();
    statprecision_vs_ring[2]->SetMarkerStyle(20);
    statprecision_vs_ring[2]->SetMarkerSize(1);
    statprecision_vs_ring[2]->SetMarkerColor(kRed+2);
    
    TGraphErrors *residual_vs_ring[3];
    residual_vs_ring[0] = new TGraphErrors();
    residual_vs_ring[0]->SetMarkerStyle(20);
    residual_vs_ring[0]->SetMarkerSize(1);
    residual_vs_ring[0]->SetMarkerColor(kGreen+2);
  
    residual_vs_ring[1] = new TGraphErrors();
    residual_vs_ring[1]->SetMarkerStyle(20);
    residual_vs_ring[1]->SetMarkerSize(1);
    residual_vs_ring[1]->SetMarkerColor(kGreen+2);
  
    residual_vs_ring[2] = new TGraphErrors();
    residual_vs_ring[2]->SetMarkerStyle(20);
    residual_vs_ring[2]->SetMarkerSize(1);
    residual_vs_ring[2]->SetMarkerColor(kGreen+2);

  
  if (evalStat){
    
    /// acquisition file for statistical precision

    TFile *f2 = new TFile(infile2);
    TFile *f3 = new TFile(infile3);
    TH2F *hcmap2[2];
    hcmap2[0] = (TH2F*)f2->Get("h_scale_map_EEM"); 
    hcmap2[1] = (TH2F*)f2->Get("h_scale_map_EEP");

    TH2F *hcmap3[2];
    hcmap3[0] = (TH2F*)f3->Get("h_scale_map_EEM"); 
    hcmap3[1] = (TH2F*)f3->Get("h_scale_map_EEP");

    TH1F *hstatprecision[2][40];
    TH1F *hstatprecisionAll[40];

    /// stat precision histos for each EE ring
    for (int k = 0; k < 2; k++){
      for (int iring = 0; iring < 40 ; iring ++){
      
	if (k==0)
	 { sprintf(hname,"hstatprecisionAll_ring%02d",iring);
           hstatprecisionAll[iring] = new TH1F(hname, hname, nbins,-2.,2.);
           sprintf(hname,"hstatprecisionEEM_ring%02d",iring);
           hstatprecision[k][iring] = new TH1F(hname, hname, nbins,-2.,2.);
          }
	else {
	      sprintf(hname,"hstatprecisionEEP_ring%02d",iring);
              hstatprecision[k][iring] = new TH1F(hname, hname, nbins,-2.,2.);
            }

      }
    }
    
    for (int k = 0; k < 2 ; k++){
      for (int ix = 1; ix < 102; ix++){
	for (int iy = 1; iy < 102; iy++){
	  int iz = k;
	  if (k==0) iz = -1;
	  int mybin = hcmap2[k] -> FindBin(ix,iy);
	  int ring  = hrings[1]-> GetBinContent(mybin);
	  float ic1 = hcmap2[k]->GetBinContent(mybin);
	  float ic2 = hcmap3[k]->GetBinContent(mybin);
          if (ic1>0 && ic2 >0){
	    hstatprecision[k][ring]->Fill((ic1-ic2)/(ic1+ic2)); /// sigma (diff/sum) gives the stat. precision on teh entire sample
            hstatprecisionAll[ring]->Fill((ic1-ic2)/(ic1+ic2));
	  }
	}
      }
    }

  
    TCanvas* c44 [120];
    /// Gaussian fit of the even/odd distribution (rms of the distribution can be also used)
    int n[3] = {0};
    for (int k = 0; k < 2; k++){
      for (int iring = 0; iring < 40 ; iring++){
	if ( hstatprecision[k][iring]->GetEntries() == 0) continue;
	float e     = 0.5*hcmap2[k]-> GetYaxis()->GetBinWidth(1);
	fgaus->SetParameter(1,1);
	fgaus->SetParameter(2,hstatprecision[k][iring]->GetRMS());
	fgaus->SetRange(-5*hstatprecision[k][iring]->GetRMS(),5*hstatprecision[k][iring]->GetRMS());
	TString name = Form("ff%d_%d",iring,k);

        hstatprecision[k][iring]->Fit("fgaus","QR");
       
	statprecision_vs_ring[k]-> SetPoint(n[k],iring,fgaus->GetParameter(2));
	statprecision_vs_ring[k]-> SetPointError(n[k],e,fgaus->GetParError(2));
	n[k]++;
      }
    }
    
    for (int iring = 0; iring < 40 ; iring++){
	if ( hstatprecisionAll[iring]->GetEntries() == 0) continue;
	float e     = 0.5*hcmap2[0]-> GetYaxis()->GetBinWidth(1);
	fgaus->SetParameter(1,1);
	fgaus->SetParameter(2,hstatprecisionAll[iring]->GetRMS());
	fgaus->SetRange(-5*hstatprecisionAll[iring]->GetRMS(),5*hstatprecisionAll[iring]->GetRMS());
	TString name = Form("ffAll%d",iring);
        hstatprecisionAll[iring]->Fit("fgaus","QR");
       
	statprecision_vs_ring[2]-> SetPoint(n[2],iring,fgaus->GetParameter(2));
	statprecision_vs_ring[2]-> SetPointError(n[2],e,fgaus->GetParError(2));
	n[2]++;
      }
     
    
    TH1F *hresidual[3];
    hresidual[0] = new TH1F("hresidualEEM","hresidualEEM",1000,0,1);
    hresidual[1] = new TH1F("hresidualEEP","hresidualEEP",1000,0,1);
    hresidual[2] = new TH1F("hresidualAll","hresidualAll",1000,0,1);

    TH1F *hstat[3];
    hstat[0] = new TH1F("hstatEEM","hstatEEM",1000,0,0.5);
    hstat[1] = new TH1F("hstatEEP","hstatEEP",1000,0,0.5);
    hstat[2] = new TH1F("hstatAll","hstatAll",1000,0,0.5);
   
    TH1F *hspre[3];
    hspre[0] = new TH1F("hspreEEM","hspreEEM",1000,0,0.5);
    hspre[1] = new TH1F("hspreEEP","hspreEEP",1000,0,0.5);
    hspre[2] = new TH1F("hspreAll","hspreAll",1000,0,0.5);

    /// Residual spread plot

    for (int k = 0; k < 3 ; k++){
      for (int i= 0; i < statprecision_vs_ring[k]-> GetN(); i++){
	double spread, espread;
	double stat, estat;
	double residual, eresidual;
	double xdummy,ex;
	sigma_vs_ring[k]-> GetPoint(i, xdummy, spread );
	espread = sigma_vs_ring[k]-> GetErrorY(i);
	statprecision_vs_ring[k]-> GetPoint(i, xdummy, stat );
	estat = statprecision_vs_ring[k]-> GetErrorY(i);
	ex = statprecision_vs_ring[k]-> GetErrorX(i);
	if (spread > stat ){
	  residual  = sqrt( spread*spread - stat*stat );
	  eresidual = sqrt( pow(spread*espread,2) + pow(stat*estat,2))/residual;
	}
	else {
	  residual = 0;
	  eresidual = 0;
	}
	residual_vs_ring[k]->SetPoint(i,xdummy, residual);
	residual_vs_ring[k]->SetPointError(i,ex,eresidual);
      }
    }
 
 }
  
  ///-----------------------------------------------------------------
  ///--- Draw plots
  ///-----------------------------------------------------------------
  TCanvas *cEEP[12];
  TCanvas *cEEM[12];

  /// --- plot 0 : map of coefficients 
  cEEP[0] = new TCanvas("cmapEEP","cmapEEP");
  cEEP[0] -> cd();
  cEEP[0]->SetLeftMargin(0.1); 
  cEEP[0]->SetRightMargin(0.13); 
  cEEP[0]->SetGridx();
  cEEP[0]->SetGridy();
  //  hcmap[1]->GetXaxis()->SetNdivisions(1020);
  hcmap[1]->GetXaxis() -> SetLabelSize(0.03);
  hcmap[1]->Draw("COLZ");
  hcmap[1]->GetXaxis() ->SetTitle("ix");
  hcmap[1]->GetYaxis() ->SetTitle("iy");
  hcmap[1]->GetZaxis() ->SetRangeUser(0.8,1.2);

  cEEM[0] = new TCanvas("cmapEEM","cmapEEM");
  cEEM[0] -> cd();
  cEEM[0]->SetLeftMargin(0.1); 
  cEEM[0]->SetRightMargin(0.13); 
  cEEM[0]->SetGridx();
  cEEM[0]->SetGridy();
  //hcmap[0]->GetXaxis()->SetNdivisions(1020);
  hcmap[0]->GetXaxis() -> SetLabelSize(0.03);
  hcmap[0]->Draw("COLZ");
  hcmap[0]->GetXaxis() ->SetTitle("ix");
  hcmap[0]->GetYaxis() ->SetTitle("iy");
  hcmap[0]->GetZaxis() ->SetRangeUser(0.8,1.2);

  /// --- plot 1 : ring precision vs ieta
  cEEP[1] = new TCanvas("csigmaEEP","csigmaEEP");
  cEEP[1]->SetGridx();
  cEEP[1]->SetGridy();
  sigma_vs_ring[1]->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.20);
  sigma_vs_ring[1]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  sigma_vs_ring[1]->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
  sigma_vs_ring[1]->GetHistogram()->GetXaxis()-> SetTitle("ring");
  sigma_vs_ring[1]->Draw("ap");
  if (evalStat){
    statprecision_vs_ring[1]->Draw("psame");
    sigma_vs_ring[1]->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ring[1],"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ring[1],"spread", "LP");
    leg->Draw("same");
  }

  cEEM[1] = new TCanvas("csigmaEEM","csigmaEEM");
  cEEM[1]->SetGridx();
  cEEM[1]->SetGridy();
  sigma_vs_ring[0]->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.20);
  sigma_vs_ring[0]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  sigma_vs_ring[0]->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
  sigma_vs_ring[0]->GetHistogram()->GetXaxis()-> SetTitle("ring");
  sigma_vs_ring[0]->Draw("ap");
  if (evalStat){
    statprecision_vs_ring[0]->Draw("psame");
    sigma_vs_ring[0]->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ring[0],"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ring[0],"spread", "LP");
    leg->Draw("same");
  }


  /// --- plot 5 : statistical precision vs ieta
  if (evalStat){
    cEEP[5] = new TCanvas("cstat","cstat");
    cEEP[5]->SetGridx();
    cEEP[5]->SetGridy();
    statprecision_vs_ring[1]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    statprecision_vs_ring[1]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    statprecision_vs_ring[1]->GetHistogram()->GetYaxis()-> SetTitle("#sigma((c_{P}-c_{D})/(c_{P}+c_{D}))");
    statprecision_vs_ring[1]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    statprecision_vs_ring[1]->Draw("ap");
    
    cEEP[6] = new TCanvas("cresidualP","cresidualP");
    cEEP[6]->SetGridx();
    cEEP[6]->SetGridy();
    residual_vs_ring[1]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    residual_vs_ring[1]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    residual_vs_ring[1]->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
    residual_vs_ring[1]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    residual_vs_ring[1]->Draw("ap");
 
    cEEM[5] = new TCanvas("cstatM","cstatM");
    cEEM[5]->SetGridx();
    cEEM[5]->SetGridy();
    statprecision_vs_ring[0]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    statprecision_vs_ring[0]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    statprecision_vs_ring[0]->GetHistogram()->GetYaxis()-> SetTitle("#sigma((c_{P}-c_{D})/(c_{P}+c_{D}))");
    statprecision_vs_ring[0]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    statprecision_vs_ring[0]->Draw("ap");
    
    cEEM[6] = new TCanvas("cresidualM","cresidualM");
    cEEM[6]->SetGridx();
    cEEM[6]->SetGridy();
    residual_vs_ring[0]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    residual_vs_ring[0]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    residual_vs_ring[0]->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
    residual_vs_ring[0]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    residual_vs_ring[0]->Draw("ap");
 
    cEEP[8] = new TCanvas("csigmaFolded","csigmaFolded");
    cEEP[8]->SetGridx();
    cEEP[8]->SetGridy();
    sigma_vs_ring[2]->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.20);
    sigma_vs_ring[2]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    sigma_vs_ring[2]->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
    sigma_vs_ring[2]->GetHistogram()->GetXaxis()-> SetTitle("ring");
    sigma_vs_ring[2]->Draw("ap");
    if (evalStat){
    statprecision_vs_ring[2]->Draw("psame");
    sigma_vs_ring[2]->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ring[2],"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ring[2],"spread", "LP");
    leg->Draw("same");
    }

    cEEP[9] = new TCanvas("cresidualFolded","cresidualFolded");
    cEEP[9]->SetGridx();
    cEEP[9]->SetGridy();
    residual_vs_ring[2]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    residual_vs_ring[2]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    residual_vs_ring[2]->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
    residual_vs_ring[2]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    residual_vs_ring[2]->Draw("ap");

    /// save precision for MC comparison

    if(isMC==true)
    {
     TFile * output = new TFile ("StatPrec_MC_EE.root","RECREATE");
     output->cd();
     statprecision_vs_ring[0]->SetName("gr_stat_prec_EEP");
     statprecision_vs_ring[1]->SetName("gr_stat_prec_EEM");
     statprecision_vs_ring[2]->SetName("gr_stat_prec");

     statprecision_vs_ring[0]->Write();
     statprecision_vs_ring[1]->Write();
     statprecision_vs_ring[2]->Write();
    }
  }
 
  /// Comparison Plot MC - Data
  TCanvas* canEEP[10], *canEEM[10];
  if(isMC == true)
  {
 
   canEEM[0] = new TCanvas("ICComparison MC EEM","ICComparison MC EEM");
   canEEM[0]->SetGridx();
   canEEM[0]->SetGridy();
   ICComparison[0]->GetXaxis() -> SetLabelSize(0.03);
   ICComparison[0]->Draw("COLZ");
   ICComparison[0]->GetXaxis() ->SetTitle("ix");
   ICComparison[0]->GetYaxis() ->SetTitle("iy");
   ICComparison[0]->GetZaxis() ->SetRangeUser(0.85,1.15);
 
   canEEP[0] = new TCanvas("ICComparison MC EEP","ICComparison MC EEP");
   canEEP[0]->SetGridx();
   canEEP[0]->SetGridy();
   ICComparison[1]->GetXaxis() -> SetLabelSize(0.03);
   ICComparison[1]->Draw("COLZ");
   ICComparison[1]->GetXaxis() ->SetTitle("ix");
   ICComparison[1]->GetYaxis() ->SetTitle("iy");
   ICComparison[1]->GetZaxis() ->SetRangeUser(0.85,1.15);

   TFile* output = new TFile ("IC_MC_4Correction.root","RECREATE");
   output->cd();
   ICComparison[0]->Write();
   ICComparison[1]->Write();
   output->Close();
  }

  TFile *exisistingEE = new TFile ("existingEE.root","READ");
  TH2F* exmap = (TH2F*) exisistingEE->Get("endcap");

  TH2F* warning_Map_EEP = (TH2F*) exmap->Clone("warning_Map_EEP");
  warning_Map_EEP->Reset("ICMES");
  warning_Map_EEP->Reset();

  TH2F* warning_Map_EEM = (TH2F*) exmap->Clone("warning_Map_EEM");
  warning_Map_EEM->Reset("ICMES");
  warning_Map_EEM->Reset();


  if(isMC == false)
  {
   std::ofstream outTxt ("Calibration_Coefficient_EE_dinamic_alpha.txt",std::ios::out);

   outTxt << "---------------------------------------------------------------" << std::endl;
   outTxt << std::fixed << std::setprecision(0) << std::setw(10) << "iX"
          << std::fixed << std::setprecision(0) << std::setw(10) << "iY"
          << std::fixed << std::setprecision(0) << std::setw(10) << "iZ"
          << std::fixed << std::setprecision(6) << std::setw(15) << "IC"
          << std::fixed << std::setprecision(6) << std::setw(15) << "error"
          << std::endl;
   outTxt << "---------------------------------------------------------------" << std::endl;

   for (int ix = 1; ix < hcmap[0]->GetNbinsX()+1 ; ix ++)
     {
       for (int iy = 1; iy < hcmap[0] -> GetNbinsY()+1; iy++)
	 {
	   if( exmap->GetBinContent(ix,iy) !=1) continue;
	   
	   double x,statPrec;
	   statprecision_vs_ring[0]->GetPoint(hrings[0]->GetBinContent(ix,iy),x,statPrec);
	   
	   outTxt << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[0]->GetXaxis()->GetBinLowEdge(ix)
		  << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[0]->GetYaxis()->GetBinLowEdge(iy)
		  << std::fixed << std::setprecision(0) << std::setw(10) << "-1";
	   
	   if( hcmap[0]->GetBinContent(ix,iy) == 0. )
	     {  
               outTxt << std::fixed << std::setprecision(6) << std::setw(15) << "-1."
                      << std::fixed << std::setprecision(6) << std::setw(15) << "999."
                      << std::endl;
	     }
	   else
	     {
	       outTxt << std::fixed << std::setprecision(6) << std::setw(15) << hcmap[0]->GetBinContent(ix,iy)
		      << std::fixed << std::setprecision(6) << std::setw(15) << statPrec
		      << std::endl;
	       
	       //warning_Map_EEM->Fill(ix,iy);
	     }
	  
	}
    }
    
    for (int ix = 1; ix < hcmap[1]->GetNbinsX()+1 ; ix ++)
      {
	for (int iy = 1; iy < hcmap[1] -> GetNbinsY()+1; iy++)
	  {
	    if( exmap->GetBinContent(ix,iy) !=1) continue;
	    
	    double x,statPrec;
	    statprecision_vs_ring[1]->GetPoint(hrings[1]->GetBinContent(ix,iy),x,statPrec);
	    
	    outTxt << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[1]->GetXaxis()->GetBinLowEdge(ix)
		   << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[1]->GetYaxis()->GetBinLowEdge(iy)
		   << std::fixed << std::setprecision(0) << std::setw(10) << "1";
	    
	    if( hcmap[1]->GetBinContent(ix,iy) == 0. )
	      {
		outTxt << std::fixed << std::setprecision(6) << std::setw(15) << "-1."
		       << std::fixed << std::setprecision(6) << std::setw(15) << "999."
		       << std::endl;
	      }
	    else
	      {
		outTxt << std::fixed << std::setprecision(6) << std::setw(15) << hcmap[1]->GetBinContent(ix,iy)
		       << std::fixed << std::setprecision(6) << std::setw(15) << statPrec
		       << std::endl;
		
		//warning_Map_EEM->Fill(ix,iy);                                                                                                                               
	      }
	    
	  }
      }
  }
  
  
  canEEP[1] = new TCanvas("Warning_EEP","Warning_EEP");
  canEEP[1]->SetGridx();
  canEEP[1]->SetGridy();
  warning_Map_EEP->GetXaxis() -> SetLabelSize(0.03);
  warning_Map_EEP->Draw("COLZ");
  warning_Map_EEP->GetXaxis() ->SetTitle("ix");
  warning_Map_EEP->GetYaxis() ->SetTitle("iy");
  warning_Map_EEP->GetZaxis() ->SetRangeUser(0.85,1.15);

  canEEM[1] = new TCanvas("Warning_EEM","Warning_EEM");
  canEEM[1]->SetGridx();
  canEEM[1]->SetGridy();
  warning_Map_EEM->GetXaxis() -> SetLabelSize(0.03);
  warning_Map_EEM->Draw("COLZ");
  warning_Map_EEM->GetXaxis() ->SetTitle("ix");
  warning_Map_EEM->GetYaxis() ->SetTitle("iy");
  warning_Map_EEM->GetZaxis() ->SetRangeUser(0.85,1.15);



}
Esempio n. 10
0
TF1* fitMass(TH1D* hData, TH1D* hMCSignal, TH1D* hMCSwapped)
{
  Double_t setparam0=100.;
  Double_t setparam1=1.865;
  Double_t setparam2=0.03;
  Double_t setparam10=0.005;
  Double_t setparam8=0.1;
  Double_t setparam9=0.1;
  Double_t fixparam1=1.865;
  Double_t minhisto=1.7;
  Double_t maxhisto=2.0;

  TF1* f = new TF1("fMass","[0]*([7]*([9]*Gaus(x,[1],[2]*(1+[11]))/(sqrt(2*3.1415927)*[2]*(1+[11]))+(1-[9])*Gaus(x,[1],[10]*(1+[11]))/(sqrt(2*3.1415927)*[10]*(1+[11])))+(1-[7])*Gaus(x,[1],[8]*(1+[11]))/(sqrt(2*3.1415927)*[8]*(1+[11])))+[3]+[4]*x+[5]*x*x+[6]*x*x*x", 1.7, 2.0);
  f->SetParLimits(4,-1000,1000);
  f->SetParLimits(10,0.005,0.05);
  f->SetParLimits(2,0.01,0.1);
  f->SetParLimits(8,0.02,0.2);
  f->SetParLimits(7,0,1);
  f->SetParLimits(9,0,1);

  f->SetParameter(0,setparam0);
  f->SetParameter(1,setparam1);
  f->SetParameter(2,setparam2);
  f->SetParameter(10,setparam10);
  f->SetParameter(9,setparam9);

  f->FixParameter(8,setparam8);
  f->FixParameter(7,1);
  f->FixParameter(1,fixparam1);
  f->FixParameter(3,0);
  f->FixParameter(4,0);
  f->FixParameter(5,0);
  f->FixParameter(6,0);
  f->FixParameter(11,0);

  hMCSignal->Fit("fMass","q","",minhisto,maxhisto);
  hMCSignal->Fit("fMass","q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  hMCSignal->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSignal->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSignal->Fit("fMass","L m","",minhisto,maxhisto);

  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(10,f->GetParameter(10));
  f->FixParameter(9,f->GetParameter(9));
  f->FixParameter(7,0);
  f->ReleaseParameter(8);
  f->SetParameter(8,setparam8);

  hMCSwapped->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSwapped->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSwapped->Fit("fMass","L q","",minhisto,maxhisto);
  hMCSwapped->Fit("fMass","L m","",minhisto,maxhisto);

  f->FixParameter(7,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(8,f->GetParameter(8));
  f->ReleaseParameter(3);
  f->ReleaseParameter(4);
  f->ReleaseParameter(5);
  f->ReleaseParameter(6);

  f->SetLineColor(kRed);

  hData->Fit("fMass","q","",minhisto,maxhisto);
  hData->Fit("fMass","q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  f->SetParLimits(1,1.86,1.87);
  f->ReleaseParameter(11);
  f->SetParLimits(11,-0.2,0.2);
  hData->Fit("fMass","L q","",minhisto,maxhisto);
  hData->Fit("fMass","L q","",minhisto,maxhisto);
  hData->Fit("fMass","L q","",minhisto,maxhisto);
  hData->Fit("fMass","L m","",minhisto,maxhisto);

  TF1* background = new TF1("fBackground","[0]+[1]*x+[2]*x*x+[3]*x*x*x");
  background->SetParameter(0,f->GetParameter(3));
  background->SetParameter(1,f->GetParameter(4));
  background->SetParameter(2,f->GetParameter(5));
  background->SetParameter(3,f->GetParameter(6));
  background->SetLineColor(4);
  background->SetRange(minhisto,maxhisto);
  background->SetLineStyle(2);

  TF1* mass = new TF1("fSignal","[0]*([3]*([4]*Gaus(x,[1],[2]*(1+[6]))/(sqrt(2*3.1415927)*[2]*(1+[6]))+(1-[4])*Gaus(x,[1],[5]*(1+[6]))/(sqrt(2*3.1415927)*[5]*(1+[6]))))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10),f->GetParameter(11));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(7));
  mass->SetParError(4,f->GetParError(9));
  mass->SetParError(5,f->GetParError(10));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);

  TF1* massSwap = new TF1("fBackground","[0]*(1-[2])*Gaus(x,[1],[3]*(1+[4]))/(sqrt(2*3.1415927)*[3]*(1+[4]))");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8),f->GetParameter(11));
  massSwap->SetParError(0,f->GetParError(0));
  massSwap->SetParError(1,f->GetParError(1));
  massSwap->SetParError(2,f->GetParError(7));
  massSwap->SetParError(3,f->GetParError(8));
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);

  hData->SetXTitle("m_{#piK} (GeV/c^{2})");
  hData->SetYTitle("Entries / (5 MeV/c^{2})");
  hData->SetAxisRange(0,hData->GetBinContent(hData->GetMaximumBin())*1.4*1.2,"Y");
  hData->SetMarkerSize(0.3);
  hData->Draw("e");

  cout<<"hData->GetMaximum(): "<<hData->GetMaximum()<<endl;

  background->Draw("same");
  mass->SetRange(minhisto,maxhisto);
  mass->Draw("same");
  massSwap->SetRange(minhisto,maxhisto);
  massSwap->Draw("same");
  f->Draw("same");

  Double_t yield = mass->Integral(minhisto,maxhisto)/hData->GetBinWidth(1);
  Double_t yieldErr = mass->Integral(minhisto,maxhisto)/hData->GetBinWidth(1)*mass->GetParError(0)/mass->GetParameter(0);

  std::cout<<"integral function yield: "<<yield<<"    fit yield: "<<f->GetParameter(0)*f->GetParameter(7)/hData->GetBinWidth(1)<<" +- "<<f->GetParError(0)*f->GetParameter(7)/hData->GetBinWidth(1)<<std::endl;

  TLegend* leg = new TLegend(0.65,0.5,0.82,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.06);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry(hData,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D^{0}+#bar{D^{#lower[0.2]{0}}} Signal","f");
  leg->AddEntry(massSwap,"K-#pi swapped","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  hData->GetFunction("fMass")->Delete();
  TH1D* hDataNoFitFun = (TH1D*) hData->Clone("hDataNoFitFun");
  hDataNoFitFun->Draw("esame");

  return f;
}
Esempio n. 11
0
int main(int argc, char** argv){

	// because root is a piece of shit	
	gSystem->Load("libTree");

	if (argc != 2){
		printf("Usage: ./pulse_shape <gain_meas root file>\n\te.g. ./pulse_shape test.root\n");
		return -1;
	}

	char* file_name = argv[1];
//	float t_min = -70e-9, t_max = 130e-9, u_min = -1., u_max = 2.; 
	int sample_len;
	float baseline;
	

	// open root file and extract tree
 	printf("[Pulse Shape] - Opening file '%s'..\n", file_name);
	TFile* in_file = TFile::Open(file_name, "READ");
	TTree* in_tree = (TTree*)in_file->Get("outtree");
	in_tree->SetBranchAddress("len", &sample_len);
	in_tree->SetBranchAddress("baseline", &baseline);
	in_tree->GetEntry(0);

	double* u = new double[sample_len];
	double* t = new double[sample_len];
	in_tree->SetBranchAddress("amplitude", u);
	in_tree->SetBranchAddress("time", t);
	const int nEvents = in_tree->GetEntries();

 	printf("[Pulse Shape] - Found tree with %i events, %i samples per event.\n", nEvents, sample_len);

	TFile* out_file = new TFile("out.root", "RECREATE");
	TTree* out_tree = new TTree("out_tree", "outtree");
	double riseTime, fallTime, pulseDuration;
	out_tree->Branch("risetime", &riseTime);
	out_tree->Branch("falltime", &fallTime);
	out_tree->Branch("pulseduration", &pulseDuration);
	
	TCanvas* c1 = new TCanvas();
	TGraph* pulse = new TGraph();
	pulse->SetTitle("Output pulse;t [s];U [V]");
	pulse->SetMarkerStyle(7);
	TGraph* rf = new TGraph();	// drawing rise and fall time points
	rf->SetMarkerStyle(8);
	rf->SetMarkerColor(46);
	TF1* bl = new TF1("baseline", "[0]", -100, 100);	// baseline
	bl->SetLineColor(38);
	
        // loop over data
	float uMax, lPos, hPos, lTime, hTime, rTime, buf;
	int maxEntry;
        for (int iEvent = 0; iEvent < nEvents; iEvent++){
                uMax = -1.;
                in_tree->GetEntry(iEvent);
                for (int i = 0; i < sample_len; i++){
                        u[i] *= -1;
                        pulse->SetPoint(i, t[i], u[i]);
                        // find Maximum by Hand because root apparently isnt able to do so
                        if (u[i] > uMax){
                                uMax = u[i];
                                maxEntry = i;
                        }
                }
		// get 10% and 90% amplitude
                lPos = 0.1*(uMax - baseline) + baseline;
                hPos = 0.9*(uMax - baseline) + baseline;
                
		// get rise time -> start at maximum and go left
		lTime = -1;
                hTime = -1;
                for (int i = maxEntry; (buf = pulse->GetY()[i]) > 0.9*lPos; i--){
                        if ( buf > hPos )
                                hTime = pulse->GetX()[i];
                        if ( buf > lPos ){
                                lTime = pulse->GetX()[i];
                        }
                }
                riseTime = hTime - lTime;
		rf->SetPoint(0, lTime, lPos);               
		rf->SetPoint(1, hTime, hPos);               
 
		// get fall time -> start at maximum and go right
		rTime = -1;
                hTime = -1;
                for (int i = maxEntry; (buf = pulse->GetY()[i]) > 0.9*lPos; i++){
                        if ( buf > hPos )
                                hTime = pulse->GetX()[i];
                        if ( buf > lPos ){
                                rTime = pulse->GetX()[i];
                        }
                }
                fallTime = rTime - hTime;
		pulseDuration = rTime - lTime; 
		rf->SetPoint(2, rTime, lPos);               
		rf->SetPoint(3, hTime, hPos);               

		out_tree->Fill();

                // draw & save every 500th event
                if (iEvent%100 == 0) {
 			printf("[Pulse Shape] - Risetime = %e s\n", riseTime);
			printf("[Pulse Shape] - Falltime = %e s\n", pulseDuration);
 			printf("[Pulse Shape] - Pulse duration = %e s\n", fallTime);
			
			bl->SetParameter(0, baseline);
                        pulse->Draw("A*");
			bl->Draw("SAME");
			rf->Draw("SAME*");
			c1->Write();
                }
	}




	// cleanup
	out_tree->Write();
	out_file->Close();
	in_file->Close();
	return 0;
}
Esempio n. 12
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","",1300,1000);
//  c15->Divide(3,5);
	c15->Divide(5,5);

  TFile* fPP = new TFile("bFeedDownPP.hist.root");
  TFile* fPPMB = new TFile("bFeedDownPPMB.hist.root");
  TFile* fPPMC = new TFile("bFeedDownPPMC.hist.root");
  TFile* fPPMBMC = new TFile("bFeedDownPPMBMC.hist.root");

  TH3D* hDataPP = (TH3D*)fPP->Get("hData");
  TH3D* hSidebandPP = (TH3D*)fPP->Get("hSideband");
  TH3D* hDataPPMB = (TH3D*)fPPMB->Get("hData");
  TH3D* hSidebandPPMB = (TH3D*)fPPMB->Get("hSideband");
  TH3D* hPtMD0DcaPP = (TH3D*)fPP->Get("hPtMD0Dca");
  TH3D* hPtMD0DcaPPMB = (TH3D*)fPPMB->Get("hPtMD0Dca");

  TH3D* hMCPSignalPP = (TH3D*)fPPMC->Get("hMCPSignal");
  TH3D* hMCNPSignalPP = (TH3D*)fPPMC->Get("hMCNPSignal");
  TH3D* hMCPSignalPPMB = (TH3D*)fPPMBMC->Get("hMCPSignal");
  TH3D* hMCNPSignalPPMB = (TH3D*)fPPMBMC->Get("hMCNPSignal");
  TH3D* hPtMD0DcaMCPSignalPP = (TH3D*)fPPMC->Get("hPtMD0DcaMCPSignal");
  TH3D* hPtMD0DcaMCPSwappedPP = (TH3D*)fPPMC->Get("hPtMD0DcaMCPSwapped");
  TH3D* hPtMD0DcaMCPSignalPPMB =(TH3D*)fPPMBMC->Get("hPtMD0DcaMCPSignal");
  TH3D* hPtMD0DcaMCPSwappedPPMB = (TH3D*)fPPMBMC->Get("hPtMD0DcaMCPSwapped");

  TH3D* hData = (TH3D*)hDataPP->Clone("hData");
  hData->Sumw2();
  hData->Add(hDataPPMB);

  TH3D* hSideband = (TH3D*)hSidebandPP->Clone("hSideband");
  hSideband->Sumw2();
  hSideband->Add(hSidebandPPMB);

  TH3D* hPtMD0Dca = (TH3D*)hPtMD0DcaPP->Clone("hPtMD0Dca");
  hPtMD0Dca->Sumw2();
  hPtMD0Dca->Add(hPtMD0DcaPPMB);

  TH3D* hMCPSignal = (TH3D*)hMCPSignalPP->Clone("hMCPSignal");
  hMCPSignal->Sumw2();
  hMCPSignal->Add(hMCPSignalPPMB);

  TH3D* hMCNPSignal = (TH3D*)hMCNPSignalPP->Clone("hMCNPSignal");
  hMCNPSignal->Sumw2();
  hMCNPSignal->Add(hMCNPSignalPPMB);

  TH3D* hPtMD0DcaMCPSignal = (TH3D*)hPtMD0DcaMCPSignalPP->Clone("hPtMD0DcaMCPSignal");
  hPtMD0DcaMCPSignal->Sumw2();
  hPtMD0DcaMCPSignal->Add(hPtMD0DcaMCPSignalPPMB);

  TH3D* hPtMD0DcaMCPSwapped =(TH3D*)hPtMD0DcaMCPSwappedPP->Clone("hPtMD0DcaMCPSwapped");
  hPtMD0DcaMCPSwapped->Sumw2();
  hPtMD0DcaMCPSwapped->Add(hPtMD0DcaMCPSwappedPPMB);

  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, "PP #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};

  const int nPtBins = 9;
  float ptBins[nPtBins+1] = {2.,4.,6.,8.,10.,12.5,20.,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];

  TH1D *D0DcaDataOut[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;
*/
  const int nBinY = 20;
  Float_t binsY[nBinY+1] = {-0.0734,-0.0562,-0.0428,-0.0320,-0.0236,-0.0170,-0.0118,-0.0078,-0.0046,-0.002,0.0,0.002,0.0046,0.0078,0.0118,0.0170,0.0236,0.0320,0.0428,0.0562,0.0734};



  for(int i=1; i<=nPtBins; 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.07,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/PP_%.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/PP_%.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<=20; 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/PP_%.0f_%.0f_invMassFit.pdf",ptLow,ptHigh));

    if(pts[i-1]<=20)
    {     D0DcaDataOut[i-1]=(TH1D*)hD0DcaDataFit->Clone(Form("D0DcaDataOut_pt%i",i-1));}
    if(pts[i-1]>20)
    {      D0DcaDataOut[i-1]=(TH1D*)hD0DcaDataSubSideBand->Clone(Form("D0DcaDataOut_pt%i",i-1));
      mutiplyBinWidth(D0DcaDataOut[i-1]);
    }



      divideBinWidth(hD0DcaDataFit);

      c4->cd(1);
      gPad->SetLogy();
 
      normalize(hD0DcaMCPSignal);
      setColorTitleLabel(hD0DcaMCPSignal, 2);
      hD0DcaMCPSignal->GetXaxis()->SetRangeUser(-0.07,0.07);
   
      normalize(hD0DcaMCNPSignal);
      setColorTitleLabel(hD0DcaMCNPSignal, 4);
      hD0DcaMCNPSignal->GetXaxis()->SetRangeUser(-0.07,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]>8) 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.5, 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.08;
      float fitRangeH = 0.08;
      
      hD0DcaData->GetXaxis()->SetRangeUser(-0.07,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/PP_%.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.07,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;

    }
  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->cd();
  for (int i = 0; i<nPtBins;i++){
    D0DcaDataOut[i]->Write();
  }

  fOut->Write();
  fOut->Close();

	cout<<"end of main"<<endl;
}
Esempio n. 13
0
TF1* fit(Double_t ptmin, Double_t ptmax)
{
  TCanvas* c = new TCanvas(Form("c_%.0f_%.0f",ptmin,ptmax),"",600,600);
  TFile* infile = new TFile(Form("%s_%s_%.0f_%.0f.root",infname.Data(),collisionsystem.Data(),ptmin,ptmax));
  TH1D* h = (TH1D*)infile->Get("h");                    h->SetName(Form("h_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSignal = (TH1D*)infile->Get("hMCSignal");    hMCSignal->SetName(Form("hMCSignal_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSwapped = (TH1D*)infile->Get("hMCSwapped");  hMCSwapped->SetName(Form("hMCSwapped_%.0f_%.0f",ptmin,ptmax));
  TF1* f = new TF1(Form("f_%.0f_%.0f",ptmin,ptmax),"[0]*([7]*([9]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[9])*Gaus(x,[1],[10])/(sqrt(2*3.14159)*[10]))+(1-[7])*Gaus(x,[1],[8])/(sqrt(2*3.14159)*[8]))+[3]+[4]*x+[5]*x*x", 1.7, 2.0);

  f->SetParLimits(4,-1000,1000);
  f->SetParLimits(10,0.001,0.05);
  f->SetParLimits(2,0.01,0.1);
  f->SetParLimits(8,0.02,0.2);
  f->SetParLimits(7,0,1);
  f->SetParLimits(9,0,1);
  
  f->SetParameter(0,setparam0);
  f->SetParameter(1,setparam1);
  f->SetParameter(2,setparam2);
  f->SetParameter(10,setparam10);
  f->SetParameter(9,setparam9);

  f->FixParameter(8,setparam8);
  f->FixParameter(7,1);
  f->FixParameter(1,fixparam1);
  f->FixParameter(3,0);
  f->FixParameter(4,0);
  f->FixParameter(5,0);
  h->GetEntries();
  
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m","",minhisto,maxhisto);
  
  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(10,f->GetParameter(10));
  f->FixParameter(9,f->GetParameter(9));
  f->FixParameter(7,0);
  f->ReleaseParameter(8);
  f->SetParameter(8,setparam8);
  
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m","",minhisto,maxhisto);
  
  f->FixParameter(7,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(8,f->GetParameter(8));
  f->ReleaseParameter(3);
  f->ReleaseParameter(4);
  f->ReleaseParameter(5);

  f->SetLineColor(kRed);
  
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  //f->ReleaseParameter(2);                                     // you need to release these two parameters if you want to perform studies on the sigma shape
  //f->ReleaseParameter(10);                                   // you need to release these two parameters if you want to perform studies on the sigma shape
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m","",minhisto,maxhisto);
  
  TF1* background = new TF1(Form("background_%.0f_%.0f",ptmin,ptmax),"[0]+[1]*x+[2]*x*x");
  background->SetParameter(0,f->GetParameter(3));
  background->SetParameter(1,f->GetParameter(4));
  background->SetParameter(2,f->GetParameter(5));
  background->SetLineColor(4);
  background->SetRange(minhisto,maxhisto);
  background->SetLineStyle(2);
  
  TF1* mass = new TF1(Form("fmass_%.0f_%.0f",ptmin,ptmax),"[0]*([3]*([4]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[4])*Gaus(x,[1],[5])/(sqrt(2*3.14159)*[5])))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(7));
  mass->SetParError(4,f->GetParError(9));
  mass->SetParError(5,f->GetParError(10));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);
  
  TF1* massSwap = new TF1(Form("fmassSwap_%.0f_%.0f",ptmin,ptmax),"[0]*(1-[2])*Gaus(x,[1],[3])/(sqrt(2*3.14159)*[3])");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8));
  massSwap->SetParError(0,f->GetParError(0));
  massSwap->SetParError(1,f->GetParError(1));
  massSwap->SetParError(2,f->GetParError(7));
  massSwap->SetParError(3,f->GetParError(8));
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);
  
  h->SetXTitle("m_{#piK} (GeV/c^{2})");
  h->SetYTitle("Entries / (5 MeV/c^{2})");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  h->SetAxisRange(0,h->GetMaximum()*1.4*1.2,"Y");
  h->GetXaxis()->SetTitleOffset(1.3);
  h->GetYaxis()->SetTitleOffset(1.8);
  h->GetXaxis()->SetLabelOffset(0.007);
  h->GetYaxis()->SetLabelOffset(0.007);
  h->GetXaxis()->SetTitleSize(0.045);
  h->GetYaxis()->SetTitleSize(0.045);
  h->GetXaxis()->SetTitleFont(42);
  h->GetYaxis()->SetTitleFont(42);
  h->GetXaxis()->SetLabelFont(42);
  h->GetYaxis()->SetLabelFont(42);
  h->GetXaxis()->SetLabelSize(0.04);
  h->GetYaxis()->SetLabelSize(0.04);
  h->SetMarkerSize(0.8);
  h->SetMarkerStyle(20);
  h->SetStats(0);
  h->Draw("e");

  background->Draw("same");   
  mass->SetRange(minhisto,maxhisto);	
  mass->Draw("same");
  massSwap->SetRange(minhisto,maxhisto);
  massSwap->Draw("same");
  f->Draw("same");
  
  Double_t yield = mass->Integral(minhisto,maxhisto)/binwidthmass;
  Double_t yieldErr = mass->Integral(minhisto,maxhisto)/binwidthmass*mass->GetParError(0)/mass->GetParameter(0);
  
  std::cout<<"YIELD="<<yield<<std::endl;

  TLegend* leg = new TLegend(0.65,0.58,0.82,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D^{0}+#bar{D^{#lower[0.2]{0}}} Signal","f");
  leg->AddEntry(massSwap,"K-#pi swapped","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

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

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

  TLatex* texPt = new TLatex(0.22,0.78,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
  texPt->SetNDC();
  texPt->SetTextFont(42);
  texPt->SetTextSize(0.04);
  texPt->SetLineWidth(2);
  texPt->Draw();

  TLatex* texY = new TLatex(0.22,0.83,"|y| < 1.0");
  texY->SetNDC();
  texY->SetTextFont(42);
  texY->SetTextSize(0.04);
  texY->SetLineWidth(2);
  texY->Draw();

  TLatex* texYield = new TLatex(0.22,0.73,Form("N_{D} = %.0f #pm %.0f",yield,yieldErr));
  texYield->SetNDC();
  texYield->SetTextFont(42);
  texYield->SetTextSize(0.04);
  texYield->SetLineWidth(2);
  texYield->Draw();

  c->SaveAs(Form("plotFits/DMass_poly2_%s_%.0f_%.0f.pdf",collisionsystem.Data(),ptmin,ptmax));
  
  TCanvas* cPull = new TCanvas(Form("cPull_%.0f_%.0f",ptmin,ptmax),"",600,700);
  TH1D* hPull = (TH1D*)h->Clone("hPull");
  for(int i=0;i<h->GetNbinsX();i++)
    {
      Double_t nfit = f->Integral(h->GetBinLowEdge(i+1),h->GetBinLowEdge(i+1)+h->GetBinWidth(i+1))/h->GetBinWidth(i+1);
      hPull->SetBinContent(i+1,(h->GetBinContent(i+1)-nfit)/h->GetBinError(i+1));
      hPull->SetBinError(i+1,0);
    }
  hPull->SetMinimum(-4.);
  hPull->SetMaximum(4.);
  hPull->SetYTitle("Pull");
  hPull->GetXaxis()->SetTitleOffset(1.);
  hPull->GetYaxis()->SetTitleOffset(0.65);
  hPull->GetXaxis()->SetLabelOffset(0.007);
  hPull->GetYaxis()->SetLabelOffset(0.007);
  hPull->GetXaxis()->SetTitleSize(0.12);
  hPull->GetYaxis()->SetTitleSize(0.12);
  hPull->GetXaxis()->SetLabelSize(0.1);
  hPull->GetYaxis()->SetLabelSize(0.1);
  hPull->GetYaxis()->SetNdivisions(504);
  TLine* lPull = new TLine(1.7, 0, 2., 0);
  lPull->SetLineWidth(1);
  lPull->SetLineStyle(7);
  lPull->SetLineColor(1);
  TPad* pFit = new TPad("pFit","",0,0.3,1,1);
  pFit->SetBottomMargin(0);
  pFit->Draw();
  pFit->cd();
  h->Draw("e");
  background->Draw("same");
  mass->Draw("same");
  massSwap->Draw("same");
  f->Draw("same");
  leg->Draw("same");
  texCms->Draw();
  texCol->Draw();
  texPt->Draw();
  texY->Draw();
  texYield->Draw();
  cPull->cd();
  TPad* pPull = new TPad("pPull","",0,0,1,0.3);
  pPull->SetTopMargin(0);
  pPull->SetBottomMargin(0.3);
  pPull->Draw();
  pPull->cd();
  hPull->Draw("p");
  lPull->Draw();
  cPull->cd();
  cPull->SaveAs(Form("plotFits/DMass_poly2_%s_%.0f_%.0f_Pull.pdf",collisionsystem.Data(),ptmin,ptmax));

  return mass;
}
TH1D* getYield(TTree* nt, TTree* ntMC, TString triggerpass, TString triggername, TString prescale, TString variable, TString varname, TString varlatex, Int_t BIN_NUM, Double_t BIN_MIN, Double_t BIN_MAX, TString addcut="")
{
  TH1D* hDistrib = new TH1D(Form("h%s_Distrib_%s",triggername.Data(),varname.Data()),"",BIN_NUM,BIN_MIN,BIN_MAX);
  for(float ivar=0;ivar<BIN_NUM;ivar++)
  {
    TCanvas* c = new TCanvas(Form("c%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"",500,500);
    TH1D* h = new TH1D(Form("h%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),";D^{0} mass (GeV/c^{2});Candidates",60,1.7,2.0);
    TH1D* hMC = new TH1D(Form("hMC%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"",60,1.75,1.95);
    TH1D* hSW = new TH1D(Form("hSW%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"",60,1.75,1.95);
    Float_t varmin = BIN_MIN+ivar*((BIN_MAX-BIN_MIN)/BIN_NUM);
    Float_t varmax = BIN_MIN+(ivar+1)*((BIN_MAX-BIN_MIN)/BIN_NUM);
    nt->Project(Form("h%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),Form("Dmass%s",prescale.Data()),Form("%s%s&&(%s>%f&&%s<%f)%s",prefilter.Data(),addcut.Data(),variable.Data(),varmin,variable.Data(),varmax,triggerpass.Data()));
    ntMC->Project(Form("hMC%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"Dmass",Form("%s%s&&(%s>%f&&%s<%f)%s",prefilterMC.Data(),addcut.Data(),variable.Data(),varmin,variable.Data(),varmax,"&&1"));
    ntMC->Project(Form("hSW%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"Dmass",Form("%s%s&&(%s>%f&&%s<%f)%s",prefilterSW.Data(),addcut.Data(),variable.Data(),varmin,variable.Data(),varmax,"&&1"));
    h->SetMaximum(h->GetMaximum()*1.20);
    h->Draw();

    TF1* f = new TF1(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]*([7]*([9]*Gaus(x,[1],[2]*(1+[11]))/(sqrt(2*3.14159)*[2]*(1+[11]))+(1-[9])*Gaus(x,[1],[10]*(1+[11]))/(sqrt(2*3.14159)*[10]*(1+[11])))+(1-[7])*Gaus(x,[1],[8]*(1+[11]))/(sqrt(2*3.14159)*[8]*(1+[11])))+[3]+[4]*x+[5]*x*x+[6]*x*x*x", 1.7, 2.0);
    f->SetParLimits(4,-1000,1000);
    f->SetParLimits(10,0.001,0.05);
    f->SetParLimits(2,0.01,0.1);
    f->SetParLimits(8,0.02,0.2);
    f->SetParLimits(7,0,1);
    f->SetParLimits(9,0,1);

    f->SetParameter(0,setparam0);
    f->SetParameter(1,setparam1);
    f->SetParameter(2,setparam2);
    f->SetParameter(10,setparam10);
    f->SetParameter(9,setparam9);

    f->FixParameter(8,setparam8);
    f->FixParameter(7,1);
    f->FixParameter(1,fixparam1);
    f->FixParameter(3,0);
    f->FixParameter(4,0);
    f->FixParameter(5,0);
    f->FixParameter(6,0);
    f->FixParameter(11,0);
    h->GetEntries();

    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    f->ReleaseParameter(1);
    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hMC->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L m","",1.7,2.0);

    f->FixParameter(1,f->GetParameter(1));
    f->FixParameter(2,f->GetParameter(2));
    f->FixParameter(10,f->GetParameter(10));
    f->FixParameter(9,f->GetParameter(9));
    f->FixParameter(7,0);
    f->ReleaseParameter(8);
    f->SetParameter(8,setparam8);

    hSW->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hSW->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hSW->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    hSW->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L m","",1.7,2.0);

    f->FixParameter(7,hMC->Integral(0,1000)/(hSW->Integral(0,1000)+hMC->Integral(0,1000)));
    f->FixParameter(8,f->GetParameter(8));
    f->ReleaseParameter(3);
    f->ReleaseParameter(4);
    f->ReleaseParameter(5);
    f->ReleaseParameter(6);

    f->SetLineColor(kRed);

    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"q","",1.7,2.0);
    f->ReleaseParameter(1);
    f->SetParLimits(1,1.86,1.87);
    f->ReleaseParameter(11);
    f->SetParLimits(11,-1.,1.);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L q","",1.7,2.0);
    h->Fit(Form("f%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"L m","",1.7,2.0);
    h->SetMarkerSize(0.8);
    h->SetMarkerStyle(20);

    TF1* background = new TF1(Form("background%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]+[1]*x+[2]*x*x+[3]*x*x*x");
    background->SetParameter(0,f->GetParameter(3));
    background->SetParameter(1,f->GetParameter(4));
    background->SetParameter(2,f->GetParameter(5));
    background->SetParameter(3,f->GetParameter(6));
    background->SetLineColor(4);
    background->SetRange(1.7,2.0);
    background->SetLineStyle(2);

    TF1* mass = new TF1(Form("fmass%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]*([3]*([4]*Gaus(x,[1],[2]*(1+[6]))/(sqrt(2*3.14159)*[2]*(1+[6]))+(1-[4])*Gaus(x,[1],[5]*(1+[6]))/(sqrt(2*3.14159)*[5]*(1+[6]))))");
    mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10),f->GetParameter(11));
    mass->SetParError(0,f->GetParError(0));
    mass->SetParError(1,f->GetParError(1));
    mass->SetParError(2,f->GetParError(2));
    mass->SetParError(3,f->GetParError(7));
    mass->SetParError(4,f->GetParError(9));
    mass->SetParError(5,f->GetParError(10));
    mass->SetFillColor(kOrange-3);
    mass->SetFillStyle(3002);
    mass->SetLineColor(kOrange-3);
    mass->SetLineWidth(3);
    mass->SetLineStyle(2);

    TF1* massSwap = new TF1(Form("fmassSwap%s_Fit_%s_%.0f",triggername.Data(),varname.Data(),ivar),"[0]*(1-[2])*Gaus(x,[1],[3]*(1+[4]))/(sqrt(2*3.14159)*[3]*(1+[4]))");
    massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8),f->GetParameter(11));
    massSwap->SetParError(0,f->GetParError(0));
    massSwap->SetParError(1,f->GetParError(1));
    massSwap->SetParError(2,f->GetParError(7));
    massSwap->SetParError(3,f->GetParError(8));
    massSwap->SetFillColor(kGreen+4);
    massSwap->SetFillStyle(3005);
    massSwap->SetLineColor(kGreen+4);
    massSwap->SetLineWidth(3);
    massSwap->SetLineStyle(1);

    h->SetXTitle("m_{#piK} (GeV/c^{2})");
    h->SetYTitle("Entries / (5 MeV/c^{2})");
    h->GetXaxis()->CenterTitle();
    h->GetYaxis()->CenterTitle();
    h->SetAxisRange(0,h->GetMaximum()*1.4*1.2,"Y");
    h->GetXaxis()->SetTitleOffset(1.3);
    h->GetYaxis()->SetTitleOffset(1.8);
    h->GetXaxis()->SetLabelOffset(0.007);
    h->GetYaxis()->SetLabelOffset(0.007);
    h->GetXaxis()->SetTitleSize(0.045);
    h->GetYaxis()->SetTitleSize(0.045);
    h->GetXaxis()->SetTitleFont(42);
    h->GetYaxis()->SetTitleFont(42);
    h->GetXaxis()->SetLabelFont(42);
    h->GetYaxis()->SetLabelFont(42);
    h->GetXaxis()->SetLabelSize(0.04);
    h->GetYaxis()->SetLabelSize(0.04);
    h->SetMarkerSize(0.8);
    h->SetMarkerStyle(20);
    h->SetStats(0);
    h->Draw("e");

    background->Draw("same");   
    mass->SetRange(1.7,2.0);	
    mass->Draw("same");
    massSwap->SetRange(1.7,2.0);
    massSwap->Draw("same");
    f->Draw("same");

    Double_t yield = mass->Integral(1.7,2.0)/0.005;
    Double_t yieldErr = (mass->Integral(1.7,2.0)/0.005)*(mass->GetParError(0)/mass->GetParameter(0));
    std::cout<<"YIELD="<<yield<<std::endl;

    // Draw the legend:)   
    TLegend* leg = myLegend(0.20,0.60,0.53,0.94);
    leg->SetFillColor(0);
    leg->SetBorderSize(0);
    leg->AddEntry((TObject*)0,"CMS Preliminary","");
    if(isPbPb) leg->AddEntry((TObject*)0,"PbPb #sqrt{s_{NN}}= 5.02 TeV","");
    else leg->AddEntry((TObject*)0,"pp #sqrt{s_{NN}}= 5.02 TeV","");
    leg->AddEntry((TObject*)0,Form("%.1f<%s<%.1f",varmin,varlatex.Data(),varmax),"");
    leg->AddEntry(h,"Data","pl");
    leg->AddEntry(f,"Fit","l");
    leg->AddEntry(mass,"Signal","f");
    leg->AddEntry(massSwap,"K-#pi swapped","f");
    leg->AddEntry(background,"Combinatorial Background","l");
    leg->Draw();
    TLegend* leg2 = myLegend(0.45,0.80,0.90,0.94);
    leg2->SetFillColor(0);
    leg2->SetBorderSize(0);
    leg2->AddEntry(h,"D meson","");
    leg2->AddEntry(h,Form("M_{D}=%.2f #pm %.2f MeV/c^{2}",mass->GetParameter(1)*1000.,mass->GetParError(1)*1000.),"");
    leg2->AddEntry(h,Form("N_{D}=%.0f #pm %.0f", yield, yieldErr),"");
    leg2->Draw();

    hDistrib->SetBinContent(ivar+1,yield);
    hDistrib->SetBinError(ivar+1,yieldErr);

    if(isPbPb) c->SaveAs(Form("fitefficiencyPbPb/c%s_Fit_%s_%.0f.pdf",triggername.Data(),varname.Data(),ivar));
    else c->SaveAs(Form("fitefficiencyPP/c%s_Fit_%s_%.0f.pdf",triggername.Data(),varname.Data(),ivar));
  }
  TCanvas* cDistrib = new TCanvas(Form("c%s_Distrib_%s",triggername.Data(),varname.Data()),"",500,500);
  hDistrib->Draw();
  hDistrib->SetStats(0);
  if(isPbPb) cDistrib->SaveAs(Form("fitefficiencyPbPb/c%s_Distrib_%s.pdf",triggername.Data(),varname.Data()));
  else cDistrib->SaveAs(Form("fitefficiencyPP/data/pp/c%s_Distrib_%s.pdf",triggername.Data(),varname.Data()));

  return hDistrib;
}
Esempio n. 15
0
void compareCorrRCSpike(){
	

  char tmp[1000];
  setTDRStyle();
  // settings for purity TGraphAsymmetryErrors
  Double_t fBinsPtMidPoint[nPtBin]={0};
  Double_t fBinsPtError[nPtBin]={0};
  
  for(int ipt=0; ipt < nPtBin; ipt++)
    {
      fBinsPtMidPoint[ipt] = 0.5*(fBinsPt[ipt+1]+fBinsPt[ipt]);
      fBinsPtError[ipt] = 0.5*(fBinsPt[ipt+1]-fBinsPt[ipt]);
    }


  TH1F* hTemplate_S[nEtaBin][nPtBin];
  TH1F* hdata_S[nEtaBin][nPtBin];

  
  std::string dataFile     = "SBDataTemplate_131511_139239.root";
  std::string templateFile = "spike_131511_139239.root";

  TFile* inf_data = new TFile(dataFile.data());
  TFile* inf_template = new TFile(templateFile.data());

  
  char* dec[2] = {"EB","EE"};
  for(int ieta=0; ieta<1; ieta++){
    for(int ipt=0; ipt < nPtBin; ipt++){

      // getting histograms from data root file

      sprintf(tmp,"h_%s_comb3Iso_sig_pt%d",dec[ieta],(int)fBinsPt[ipt]);
      cout << "looking for histogram " << tmp << " in file " << 
	inf_data->GetName() << endl;
      hdata_S[ieta][ipt] = (TH1F*)inf_data->FindObjectAny(tmp);
      hdata_S[ieta][ipt]->SetName(Form("hdata_S_%d_%d",ieta,ipt));
      hdata_S[ieta][ipt]->Rebin(REBINNINGS);

      // getting histogram for template root file
      sprintf(tmp,"h_EB_comb3Iso_EGdata_SIG");
      cout << "looking for histogram " << tmp << " in file " << 
	inf_template->GetName() << endl;
      hTemplate_S[ieta][ipt] = (TH1F*)inf_template->FindObjectAny(tmp);
      hTemplate_S[ieta][ipt]->SetName(Form("hTemplate_S_%d_%d",ieta,ipt));
      hTemplate_S[ieta][ipt]->Rebin(REBINNINGS);

    }
  }


  TH1F* hfit_sig;
  TH1F* hfit_spike;

  TH1F* hsig = new TH1F("hsig","",120,-1,11);
  hsig->SetXTitle("Iso (GeV)");
  hsig->SetYTitle("A.U.");
  hsig->GetYaxis()->SetDecimals();
  hsig->SetYTitle("Iso (GeV)");

  hsig->SetLineColor(2);
  TH1F* hspike = new TH1F("hspike","",120,-1,11);
  hspike->SetLineColor(4);

  TCanvas* c1 = new TCanvas("c1","",500,500);

  for(int ieta=0; ieta< 1; ieta++){
    for(int ipt=0; ipt < nPtBin; ipt++){


      hsig->Reset();
      hspike->Reset();

      // first obtain fit for the random cone corrected values
      hfit_sig  = (TH1F*)hdata_S[ieta][ipt]->Clone();
      hfit_sig  -> SetName("hfit_sig");
      hfit_sig  -> Rebin(4);

      double sigPar[20] = {hfit_sig->GetMaximum(), 1., 0.5, 0.3,
			   1.,-.3,-1., 0.01, 0.5, 0.01, 1., 1.};

      TF1 *fsig = new TF1("fsig", exp_conv, -1., 11., 12);
      fsig->SetParameters(sigPar);
      fsig->SetNpx(2500);
      fsig->SetLineColor(2);
      hfit_sig->Fit(fsig,"","",-1,5.0);

      c1->Print(Form("hfit_sig_pt%d.gif",(int)fBinsPt[ipt]));
      
      fsig->SetParameter(0,2);
      fsig->SetParameter(1,fsig->GetParameter(1)*8.39614e-01/6.83080e-01);//correction from RC
      fsig->SetParameter(2,4.83182e-01);
      fsig->SetParameter(3,fsig->GetParameter(3)*2.33769e-01/2.26323e-01);
    
      cout << "fsig Integral = " << fsig->Integral(-1,11) << endl;
      for(int i=0;i<4;i++)
	cout << "fsig par " << i << "= " << fsig->GetParameter(i) << endl;

      // second obtain fit for the spikes
      hfit_spike  = (TH1F*)hTemplate_S[ieta][ipt]->Clone();
      hfit_spike  -> SetName("hfit_spike");
      hfit_spike  -> Rebin(4);

      TF1 *fspike = new TF1("fspike", exp_conv, -1., 11., 12);
      fspike->SetParameters(sigPar);
      fspike->SetParameter(0,hfit_spike->GetMaximum());
      fspike->SetLineColor(4);
      fspike->SetNpx(2500);
      hfit_spike->Fit(fspike,"","",-1,5.0);

      c1->Print(Form("hfit_spike_pt%d.gif",(int)fBinsPt[ipt]));
      
      fspike->SetParameter(0,2.0);
      cout << "fspike Integral = " << fspike->Integral(-1,11) << endl;
      float scale = (float)fsig->Integral(-1,11)/(float)fspike->Integral(-1,11);
      fspike->SetParameter(0,2.0*scale);
      cout << "now fspike Integral = " << fspike->Integral(-1,11) << endl;

      for(int i=0;i<4;i++)
	cout << "fspike par " << i << "= " << fspike->GetParameter(i) << endl;

    
      hsig->FillRandom("fsig",10000);
      hspike->FillRandom("fspike",10000);

      cout << "KS test for sideband data and sideband MC = " << 
	hsig->KolmogorovTest(hspike,"X") << endl;
      cout << "KS test 2 for sideband data and sideband MC = " << 
	hsig->KolmogorovTest(hspike) << endl;
     
      hsig->Reset();
      hsig->SetMaximum(1.2);
      hsig->Draw();
//       hspike->Draw("same");
      fsig->Draw("same");
      fspike->Draw("same");

      TLegend* leg = new TLegend(0.35,0.70,0.55,0.85);
      leg->SetHeader(Form("p_{T}[%d,%d]",(int)fBinsPt[ipt],(int)fBinsPt[ipt+1]));
      leg->SetFillColor(0);
      leg->SetFillStyle(0);
      leg->SetTextSize(0.04);
      leg->SetBorderSize(0);
      leg->AddEntry(fsig,"Random-cone-corrected MC","f");
      leg->AddEntry(fspike,"Spike","f");   
      leg->Draw("same");
      
      c1->Print(Form("CorrRCSpike_pt%d.eps",(int)fBinsPt[ipt]));
      c1->Print(Form("CorrRCSpike_pt%d.gif",(int)fBinsPt[ipt]));
      c1->Print(Form("CorrRCSpike_pt%d.C",(int)fBinsPt[ipt]));
      
    } 
  }

    
   

}
Esempio n. 16
0
void toyMC_testFitter(int runIeta=-1, int runIpt=-1, int startExp=0){
	
  cout << "ROOT version = " << gROOT->GetVersion() << endl;
//   gSystem->mkdir("toysPlot");
  char tmp[1000];
  TRandom2* r2 = new TRandom2();

  TH1D* htoyResult_pull[nEtaBin][nPtBin];
  TH1D* htoyResult_bias[nEtaBin][nPtBin];

  TFile *fsumFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/proj_comb_comb3Iso_template.root");
  TFile* finFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/template_comb3Iso_template.root");  
  TFile* zeeFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/anadipho_Zee_Vg_3pb.root");
  TH1D* hTemplate = (TH1D*)finFile->FindObjectAny("h_EB_comb3Iso_EGdata_pt21");
  hTemplate->Reset();

  
  char* dec[2] = {"EB","EE"};
  for(int ieta=0; ieta<nEtaBin; ieta++){
    for(int ipt=0; ipt < nPtBin; ipt++){

      htoyResult_pull[ieta][ipt] = new TH1D(Form("hpull_%s_pt_%d",		
						 dec[ieta],
						 (int)fBinsPt[ipt]),
 					    "",50,-5.0,5.0);


      htoyResult_bias[ieta][ipt] = new TH1D(Form("hbias_%s_pt_%d",		
						 dec[ieta],
						 (int)fBinsPt[ipt]),
 					    "",100,-0.5,0.5);


    }
  }



  TH1D* hfit_sig;
  TH1D* hfit_bkg;

  TH1D* hTemplate_S[nEtaBin][nPtBin];
  TH1D* hTemplate_B[nEtaBin][nPtBin];
  TH1D* hZeeTemplate_S[nEtaBin];
  TH1D* hdata_data[nEtaBin][nPtBin];
  TH1D* htemp;


  for(int ieta=0; ieta< nEtaBin; ieta++){

    // getting a different signal template
    if(ieta==0){
      sprintf(tmp,"h_%s_combIso",dec[ieta]);
      cout << "looking for histogram " << tmp << " in file " << 
	zeeFile->GetName() << endl;
      hZeeTemplate_S[ieta]= (TH1D*)zeeFile->FindObjectAny(tmp);	
      hZeeTemplate_S[ieta]->Rebin(REBINNINGS_TEMP);
    }
    else {
      sprintf(tmp,"h_%s_comb3Iso_sig_sum_SIG",dec[ieta]); //no pt dep.
      cout << "looking for histogram " << tmp << " in file " << 
	fsumFile->GetName() << endl;
      hZeeTemplate_S[ieta]= (TH1D*)fsumFile->FindObjectAny(tmp);	
      hZeeTemplate_S[ieta]->Rebin(REBINNINGS_TEMP);
    }

    for(int ipt=0; ipt < nPtBin; ipt++){

      if(runIeta>=0 && ieta!=runIeta)continue;
      if(runIpt>=0 && ipt!=runIpt)continue;
      
      // getting histograms from data root file
      sprintf(tmp,"h_%s_comb3Iso_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
      cout << "looking for histogram " << tmp << " in file " << 
	finFile->GetName() << endl;
      hdata_data[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
      hdata_data[ieta][ipt]->Rebin(REBINNINGS_DATA);

      // filling unbinned data
      htemp = (TH1D*)hdata_data[ieta][ipt]->Clone("htemp");
      htemp->Reset();


      sprintf(tmp,"h_%s_comb3Iso_sig_pt%d",dec[ieta],(int)fBinsPt[ipt]);
      cout << "looking for histogram " << tmp << " in file " << 
	finFile->GetName() << endl;
      hTemplate_S[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
      hTemplate_S[ieta][ipt]->Rebin(REBINNINGS_TEMP);

      if(ieta==0 && fBinsPt[ipt]>=50)
	sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],50);
      else if(ieta==0 )
	sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],(int)fBinsPt[ipt]);  
      else if(ieta==1 && fBinsPt[ipt]>=60)
	sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],60);       
      else if(ieta==1)
	sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
      cout << "looking for histogram " << tmp << " in file " << 
	finFile->GetName() << endl;
      hTemplate_B[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
      hTemplate_B[ieta][ipt]->Rebin(REBINNINGS_TEMP);



      const int NRETURN = 3*NPAR;
      Double_t myFitPar[NRETURN]={0};
      Double_t* FuncFitResult;
      FuncFitResult = Ifit("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/EGdata_comb3Iso_et.dat",
			   hZeeTemplate_S[ieta],hTemplate_B[ieta][ipt],
			   hdata_data[ieta][ipt], myFitPar,
			   (int)fBinsPt[ipt], dec[ieta],2);

      Double_t nsig_input    = FuncFitResult[0];
      Double_t nsigerr_input = FuncFitResult[1];
      Double_t nbkg_input    = FuncFitResult[2];
      Double_t nbkgerr_input = FuncFitResult[3];
      Double_t nsig_input5GeV = FuncFitResult[4];
      Double_t nsigerr_input5GeV = FuncFitResult[5];

       // force the parameters since EE pt=40 fails
       if(ieta==1 && ipt==5)
	 {
	   nsig_input = 3172.0;
	   nbkg_input = 10031.0;
	   nsig_input5GeV = 3158.7;
	   
	   Double_t tempPar[NRETURN]={
	     22517.049862,
	     0.900766,
	     0.044772,
	     0.191920,
	     313.878244,
	     -0.545069,
	     -0.281830,
	     0.026143,
	     2.549494,
	     0.,
	     0.,
	     22517.049862,
	     0.900766,
	     0.044772,
	     0.191920,
	     313.878244,
	     -0.545069,
	     -0.281830,
	     0.026143,
	     2.549494,
	     0.,
	     0.,
	     22517.049862,
	     0.900766,
	     0.044772,
	     0.191920,
	     313.878244,
	     -0.545069,
	     -0.281830,
	     0.026143,
	     2.549494,
	     0.,
	     0.
	   };

	   for(int ipar=0; ipar <NRETURN; ipar++)
	     myFitPar[ipar] = tempPar[ipar];
	 } // end if EE, Et=40 GeV


      Double_t sigFitPar[NPAR]={0};
      for(int ipar=0; ipar<NPAR; ipar++)
	sigFitPar[ipar] = myFitPar[ipar];

      Double_t bkgFitPar[NPAR]={0};
      for(int ipar=0; ipar<NPAR; ipar++)
	bkgFitPar[ipar] = myFitPar[ipar+NPAR];


      Double_t sumFitPar[NPAR]={0};
      for(int ipar=0; ipar<NPAR; ipar++)
	sumFitPar[ipar] = myFitPar[ipar+NPAR*2];


      TF1* fsig = new TF1("fsig", exp_conv, fit_lo, fit_hi, 11);
      fsig->SetParameters(sigFitPar);       
      fsig->SetParameter(0,1.0);

      mySigPDFnorm = fsig->Integral(fit_lo,fit_hi);
      cout << "mySigPDFnorm = " << mySigPDFnorm << endl;
      
      TF1* fbkg = new TF1("fbkg", expinv_power, fit_lo, fit_hi, 11);
      fbkg->SetParameters(bkgFitPar);
      fbkg->SetParameter(4,1.0);

      myBkgPDFnorm = fbkg->Integral(fit_lo, fit_hi);
      cout << "myBkgPDFnorm = " << myBkgPDFnorm << endl;
 
      TF1* fsum = new TF1("fsum",mysum_norm, fit_lo, fit_hi,11);
      fsum->SetParameters(sumFitPar);

      cout << "Using nsig_input = " << nsig_input << endl;
      cout << "Using nbkg_input = " << nbkg_input << endl;
      cout << "Using nsig_input5GeV = " << nsig_input5GeV << endl;

      fsum->SetParameter(0, nsig_input*hdata_data[ieta][ipt]->GetBinWidth(2));
      fsum->SetParameter(4, nbkg_input*hdata_data[ieta][ipt]->GetBinWidth(2));
      fsum->SetLineColor(2);
      fsum->SetNpx(2500);

      //        cout << "fsum integral = " << fsum->Integral(fit_lo,fit_hi) << endl;
      //        for(int ipar=0; ipar<NPAR; ipar++)cout << "fsum par " << ipar << " = " << fsum->GetParameter(ipar) << endl;

//       FILE *infile =  fopen("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/EGdata_comb3Iso_et.dat","r");  
//       float xdata, xdata1, xdata2; // combined isolation, pt, eta
//       int flag = 1;
//       while (flag!=-1){
// 	flag =fscanf(infile,"%f %f %f",&xdata, &xdata1, &xdata2);
// 	if( xdata1 >= fBinsPt[ipt] && xdata1 < fBinsPt[ipt+1] && xdata<20.) {
// 	  if((ieta==0 && TMath::Abs(xdata2)<1.5) ||
// 	     (ieta==1 && TMath::Abs(xdata2)>1.5) ) {
// 	    htemp->Fill(xdata);
// 	  }
// 	} 
//       }// keep reading files as long as text exists

    
//       TCanvas* myCanvas = new TCanvas("myCanvas","myCanvas");
//       htemp->Draw();
//       fsum->Draw("same");

      ofstream dumpout;
      dumpout.open(Form("pull_bias%d_%s_pt%d.dat",startExp, dec[ieta],(int)fBinsPt[ipt]));
 
      //        // loops over toys
      for(int iexp=NEXP*startExp; iexp<NEXP*(startExp+1); iexp++){

	TH1D* htoyMC_data = (TH1D*)hdata_data[ieta][ipt]->Clone("htoyMC_data");
	htoyMC_data->Reset();
	 
	TH1D* htoyMC_sig  = (TH1D*)hZeeTemplate_S[ieta]->Clone("htoyMC_sig");
	 
	TH1D* htoyMC_bkg  = (TH1D*)hTemplate_B[ieta][ipt]->Clone("htoyMC_bkg");




	UInt_t nowSeed = (unsigned long)gSystem->Now();
	r2->SetSeed(nowSeed);
	int nsiggen  = r2->Poisson(nsig_input);
	int nbkggen  = r2->Poisson(nbkg_input);
	int ndata = nsiggen + nbkggen;

	// reset toy MC data
	htoyMC_data->Reset();
	ofstream fout;
	std::string toyData = Form("/tmp/syu/testtoy%d_%d_%d.dat",startExp,ieta,ipt);
	fout.open(toyData.data());
	for(int ieve=0; ieve < nsiggen; ieve++)
	  {
	    Double_t xvalue = fsig->GetRandom(fit_lo,fit_hi);
	    fout << xvalue << " " << 
	      0.5*(fBinsPt[ipt]+fBinsPt[ipt+1]) << " " << fBinsEta[ieta] << endl;
	    htoyMC_data->Fill(xvalue);
	  }
	     
	for(int ieve=0; ieve < nbkggen; ieve++)
	  {
	    Double_t xvalue = fbkg->GetRandom(fit_lo,fit_hi);
	    fout << xvalue << " " << 
	      0.5*(fBinsPt[ipt]+fBinsPt[ipt+1]) << " " << fBinsEta[ieta] << endl;
	    htoyMC_data->Fill(xvalue);
	  }
	     
	fout.close();


	Double_t* toyFitResult;
	Double_t toyMyFitPar[NRETURN]={0};

	toyFitResult =  Ifit(toyData.data(), 
			     htoyMC_sig, htoyMC_bkg,
			     htoyMC_data, toyMyFitPar,
			     (int)fBinsPt[ipt], dec[ieta],2);

	Double_t nsigtoyfit    = toyFitResult[0];
	Double_t errnsigtoyfit = toyFitResult[1];
	Double_t nbkgtoyfit    = toyFitResult[2];
  	Double_t errnbkgtoyfit = toyFitResult[3];
	Double_t nsigtoyfit_5GeV = toyFitResult[4];
	Double_t errnsigtoyfit_5GeV = toyFitResult[5];


	if(errnsigtoyfit < 1e-6 || errnbkgtoyfit < 1e-6 || 
	   nsigtoyfit < 1e-6 || nbkgtoyfit < 1e-6 || 
	   nsig_input < 1e-6 || fabs(nsigtoyfit - nsig_input)<1e-4)continue;
	   

	Double_t toySumFitPar[NPAR]={0};
	for(int ipar=0; ipar<NPAR; ipar++)
	  toySumFitPar[ipar] = toyMyFitPar[ipar+NPAR*2];


 	fsum->SetParameters(toySumFitPar);
 	fsum->SetParameter(0, nsigtoyfit*hdata_data[ieta][ipt]->GetBinWidth(2));
 	fsum->SetParameter(4, nbkgtoyfit*hdata_data[ieta][ipt]->GetBinWidth(2));
	// 	fsum->SetParameter(0, (float)nsiggen*hdata_data[ieta][ipt]->GetBinWidth(2));
	// 	fsum->SetParameter(4, (float)nbkggen*hdata_data[ieta][ipt]->GetBinWidth(2));

// 	 	if(iexp%20==0){
// 	 	  TCanvas* myCanvas = new TCanvas("myCanvas","SHIT");
// 	 	  htoyMC_data->SetMaximum(htoyMC_data->GetMaximum()*1.5);
// 	 	  htoyMC_data->Draw();
// 	 	  fsum->Draw("same");
// 	 	  myCanvas->Print(Form("toysPlot/fit_%03i.gif",iexp));
// 	 	  delete myCanvas;
// 	 	}

	// 	 cout << "fsum integral = " << fsum->Integral(-1,20) << endl;
	// 	 for(int ipar=0; ipar<NPAR; ipar++)cout << "fsum par " << ipar << " = " << fsum->GetParameter(ipar) << endl;

	
	Double_t pull = (nsigtoyfit - nsig_input)/errnsigtoyfit;
	Double_t bias = (nsigtoyfit - nsig_input)/nsig_input;
	dumpout << pull << " " << bias << endl; 
    
   	htoyResult_pull[ieta][ipt]->Fill(pull);
	htoyResult_bias[ieta][ipt]->Fill(bias);


      } // end loops of toys
      dumpout.close();

      delete fsig;
      delete fbkg;


    } // end of loop over pt bins


  }


//   TFile* outFile = new TFile(Form("fittertest%d_%s_pt%d.root",
// 				  startExp,
// 				  dec[runIeta], (int)fBinsPt[runIpt]),
// 			     "recreate");

//   for(int ieta=0; ieta < nEtaBin; ieta++){
//     for(int ipt=0; ipt < nPtBin; ipt++){      
 
//       if(htoyResult_pull[ieta][ipt]->GetEntries()>0)
// 	htoyResult_pull[ieta][ipt]->Write();

//       if(htoyResult_bias[ieta][ipt]->GetEntries()>0)
// 	htoyResult_bias[ieta][ipt]->Write();      
//     }
//   }
   
//   outFile->Close();

}
Esempio n. 17
0
void MCCTRapDep()   
{
  for(int iSpec = 0; iSpec < 3; iSpec++){
    int Prompt =1; int PutWeight = 1;
    bool bDefault = true; // true : cowboy only, false : salior
    bool bCowboy = false; // true : cowboy only, false : salior
    bool bSailor = false; // true : cowboy only, false : salior
    double fake_v2 = 0.3;

    // iSpec : choose the condition for default/cowboy/sailor
    if(iSpec == 0) {bDefault = true;bCowboy = false;bSailor = false;}
    if(iSpec == 1) {bDefault = false;bCowboy = true;bSailor = false;}
    if(iSpec == 2) {bDefault = false;bCowboy = false;bSailor = true;}

    char cCond[512];
    int iCond = 0; // the number of the cases, 1 : default, 2 : cowboy, 3 : sailor
    if(bDefault) {sprintf(cCond, "default"); iCond = 0;}
    if(bCowboy)  {sprintf(cCond, "cowboy"); iCond = 1;}
    if(bSailor)  {sprintf(cCond, "sailor"); iCond = 2;}

    // iCat : decide the categories for Rapidity (1: 0.0 - 1.2, 2: 1.2 - 1.6, 3: 1.6 - 2.4)
    for(int iCat = 0; iCat < 4; iCat++){
      gROOT->SetStyle("Plain");
      gStyle->SetPalette(1);
      gStyle->SetFrameBorderMode(0);
      gStyle->SetFrameFillColor(0);
      gStyle->SetCanvasColor(0);
      gStyle->SetTitleFillColor(0);
      gStyle->SetStatColor(0);
      gStyle->SetPadBorderSize(0);
      gStyle->SetCanvasBorderSize(0);
      gStyle->SetOptTitle(0); // at least most of the time
      gStyle->SetOptStat("emri");
      gStyle->SetOptFit(1); // set to 1 only if you want to display fit results
      //==================================== Define Histograms====================================================
      char OutTextFile[100]; 
      if(iCat == 0) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_0012_dPhi_%s.tex", cCond);
      if(iCat == 1) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_1216_dPhi_%s.tex", cCond);
      if(iCat == 2) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_1624H_dPhi_%s.tex", cCond);
      if(iCat == 3) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_1624L_dPhi_%s.tex", cCond);
      ofstream dataFile(Form(OutTextFile));
      TH1D *diMuonsInvMass_Gen = new TH1D("diMuonsInvMass_Gen","diMuonsInvMass_Gen", 100,2.98,3.16);

      TH1D *diMuonsPt_Gen = new TH1D("diMuonsPt_Gen","diMuonsPt_Gen", 100,0,50);
      TH1D *Bin_Gen = new TH1D("Bin_Gen","Bin_Gen", 40,0,40);
      //==============================================Define Acc Eff Stuff here===========================================
      // Pt bin sizes
      // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

      const int nFiles = 6;
      const int ndPhiBins = 4;
      double dphi_bound[100] = {0};

      dphi_bound[0] = 0.0;
      dphi_bound[1] = TMath::Pi()*2/16;
      dphi_bound[2] = TMath::Pi()*4/16;
      dphi_bound[3] = TMath::Pi()*6/16;
      dphi_bound[4] = TMath::Pi()*8/16;

      //X Axis error on Eff graph 
      double xdphi_bound[ndPhiBins] = {0.0};
      for(int i = 0; i < ndPhiBins; i++){
        xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
        cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
        dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      }

      double mom_err[ndPhiBins] = {0.0};

      double genError, recError;
      double gen_pt[100]={0}, gen_ptError[100]={0}; 
      double rec_pt[100]={0}, rec_ptError[100]={0}; 
      double Eff_cat_1[100]={0},Err_Eff_cat_1[100]={0};  

      // Histogram 2D Arrays
      TH1D *diMuonsInvMass_GenA[10][1000];
      TH1D *diMuonsInvMass_RecA[10][1000];
      TH1D *diMuonsPt_GenA[10][1000];
      TH1D *diMuonsPt_RecA[10][1000];
      char nameGen[10][500], nameRec[10][500], nameGenPt[10][500], nameRecPt[10][500];
      char namePt_1B[500];//for bkg func
      for (int ifile = 0; ifile < nFiles; ifile++) {
        for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {
          sprintf(nameGen[ifile],"DiMuonMassGen_pt_%d_%d_%d",ifile,iCat,idphi);
          sprintf(nameRec[ifile],"DiMuonMassRec_pt_%d_%d_%d",ifile,iCat,idphi);

          sprintf(nameGenPt[ifile],"DiMuonPtGen_pt_%d_%d_%d",ifile,iCat,idphi);
          sprintf(nameRecPt[ifile],"DiMuonPtRec_pt_%d_%d_%d",ifile,iCat,idphi);

          diMuonsInvMass_GenA[ifile][idphi]= new TH1D(nameGen[ifile],nameGen[ifile],  100,2.98,3.16); //for eff Gen;
          diMuonsInvMass_GenA[ifile][idphi]->Sumw2();
          diMuonsInvMass_GenA[ifile][idphi]->SetMarkerStyle(7);
          diMuonsInvMass_GenA[ifile][idphi]->SetMarkerColor(4);
          diMuonsInvMass_GenA[ifile][idphi]->SetLineColor(4);

          diMuonsInvMass_RecA[ifile][idphi] = new TH1D(nameRec[ifile],nameRec[ifile], 100,2.98,3.16); //for eff Rec;
          diMuonsInvMass_RecA[ifile][idphi]->Sumw2();
          diMuonsInvMass_RecA[ifile][idphi]->SetMarkerStyle(8);
          diMuonsInvMass_RecA[ifile][idphi]->SetMarkerColor(4);
          diMuonsInvMass_RecA[ifile][idphi]->SetLineColor(4);

          diMuonsPt_GenA[ifile][idphi]= new TH1D(nameGenPt[ifile],nameGenPt[ifile],  100,0,40); //for eff Gen;
          diMuonsPt_RecA[ifile][idphi]= new TH1D(nameRecPt[ifile],nameRecPt[ifile],  100,0,40); //for eff Rec;
        }
      }

      //===========================================Input Root File============================================================
      char fileName[10][500];
      //scales for different pT bins
      double scale[10]={0};  
      scale[0]=2.35829e-07;
      scale[1]=1.99854e-07;
      scale[2]=4.48263e-08;
      scale[3]=1.01144e-08;
      scale[4]=4.89604e-09;
      scale[5]=2.62102e-09;

      if(PutWeight==0){scale[0]=(1);scale[1]=(1);scale[2]=(1);scale[3]=(1);scale[4]=(1);scale[5]=(1);}

      if(Prompt ==1){
        cout<<"==================Prompt PrJpsi================================================"<<endl;
        sprintf(fileName[0],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0003_total.root");
        sprintf(fileName[1],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0306_total.root");
        sprintf(fileName[2],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0609_total.root");
        sprintf(fileName[3],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0912_total.root");
        sprintf(fileName[4],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt1215_total.root");
        sprintf(fileName[5],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt1530_total.root");

        //sprintf(fileName[6],"../RootFiles/DiMuonTTree_PromptJpsi_Pt30XX_total.root");
      }

      TFile *infile;
      TTree *tree;
      TTree *gentree;

      //======================  File loop Starts ============================
      for(int ifile = 0; ifile < nFiles; ifile++){
        infile=new TFile(fileName[ifile],"R");
        tree=(TTree*)infile->Get("SingleMuonTree");
        gentree=(TTree*)infile->Get("SingleGenMuonTree");
        //Event variables
        int eventNb,runNb,lumiBlock, gbin, rbin;
        //Jpsi Variables
        Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
        Double_t JpsiVprob;
        Double_t JpsiPhi;
        Double_t JpsiEta;
        Double_t JpsiPsi[38];
        Double_t JpsiGenPsi;
        //2.) muon variables RECO                                                                       
        double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt,muPosP, muPosPhi;
        double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt,muNegP, muNegPhi;
        //(1).Positive Muon                                     
        double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
        int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
        bool muPos_matches,muPos_tracker;
        //(2).Negative Muon                                     
        double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
        int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
        bool muNeg_matches,muNeg_tracker;

        //Gen Level variables
        //Gen PrJpsi Variables
        double GenJpsiMass, GenJpsiPt, GenJpsiRap;
        double GenJpsiPx, GenJpsiPy, GenJpsiPz;
        double GenJpsiPhi;
        double GenJpsiEta;
        double GenJpsiPsi;
        //2.) Gen muon variables 
        double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
        double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;

        // HLTrigger
        int hbit1;

        //Event variables
        tree->SetBranchAddress("eventNb",&eventNb);
        tree->SetBranchAddress("runNb",&runNb);
        tree->SetBranchAddress("lumiBlock",&lumiBlock);
        tree->SetBranchAddress("hbit1",&hbit1);

        //Jpsi Variables
        tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
        tree->SetBranchAddress("JpsiMass",&JpsiMass);
        tree->SetBranchAddress("JpsiPt",&JpsiPt);
        tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
        tree->SetBranchAddress("JpsiEta",&JpsiEta);
        tree->SetBranchAddress("JpsiPsi",&JpsiPsi);
        tree->SetBranchAddress("JpsiGenPsi",&JpsiGenPsi);
        //tree->SetBranchAddress("JpsiPsi",&JpsiPsi[38]);
        tree->SetBranchAddress("JpsiRap",&JpsiRap);
        tree->SetBranchAddress("JpsiVprob",&JpsiVprob);
        tree->SetBranchAddress("rbin",&rbin);

        //muon variable
        tree->SetBranchAddress("muPosPx",&muPosPx);
        tree->SetBranchAddress("muPosPy",&muPosPy);
        tree->SetBranchAddress("muPosPz",&muPosPz);
        tree->SetBranchAddress("muPosEta",&muPosEta);
        tree->SetBranchAddress("muPosPhi",&muPosPhi);
        tree->SetBranchAddress("muNegPx", &muNegPx);
        tree->SetBranchAddress("muNegPy", &muNegPy);
        tree->SetBranchAddress("muNegPz", &muNegPz);
        tree->SetBranchAddress("muNegEta", &muNegEta);
        tree->SetBranchAddress("muNegPhi", &muNegPhi);


        //1). Positive Muon
        tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
        tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
        tree->SetBranchAddress("muPos_dz", &muPos_dz);
        tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
        tree->SetBranchAddress("muPos_found", &muPos_found);
        tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
        tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
        tree->SetBranchAddress("muPos_matches", &muPos_matches);
        tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
        tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);

        //2). Negative Muon                                                                            
        tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
        tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
        tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
        tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
        tree->SetBranchAddress("muNeg_found", &muNeg_found);
        tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
        tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
        tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
        tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
        tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
        //====================================Gen Variables=========================================================
        //Gen Jpsi Variables
        gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
        gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
        gentree->SetBranchAddress("GenJpsiPhi",    &GenJpsiPhi);
        gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
        gentree->SetBranchAddress("GenJpsiPsi",    &GenJpsiPsi);
        gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
        gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
        gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
        gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
        gentree->SetBranchAddress("gbin",&gbin);
        //muon variable
        gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
        gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
        gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
        gentree->SetBranchAddress("GenmuPosEta",    &GenmuPosEta);
        gentree->SetBranchAddress("GenmuPosPhi",    &GenmuPosPhi);
        gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
        gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
        gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
        gentree->SetBranchAddress("GenmuNegEta",    &GenmuNegEta);
        gentree->SetBranchAddress("GenmuNegPhi",    &GenmuNegPhi);

        //====================================================== Gen tree loop ================================================
        int NAccep=0;
        int nGenEntries=gentree->GetEntries();
        cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ==============="<<endl;

        for(int i=0; i< nGenEntries; i++)  {        
          gentree->GetEntry(i);
          //Only printing 
          if(i%100000==0){
            //cout<<" processing record "<<i<<"/"<<nGenEntries<<endl;
            //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
          }

          //if(GenJpsiPt < 6.5) continue;

          bool GenPosIn=0, GenNegIn=0;
          GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
          GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

          diMuonsInvMass_Gen->Fill(GenJpsiMass);
          diMuonsPt_Gen->Fill(GenJpsiPt);

          if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
          if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

          int AccHighPtJpsi = 0;
          int AccLowPtJpsi = 0;
          if(GenJpsiPt >= 6.5 && fabs(GenJpsiRap) < 2.4 && GenPosIn == 1 && GenNegIn == 1) AccHighPtJpsi = 1;
          if(GenJpsiPt < 6.5 && GenJpsiPt >= 3.0 && fabs(GenJpsiRap) >= 1.6 && fabs(GenJpsiRap) < 2.4 && GenPosIn == 1 && GenNegIn == 1) AccLowPtJpsi = 1;

          double gdPhi2mu = GenmuPosPhi - GenmuNegPhi;
          while (gdPhi2mu > TMath::Pi()) gdPhi2mu -= 2*TMath::Pi();
          while (gdPhi2mu <= -TMath::Pi()) gdPhi2mu += 2*TMath::Pi();
          double gchkCowboy = 1*gdPhi2mu;

          if(bCowboy && !(gchkCowboy > 0.)) continue;
          if(bSailor && (gchkCowboy > 0.)) continue;

          if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

          Bin_Gen->Fill(gbin);

          double GenCenWeight =0, GenWeight =0;
          GenCenWeight=FindCenWeight(gbin);
          
          double gJpsidPhi = TMath::Abs(GenJpsiPsi);
          double gmean_dphi = TMath::Pi()/16;
          if (gJpsidPhi>TMath::Pi()/8) gmean_dphi = 3*TMath::Pi()/16;
          if (gJpsidPhi>TMath::Pi()/4) gmean_dphi = 5*TMath::Pi()/16;
          if (gJpsidPhi>3*TMath::Pi()/8) gmean_dphi = 7*TMath::Pi()/16;
          GenWeight=GenCenWeight*scale[ifile]*(2.0/TMath::Pi()*(1+2*fake_v2*cos(2*gJpsidPhi)*TMath::Gaus(GenJpsiPt,15,4,0)));

          if(PutWeight==0) GenWeight=1; 


          for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {

            //adding pT of all pt bins to see diss is cont

            if(iCat == 0) {
              if(  AccHighPtJpsi == 1 && (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 6.5 && GenJpsiPt < 40.0) &&  
                  (TMath::Abs(GenJpsiRap)<1.2 && TMath::Abs(GenJpsiRap) >= 0.0 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
            if(iCat == 1) {
              if(  AccHighPtJpsi == 1 && (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 6.5 && GenJpsiPt < 40.0) &&  
                  (TMath::Abs(GenJpsiRap)<1.6 && TMath::Abs(GenJpsiRap) >= 1.2 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
            if(iCat == 2) {
              if(  AccHighPtJpsi == 1 &&  (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 6.5 && GenJpsiPt < 40.0) &&  
                  (TMath::Abs(GenJpsiRap)<2.4 && TMath::Abs(GenJpsiRap) >= 1.6 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
            if(iCat == 3) {
              if(  AccLowPtJpsi == 1 && (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 3.0 && GenJpsiPt < 6.5) &&  
                  (TMath::Abs(GenJpsiRap)<2.4 && TMath::Abs(GenJpsiRap) >= 1.6 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
          }
        }//gen loop end



        cout<<" accepted no "<< NAccep<<endl;
        dataFile<<" accepted no "<< NAccep<<endl;

        //dataFile<<" accepted no "<< NAccep<<endl;
        //   new TCanvas;
        //diMuonsInvMass_Gen->Draw();
        //gPad->Print("plots/diMuonsInvMass_Gen.png");

        new TCanvas;
        diMuonsPt_Gen->Draw();

        //=============== Rec Tree Loop ==============================================================================

         // start to fill up reco corrected by efficiency
        char tmp_eff_input[512], tmp_input_histo[512];
        if(!(iCat == 3)) sprintf(tmp_eff_input,"../../EffRoots_New/PrJpsi_HighPt_%s.root", cCond);
        if(iCat == 3) sprintf(tmp_eff_input,"../../EffRoots_New/PrJpsi_LowPt_%s.root", cCond);
        sprintf(tmp_input_histo,"eff_%s", cCond);

        TFile *eff_input;
        eff_input=new TFile(tmp_eff_input,"R");

        int nRecEntries=tree->GetEntries();
        cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
        for(int i=0; i<nRecEntries; i++)  {     
          tree->GetEntry(i);
          //if(bCowboy && !(gchkCowboy > 0.)) {cout<<"This is not Cowboy from Gen"<<endl; continue;}
          //if(bSailor && (gchkCowboy > 0.)) {cout<<"This is not Sailor from Gen"<<endl; continue;}
          //Only printing 
          if(i%10000==0){
            //cout<<" processing record "<<i<<"/"<<nRecEntries<<endl;
            //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
            //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<endl; 
          }
          //if(JpsiPt < 6.5) continue;
          bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
          muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
          muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
          muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
          muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 

          if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
          if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

          bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
          bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

          double dPhi2mu = muPosPhi - muNegPhi;
          while (dPhi2mu > TMath::Pi()) dPhi2mu -= 2*TMath::Pi();
          while (dPhi2mu <= -TMath::Pi()) dPhi2mu += 2*TMath::Pi();
          double chkCowboy = 1*dPhi2mu;

          if(bCowboy && !(chkCowboy > 0.)) continue;
          if(bSailor && (chkCowboy > 0.)) continue;

          if(muPos_found > 10 && muPos_pixeLayers > 0 && muPos_nchi2In < 4.0 && TMath::Abs(muPos_dxy) < 3 && TMath::Abs(muPos_dz) < 15 && muPos_nchi2Gl < 20  &&
              muPos_arbitrated==1 && muPos_tracker==1){PosPass=1;}
          if(muNeg_found >10 && muNeg_pixeLayers >0 && muNeg_nchi2In <4.0 && TMath::Abs(muNeg_dxy) < 3 && TMath::Abs(muNeg_dz) < 15 && muNeg_nchi2Gl < 20 &&
              muNeg_arbitrated==1 && muNeg_tracker==1){NegPass=1;}

          //cout<<"Cut checks, muPos_matches : "<<muPos_matches<<", muNeg_matches : "<<muNeg_matches<<", PosIn : "<<PosIn<<", NegIn : "<<NegIn
          //    <<", PosPass : "******", NegPass : "******", mu_Global : "<<mu_Global<<", mu_Tracker : "<<mu_Tracker<<endl;
          //if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
          int AccHighPtJpsi = 0;
          int AccLowPtJpsi = 0;
          if(JpsiPt >= 6.5 && fabs(JpsiRap) < 2.4 && PosIn == 1 && NegIn == 1) AccHighPtJpsi = 1;
          if(JpsiPt < 6.5 && JpsiPt >= 3.0 && fabs(JpsiRap) >= 1.6 && fabs(JpsiRap) < 2.4 && PosIn == 1 && NegIn == 1) AccLowPtJpsi = 1;

          if(hbit1 == 1 && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

          //AllCut = 1;
          //without ID cut
          // if((muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && mu_Global && mu_Tracker){AllCut=1;}

          //without trigger matched
          //if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

          double eff_cor[2];
          double RecCenWeight=0,RecWeight=0;
          RecCenWeight=FindCenWeight(rbin);
          
          double JpsidPhi = 0.0;
          JpsidPhi = TMath::Abs(JpsiGenPsi);

          double rmean_dphi = TMath::Pi()/16;
          if (JpsidPhi>TMath::Pi()/8) rmean_dphi = 3*TMath::Pi()/16;
          if (JpsidPhi>TMath::Pi()/4) rmean_dphi = 5*TMath::Pi()/16;
          if (JpsidPhi>3*TMath::Pi()/8) rmean_dphi = 7*TMath::Pi()/16;
          RecWeight=RecCenWeight*scale[ifile]*(2.0/TMath::Pi()*(1+2*fake_v2*cos(2*JpsidPhi)*TMath::Gaus(JpsiPt,15,4,0)));


          if(PutWeight==0)RecWeight=1;


          //Eff loop for reco
          for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {
            if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {     
                if(iCat == 0) {
                  if(AccHighPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=6.5 && JpsiPt<40.0) && 
                      (TMath::Abs(JpsiRap) < 1.2 && TMath::Abs(JpsiRap) >= 0.0) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
                if(iCat == 1) {
                  if(AccHighPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=6.5 && JpsiPt<40.0) && 
                      (TMath::Abs(JpsiRap) < 1.6 && TMath::Abs(JpsiRap) >= 1.2) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
                if(iCat == 2) {
                  if(AccHighPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=6.5 && JpsiPt<40.0) && 
                      (TMath::Abs(JpsiRap) < 2.4 && TMath::Abs(JpsiRap) >= 1.6) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
                if(iCat == 3) {
                  if(AccLowPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=3.0 && JpsiPt<6.5) && 
                      (TMath::Abs(JpsiRap) < 2.4 && TMath::Abs(JpsiRap) >= 1.6) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
            }
          }
        }//rec tree loop ends
      }  // file loop ends

      ///////////////////////////////////////////////////////////////////
      cout<< " adding "<<endl;
      TH1D *diMuonsInvMass_RecA1[100];
      TH1D *diMuonsInvMass_GenA1[100];
      TH1D *diMuonsPt_GenA1[100];
      TH1D *diMuonsPt_RecA1[100];
      TF1 *backfun_1;

      for(Int_t idphi = 0; idphi < ndPhiBins; idphi++){
        diMuonsInvMass_RecA1[idphi] = diMuonsInvMass_RecA[0][idphi];
        diMuonsInvMass_GenA1[idphi] = diMuonsInvMass_GenA[0][idphi];
        diMuonsPt_GenA1[idphi] = diMuonsPt_GenA[0][idphi];
        diMuonsPt_RecA1[idphi] = diMuonsPt_RecA[0][idphi];

        for (int ifile = 1; ifile < nFiles; ifile++) {
          diMuonsInvMass_RecA1[idphi]->Add(diMuonsInvMass_RecA[ifile][idphi]);
          diMuonsInvMass_GenA1[idphi]->Add(diMuonsInvMass_GenA[ifile][idphi]);     
          diMuonsPt_GenA1[idphi]->Add(diMuonsPt_GenA[ifile][idphi]); 
          diMuonsPt_RecA1[idphi]->Add(diMuonsPt_RecA[ifile][idphi]); 
        }
      }
      //===========================Fitting=================================================================================//
      // Fit ranges
      double mass_low, mass_high;
      double MassJpsi, WeidthJpsi;
      // Fit Function crystall ball
      // Jpsi Settings
      MassJpsi = 3.096; 
      WeidthJpsi = 0.028;
      mass_low = 2.945; 
      mass_high = 3.24;  // Fit ranges

      TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,2.4,3.8,6);//2.4,3.8,6);
      GAUSPOL->SetParNames("Yield (J/#psi)","BinWidth","Mean","Sigma","#alpha","n");
      GAUSPOL->SetParameter(2, MassJpsi);
      GAUSPOL->SetParameter(3, WeidthJpsi);
      //GAUSPOL->SetParLimits(3, 0.1*WeidthJpsi,2.0*WeidthJpsi);
      GAUSPOL->SetParameter(4, 1.2);
      GAUSPOL->SetParameter(5, 20.0);
      GAUSPOL->SetLineWidth(2.0);
      GAUSPOL->SetLineColor(2);


      //=====================Loop for eff========================================================================================//
      //define stuff here for error on weighted samples
      double GenNo[100]={0};
      double GenError[100]={0};
      double RecError[100]={0};

      for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {

        gen_pt[idphi] = diMuonsInvMass_GenA1[idphi]->IntegralAndError(1, 100, genError);
        gen_ptError[idphi]= genError;
        cout<<" gen_pt[idphi] "<< gen_pt[idphi] <<" error   "<<  gen_ptError[idphi]<<endl;

        // cout<<" *********************** "<<diMuonsInvMass_RecA1[idphi]->GetMaximum()<<endl;
        //giving inetial value for crystall ball fourth parameter 
        GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[idphi]->Integral(0,50));
        GAUSPOL->FixParameter(1, diMuonsInvMass_RecA1[idphi]->GetBinWidth(1));
        //GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[idphi]->GetMaximum());
        //new TCanvas;
        //diMuonsInvMass_RecA1[idphi]->Draw();

        new TCanvas;
        diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL","EMRQ", "", mass_low, mass_high); // Jpsi
        //diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL","LLMERQ", "", 8.5,10.5); // Jpsi
        //diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL","LLMER", "", mass_low, mass_high); // Jpsi
        diMuonsInvMass_RecA1[idphi]->DrawCopy("EPLsame");

        // new TCanvas;
        //diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL_1","LLMER", "", mass_low, mass_high);
        //diMuonsInvMass_RecA1[idphi]->DrawCopy("EPLsame");
        //gPad->Print(PlotName);
        //gPad->Print(PlotName1);

        //  cout << GAUSPOL_1->GetChisquare()<<endl;
        //for(int i=0;i<=100;i++) {cout<<i<<"  "<<diMuonsInvMass_RecA1[idphi]->GetBinContent(i)<<endl;}
        //return;
        //double JpsiMass = GAUSPOL_1->GetParameter(2);
        //double JpsiWidth = GAUSPOL_1->GetParameter(3);
        //double JpsiYield = GAUSPOL_1->GetParameter(4); 

        double JpsiMass = GAUSPOL->GetParameter(2);
        double JpsiWidth = GAUSPOL->GetParameter(3);

        double JpsiYield = GAUSPOL->GetParameter(0); 
        Double_t JpsiYieldError = GAUSPOL->GetParError(0); 

        //cout<<JpsiYieldError<<"*****************"<<endl;

        //if(TMath::IsNan(JpsiYieldError)=1) {JpsiYieldError=TMath::Sqrt(JpsiYield);}

        double par[20];
        GAUSPOL->GetParameters(par);
        sprintf(namePt_1B,"pt_1B_%d",idphi);

        backfun_1 = new TF1(namePt_1B, Pol2, mass_low, mass_high, 3);
        backfun_1->SetParameters(&par[3]);

        double MassLow=(JpsiMass-3*JpsiWidth);
        double MassHigh=(JpsiMass+3*JpsiWidth);


        int binlow =diMuonsInvMass_RecA1[idphi]->GetXaxis()->FindBin(MassLow);
        int binhi =diMuonsInvMass_RecA1[idphi]->GetXaxis()->FindBin(MassHigh);

        //double binwidth=diMuonsInvMass_RecA1[idphi]->GetBinWidth(1);
        //yield by function 
        //rec_pt[idphi] = JpsiYield;
        //rec_ptError[idphi]= JpsiYieldError;

        //yield by histogram integral
        binlow = 1;
        binhi = 100;
        rec_pt[idphi] = diMuonsInvMass_RecA1[idphi]->IntegralAndError(binlow, binhi,recError);
        rec_ptError[idphi]= recError;
      }

      TFile *outfile;
      char tmp_output[512];
      if(iCat == 0) sprintf(tmp_output,"MCCT_PrJpsi_Raps_0012_dPhi_%s.root",cCond);
      if(iCat == 1) sprintf(tmp_output,"MCCT_PrJpsi_Raps_1216_dPhi_%s.root",cCond);
      if(iCat == 2) sprintf(tmp_output,"MCCT_PrJpsi_Raps_1624H_dPhi_%s.root",cCond);
      if(iCat == 3) sprintf(tmp_output,"MCCT_PrJpsi_Raps_1624L_dPhi_%s.root",cCond);
      outfile =new TFile(tmp_output,"Recreate");

      double gsum = 0.0;
      double gen_pt_Norm[ndPhiBins];
      double gen_ptError_Norm[ndPhiBins];
      for(int i = 0; i < ndPhiBins; i++){
        gsum += gen_pt[i];
      }
      gsum = gsum*(dphi_bound[1]-dphi_bound[0]);

      for(int i = 0; i < ndPhiBins; i++){
        gen_pt_Norm[i] = gen_pt[i]/gsum;
        gen_ptError_Norm[i] = gen_ptError[i]/gsum;
      }

      double sum = 0.0;
      double rec_pt_Norm[ndPhiBins];
      double rec_ptError_Norm[ndPhiBins];
      for(int i = 0; i < ndPhiBins; i++){
        sum += rec_pt[i];
      }
      sum = sum*(dphi_bound[1]-dphi_bound[0]);

      for(int i = 0; i < ndPhiBins; i++){
        rec_pt_Norm[i] = rec_pt[i]/sum;
        rec_ptError_Norm[i] = rec_ptError[i]/sum;
      }

      TH1F *hJpsi_Gen = new TH1F("hJpsi_Gen","hJpsi_Gen",ndPhiBins,0,TMath::Pi()/2);
      TH1F *hJpsi_Reco = new TH1F("hJpsi_Reco","hJpsi_Reco",ndPhiBins,0,TMath::Pi()/2);
      hJpsi_Gen->Sumw2();
      hJpsi_Reco->Sumw2();
      for(int i = 0; i < ndPhiBins; i++){
        hJpsi_Gen->SetBinContent(i+1,gen_pt[i]);
        hJpsi_Gen->SetBinError(i+1,gen_ptError[i]);
        hJpsi_Reco->SetBinContent(i+1,rec_pt[i]);
        hJpsi_Reco->SetBinError(i+1,rec_ptError[i]);
      }

      TGraphErrors *Jpsi_Reco_Norm = new TGraphErrors(ndPhiBins, xdphi_bound, rec_pt_Norm, mom_err, rec_ptError_Norm);
      TGraphErrors *Jpsi_Gen_Norm = new TGraphErrors(ndPhiBins, xdphi_bound, gen_pt_Norm, mom_err, gen_ptError_Norm);
      if(iCat == 0){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_0012");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_0012");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_0012");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_0012");
      }
      if(iCat == 1){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_1216");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_1216");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_1216");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_1216");
      }
      if(iCat == 2){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_1624H");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_1624H");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_1624H");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_1624H");
      }
      if(iCat == 3){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_1624L");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_1624L");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_1624L");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_1624L");
      }
      hJpsi_Gen->Write();
      hJpsi_Reco->Write();
      Jpsi_Reco_Norm->Write();
      Jpsi_Gen_Norm->Write();

      outfile->Write();
      outfile->Close();
    }
  }
}
void fillTree(TTree*& tree, TGraph*& graph, double& limit, double& lowlimit, unsigned int itype, std::map<double, std::string>& tanb_values, bool upper_exclusion, unsigned int verbosity)
{
  double value=-99;
  double tanb_help=-99;
  unsigned int ibin=0;
  // fill graph with scanned points
  cout << "now looping on  map" << endl;
  for(std::map<double, std::string>::const_iterator tanb = tanb_values.begin(); tanb!=tanb_values.end(); ++tanb){
    value = singlePointLimit(tanb->second, tanb->first, itype, verbosity);
    cout << "value = " << value << " = singlePointLimit(" << tanb->second <<", " << tanb->first << ", " << itype << ", " << verbosity << ");" << endl;
    if( value>0 ){
      graph->SetPoint(ibin++, tanb->first, value); 
      cout << "graph->SetPoint("<< ibin++ <<", " << tanb->first<<",  "<< value << ");"<< endl; 
    }
    tanb_help=tanb->first;
  }
  cout << "Filled graph. Will now determine the smooth curve on graph for interpolation" << endl;
  // determine smooth curve on graph for interpolation
  TSpline3* spline = new TSpline3("spline", graph, "r", 3., 10.);
  // linear polarisation func
  TF1 *fnc = 0;
  // determine all crossing points with y==1 
  std::vector<CrossPoint> points = crossPoints(graph);
  
  int dist = 1;
  bool filled = false, lowfilled=false;
  unsigned int np = 0;
  unsigned int steps = 10e6; 
  if(points.size()>0) limit = graph->GetX()[upper_exclusion ? points.begin()->first : points.end()->first];

  cout << "Starting loop on the points for determining crossings. Points.size()=" << points.size() << endl;
  for(std::vector<CrossPoint>::const_reverse_iterator point = points.rbegin(); point!=points.rend(); ++point, ++np){
  //for(std::vector<CrossPoint>::iterator point = points.begin(); point!=points.end(); ++point, ++np){
    //double min = (point->first-dist)>0 ? graph->GetX()[point->first-dist] : graph->GetX()[0]; 
    double min = (point->first)>0 ? graph->GetX()[point->first] : graph->GetX()[0]; 
    double max = (point->first+dist)<graph->GetN() ? graph->GetX()[point->first+dist] : graph->GetX()[graph->GetN()-1];

    //double y_min = (point->first-dist)>0 ? graph->GetY()[point->first-dist] : graph->GetY()[0]; 
    double y_min = (point->first)>0 ? graph->GetY()[point->first] : graph->GetY()[0];
    double y_max = (point->first+dist)<graph->GetN() ? graph->GetY()[point->first+dist] : graph->GetY()[graph->GetN()-1];

    vector<double> crossing;
    crossing.push_back((min-max-y_max*min+y_min*max)/(y_min-y_max));
    //double crossing;
    //crossing = (1.-y_min)/(y_max-y_min)*(max-min); 
				  
    double deltaM = -999.;
    double offset = min; double step_size = (max-min)/steps;
    double splinelimit;
    for(unsigned int scan=0; scan<=steps; ++scan){
      if(deltaM<0 || fabs(spline->Eval(offset+scan*step_size)-1.)<deltaM){
	splinelimit=offset+scan*step_size;
	deltaM=fabs(spline->Eval(offset+scan*step_size)-1.);
      }
    }
    std::cout << "****************************************************************" << std::endl;
    std::cout << "* [" << np+1 << "|" << point->second << "] asymptotic limit(";
    std::cout << limitType(itype) << ") :" << crossing[np] << " -- " << splinelimit << " deltaM : " << deltaM;
//     if(((upper_exclusion && point->second) || (!upper_exclusion && !(point->second))) && !filled){
//       //std::cout << "limit is taken from linear interpolation at the moment" << std::endl;
//       //limit = crossing;
//       std::cout << "    [-->to file]"; filled=true; tree->Fill();
//     }
    if(np==0){
      fnc = new TF1("fnc", "[0]*x+[1]", min, max);
      fnc->SetParameter(0, (y_min-y_max)/(min-max));
      fnc->SetParameter(1, (y_max*min-y_min*max)/(min-max));
      std::cout << std::endl;
      std::cout << "high limit is taken from linear interpolation at the moment" << std::endl;
      limit = crossing[np];
      std::cout << "high limit = " << limit << std::endl;
      filled=true;
      //std::cout << "    [-->to file]"; filled=true; tree->Fill();
    }
    if(np==1){
       fnc = new TF1("fnc", "[0]*x+[1]", min, max);
       fnc->SetParameter(0, (y_min-y_max)/(min-max));
       fnc->SetParameter(1, (y_max*min-y_min*max)/(min-max));
       std::cout << std::endl;
       std::cout << "low limit is taken from a spline fit at the moment" << std::endl;
       lowlimit = splinelimit; //crossing[np];
       std::cout << "low limit = " << lowlimit << std::endl;
       lowfilled=true; 
       //std::cout << "    [-->to file]"; lowfilled=true; tree->Fill();
    }
    std::cout << endl;
    std::cout << "****************************************************************" << std::endl;
  }
  if(filled){ 
    if(lowfilled) {std::cout << "    [-->to file]"; tree->Fill();}
    else{ lowlimit = 0.5; std::cout << "    [-->to file]"; tree->Fill();}
  }
  // catch cases where no crossing point was found
  if(!filled){
    if(value<1)
      {
	std::cout << "WARNING: no crossing found - all tanb values excluded: " << value << std::endl;
 	if(itype == observed)     { limit=1.00; lowlimit=1.00;}
 	if(itype == plus_2sigma)  { limit=3.00; lowlimit=3.00;}
 	if(itype == plus_1sigma)  { limit=2.00; lowlimit=2.00;}
 	if(itype == expected)     { limit=1.50; lowlimit=1.50;}
 	if(itype == minus_1sigma) { limit=1.00; lowlimit=1.00;}
 	if(itype == minus_2sigma) { limit=0.50; lowlimit=0.50;}
//	limit=2;
//	lowlimit=2;
	tree->Fill();
      }
    else
      {
	std::cout << "WARNING: no crossing found - no tanb value excluded: " << value << " -- " << tanb_help << std::endl;
	if(itype == observed)     { limit=tanb_help*value; }
	if(itype == plus_2sigma)  { limit=tanb_help*value; }
	if(itype == plus_1sigma)  { limit=tanb_help*value; }
	if(itype == expected)     { limit=tanb_help*value; }
	if(itype == minus_1sigma) { limit=tanb_help*value; }
	if(itype == minus_2sigma) { limit=tanb_help*value; }
	lowlimit=0.2;///////0.5;
	tree->Fill();
      }
  }
  cout << "Evaluated crossings. Now plotting" << endl;
  //if( verbosity>0 ){
    std::string monitor = std::string("SCAN-")+limitType(itype);
    TCanvas* canv = new TCanvas(monitor.c_str(), monitor.c_str(), 600, 600);
    cout << "Canva created. Now creating frame taking values from graph" << endl;
    cout << "Graph getx " << graph->GetX()[0] << endl;
    cout << "Graph getn " << graph->GetN() << endl;
    cout << "Graph getxn " << graph->GetX()[graph->GetN()-1];
    TH1F* frame = canv->DrawFrame(graph->GetX()[0]-0.1, 0., graph->GetX()[graph->GetN()-1]+0.1, 10.);
    cout << "Frame created, taking values from graph" << endl;
    canv->SetGridx(1); canv->SetGridy(1); canv->cd(); 
    graph->SetMarkerStyle(20.); 
    graph->SetMarkerColor(kBlack); 
    graph->SetMarkerSize(1.3); 
    graph->Draw("P");
    //spline->SetLineColor(kBlue); 
    //spline->SetLineWidth(3.); 
    //spline->Draw("same");
    if(filled) fnc->SetLineColor(kRed);
    if(filled) fnc->SetLineWidth(3.);
    if(filled) fnc->Draw("same");
    canv->Print(monitor.append(".png").c_str(), "png");
    delete frame; delete canv; delete spline;
    if(filled) delete fnc;
    //}
  return;
}
Esempio n. 19
0
void fitBox(
    TH1D* hist,
    double& mean,
    double& sigma,
    double& max,
    double& background,
    double sensorWidth,
    bool display)
{

  TF1 *errorfunc = new TF1("errorfunc","[0]*(1+TMath::Erf([1]*([2]-x)))*(1-TMath::Erf([3]*([4]-x)))");
  errorfunc->SetParNames("Height", "FallSlope","Fall", "RiseSlope", "Rise");

  //fit a gaussian for first approximation
  fitGaussian(hist, mean, sigma, max, background, display);


  //first order approximations
  // double maxBin = hist->GetMaximumBin();
  double rise = mean - sensorWidth/2;
  double fall = mean + sensorWidth/2;
  double height = max/4;
  double riseSlope = height*10;
  double fallSlope = height*10;
  // double maxBin = 0;
  // double rise = -1000;
  // double fall = 3000;
  // double maxHeight = 40;
  // double riseSlope = 400;
  // double fallSlope = 400;


  errorfunc->SetParameter("Height",height);
  errorfunc->SetParameter("Rise",rise);
  errorfunc->SetParameter("Fall",fall);
  errorfunc->SetParameter("RiseSlope",riseSlope);
  errorfunc->SetParameter("FallSlope",fallSlope);
  errorfunc->SetParLimits(0, height-abs(0.5*height), height+abs(0.5*height));
  errorfunc->SetParLimits(4, rise-abs(1*rise), rise+abs(1*rise));
  errorfunc->SetParLimits(2, fall-abs(1*fall), fall+abs(1*fall));
  errorfunc->SetParLimits(3, 0.01*riseSlope, 100*riseSlope);
  errorfunc->SetParLimits(1, 0.01*fallSlope, 100*fallSlope);


  hist->Fit("errorfunc", "");

  //max = gauss->GetParameter(0);
  mean = ( errorfunc->GetParameter(2) + errorfunc->GetParameter(4) ) / 2 ;
  sigma = abs ( errorfunc->GetParameter(4) - errorfunc->GetParameter(2) );
  //background = gauss->GetParameter(3);

  if (display)
  {
    TCanvas* can = new TCanvas();
    errorfunc->SetLineColor(46);
    errorfunc->SetLineWidth(1);
    hist->Draw();
    errorfunc->Draw("SAME");
    can->Update();
    can->WaitPrimitive();
  }

  delete errorfunc;

//   int maxPos = 1;
//   max = 0;
//   int risePos = 1;
//   double rise = 0;
//   int fallPos = 1;
//   double fall = 0;
//
//   for (int bin = 1; bin <= hist->GetNbinsX(); bin++)
//   {
//     const double value = hist->GetBinContent(bin);
//     if (value > max)
//     {
//       max = value;
//       maxPos = bin;
//     }
//
//     const double valuePrev = hist->GetBinContent(bin > 1 ? bin-1 : bin);
//     if (value - valuePrev > rise) {
//       rise = value - valuePrev;
//       risePos = bin;
//     }
//
//     const double valueNext = hist->GetBinContent(
//         bin < hist->GetNbinsX() ? bin+1 : bin);
//     if (value - valueNext > fall) {
//       fall = value - valueNext;
//       fallPos = bin;
//     }
//   }
//
//   mean = hist->GetXaxis()->GetBinCenter(maxPos);
//   sigma = hist->GetXaxis()->GetBinUpEdge(fallPos) -
//       hist->GetXaxis()->GetBinLowEdge(risePos);
//
//   const unsigned int initialWidth = 5;
//
//   Int_t bgBin1 = hist->FindBin(mean - initialWidth * sigma);
//   Int_t bgBin2 = hist->FindBin(mean + initialWidth * sigma);
//   if (bgBin1 < 1) bgBin1 = 1;
//   if (bgBin2 > hist->GetNbinsX()) bgBin2 = hist->GetNbinsX();
//   background = hist->GetBinContent(bgBin1) + hist->GetBinContent(bgBin2);
//   background /= 2.0;
//
//   max -= background;
//
//   // If sigma is very small, try to calculate using FWHM
// //  if (sigma < 10 * DBL_MIN)
// //  {
// //    double pt1 = 0;
// //    for (Int_t bin = 1; bin <= hist->GetNbinsX(); bin++)
// //    {
// //      if (bin >= max / 2.0)
// //      {
// //        pt1 = hist->GetBinCenter(bin);
// //        break;
// //      }
// //    }
//
// //    double pt2 = 0;
// //    for (Int_t bin = hist->GetNbinsX(); bin >= 1; bin--)
// //    {
// //      if (bin >= max / 2.0)
// //      {
// //        pt2 = hist->GetBinCenter(bin);
// //        break;
// //      }
// //    }
//
// //    sigma = pt2 - pt1;
// //  }
//
//   gauss->SetRange(mean - initialWidth * sigma, mean + initialWidth * sigma);
//   gauss->SetParameters(max, mean, sigma, background);
//   gauss->SetParLimits(2, 0, 10 * sigma);
//   hist->Fit("g1", "QR0");
//
//   max = gauss->GetParameter(0);
//   mean = gauss->GetParameter(1);
//   sigma = gauss->GetParameter(2);
//   background = gauss->GetParameter(3);
//
//   gauss->SetRange(mean - 5 * sigma, mean + 5 * sigma);
//   gauss->SetParameters(max, mean, sigma, background);
//   hist->Fit("g1", "QR0");
//
//   max = gauss->GetParameter(0);
//   mean = gauss->GetParameter(1);
//   sigma = gauss->GetParameter(2);
//   background = gauss->GetParameter(3);
//
//   if (display)
//   {
//     TCanvas* can = new TCanvas();
//     gauss->SetLineColor(46);
//     gauss->SetLineWidth(1);
//     hist->Draw();
//     gauss->Draw("SAME");
//     can->Update();
//     can->WaitPrimitive();
//   }
//
//   delete gauss;
}
Esempio n. 20
0
int fit_dscb(TH1F*& hrsp,
             const double nsigma,
             const double jtptmin,
             const int niter,
             const string alg,
	     const double fitmin,
	     const double fitmax

)
{
  if (0==hrsp) {
    cout<<"ERROR: Empty pointer to fit_dscb()"<<endl;return -1;
  }


  // first use a gaussian to constrain crystal ball gaussian core
  fit_gaussian(hrsp, nsigma, jtptmin, niter, alg);
  TF1* fgaus = hrsp->GetFunction("fgaus");
  if (0==fgaus) {
    hrsp->GetListOfFunctions()->Delete();
    return -1;
  }

  // implementation of the low pt bias threshold 
  string histname = hrsp->GetName();
  double ptRefMax(1.0),rspMax(0.0);
  int pos1     = histname.find("RefPt");
  int pos2     = histname.find("to",pos1);
  string ss    = histname.substr(pos1+5,pos2);
  if (from_string(ptRefMax,ss,std::dec)) {
    if (histname.find("RelRsp")==0)
      rspMax = jtptmin/ptRefMax;
    if (histname.find("AbsRsp")==0)
      rspMax = jtptmin-ptRefMax;
  }

  double fitrange_min(fitmin);
  double fitrange_max(fitmax);

  fitrange_min = std::max(rspMax,fitmin);
  adjust_fitrange(hrsp,fitrange_min,fitrange_max);

  TF1* fdscb = new TF1("fdscb",fnc_dscb,fitrange_min,fitrange_max,7);
  fdscb->SetLineWidth(2);
  fdscb->SetLineStyle(2);

  double norm = 2*fgaus->GetParameter(0);
  double mean = fgaus->GetParameter(1);
  double sigma= fgaus->GetParameter(2);

  //cout << hrsp->GetName() << "  fgaus "<< mean << " \t "  << hrsp->GetMean() << endl;

  // double norm = 2*hrsp->GetMaximum();
  // double mean = hrsp->GetMean();
  // //double mean = GetPeak(hrsp);
  // cout << "  mean : " << mean << "  hist mean : "<< hrsp->GetMean() << endl;
  // double sigma= hrsp->GetRMS();


  double aone(2.0),atwo(2.0),pone(10.0),ptwo(10.0);
  //double aone(1.0),atwo(1.0),pone(10.0),ptwo(10.0);
  TVirtualFitter::SetDefaultFitter("Minuit");
  
  int fitstatus(0);
  for (int i=0;i<niter;i++) {
    fdscb->SetParameter(0,norm); // N
    fdscb->SetParameter(1,mean); // mean
    fdscb->SetParameter(2,sigma);// sigma
    fdscb->SetParameter(3,aone); // a1
    fdscb->SetParameter(4,pone); // p1
    fdscb->SetParameter(5,atwo); // a2
    fdscb->SetParameter(6,ptwo); // p2                

    fdscb->FixParameter(1,mean);
    fdscb->FixParameter(2,sigma);

    if (i>0) fdscb->FixParameter(3,aone);
    else{
      fdscb->SetParLimits(3,0.,20.); //! best
    }
    if (i>1) fdscb->FixParameter(5,atwo);
    else{
      fdscb->SetParLimits(5,0.,20.); //! best
    }

    //! best
    fdscb->SetParLimits(4,0.,60.);
    fdscb->SetParLimits(6,0.,60.);

    fitstatus = hrsp->Fit(fdscb,"RQ+");
    if (0==fitstatus) i=999;
    delete fdscb;
    fdscb = hrsp->GetFunction("fdscb");
    if (0==fdscb) return -1;

    norm  = fdscb->GetParameter(0);
    aone  = fdscb->GetParameter(3);
    pone  = fdscb->GetParameter(4);
    atwo  = fdscb->GetParameter(5);
    ptwo  = fdscb->GetParameter(6);

    //cout << " aone : "  << aone << " atwo : " << atwo << " pone : " << pone << " ptwo : "  << ptwo << endl;

    //reset sigma and mean to gauss values...
    fdscb->SetParameter(1,fgaus->GetParameter(1));
    fdscb->SetParError (1,fgaus->GetParError(1));
    fdscb->SetParameter(2,fgaus->GetParameter(2));
    fdscb->SetParError (2,fgaus->GetParError(2));
  }

  if (0!=fitstatus){
    cout<<"fit_fdscb() to "<<alg.c_str()<<"  " <<hrsp->GetName()
        <<" failed. Fitstatus: "<<fitstatus<<endl;
    hrsp->GetFunction("fdscb")->Delete();
  }
  else fdscb->ResetBit(TF1::kNotDraw);
  //cout << " aone : "  << aone << " atwo : " << atwo << " pone : " << pone << " ptwo : "  << ptwo << endl;
  return fitstatus;
}
float SmearingTool::PTsmear(float PTmuonGen, float ETAmuonGen, float CHARGEmuonGen, float PTmuonReco, int Ismear, TString ParVar,float ParSig){
   //Ismear = 1 - Smear with RND (no RECO use), Ismear = 2 - Smear with SF for RECO and GEN
   if(Ismear != 1 && Ismear != 2)std::cout << "ERROR SmearingTool::PTsmear: set Ismear to 1 or 2 for smearing" << std::endl;
   const int NPThist = (sizeof(PTbin)/sizeof(float)-1);
   const int NETAhist = (sizeof(ETAbin)/sizeof(float)-1);
   //const int Nhist = NPThist*NETAhist;
   ////// Make smearing for single muon from Gen level PostFSR:
   float PTmuonSmear = -10.;
   float meanVar = 0;
   float sigVar = 0;//for sig1 and sig2
   float Asig2Var = 0;
   if(ParVar == "mean")meanVar = ParSig;
   if(ParVar == "sig1" || ParVar == "sig2")sigVar = ParSig;
   if(ParVar == "Asig2Var")Asig2Var = ParSig;
   int iK_cand = -1;
   for(int iPT = 0; iPT < NPThist; iPT++){
   for(int iETA = 0; iETA < NETAhist; iETA++){
      int iK = iPT + iETA*NPThist;
      // smear muons which out of range PT and ETA
      float PTcutDown = PTbin[iPT];
      float PTcutUp = PTbin[iPT+1];
      if(iPT == 0 && PTmuonGen < PTbin[0])PTcutDown = PTmuonGen-0.001;
      if(iPT == (NPThist-1) && PTmuonGen > PTbin[NPThist])PTcutUp = PTmuonGen+0.001;
      float ETAcutDown = ETAbin[iETA];
      float ETAcutUp = ETAbin[iETA+1];
      if(iETA == 0 && ETAmuonGen < ETAbin[0])ETAcutDown = ETAmuonGen-0.001;
      if(iETA == (NETAhist-1) && ETAmuonGen >= ETAbin[NETAhist])ETAcutUp = ETAmuonGen+0.001;
      if(PTmuonGen >= PTcutDown && PTmuonGen < PTcutUp
      && ETAmuonGen >= ETAcutDown && ETAmuonGen < ETAcutUp) iK_cand = iK;
   }}

   ///// Set Scale Factor
   float ScaleFactor = 1.;
   if (fabs(ETAmuonGen) < 0.8) ScaleFactor = 0.975;
   if (fabs(ETAmuonGen) >= 0.8 && fabs(ETAmuonGen) < 1.2) ScaleFactor = 0.99; 
   if (fabs(ETAmuonGen) >= 1.2) ScaleFactor = 1.0;
   TF1* fitDoubleGauss = new TF1("fitDoubleGauss", DoubleGauss, -0.1, 0.1, 5);
   fitDoubleGauss->SetParameter(4,1.);
   if(iK_cand > -1 && Ismear == 1){
      float meanCorr = mean[iK_cand] + meanVar*ERRmean[iK_cand];
      float sig1Corr = sig1[iK_cand] + sigVar*ERRsig1[iK_cand];
      if(sig1Corr < 0.005) sig1Corr = 0.005;
      float sig2Corr = sig2[iK_cand] + sigVar*ERRsig2[iK_cand];
      if(sig2Corr < 0.005) sig2Corr = 0.005;
      float Asig2Corr = Asig2[iK_cand] + Asig2Var*ERRAsig2[iK_cand];
      if(Asig2Corr < 0.) Asig2Corr = 0.;
      fitDoubleGauss->SetParameter(0,meanCorr);
      fitDoubleGauss->SetParameter(1,ScaleFactor*sig1Corr);
      fitDoubleGauss->SetParameter(2,Asig2Corr);
      fitDoubleGauss->SetParameter(3,ScaleFactor*sig2Corr);
      Double_t resSim = fitDoubleGauss->GetRandom();
      PTmuonSmear = PTmuonGen*(1+resSim);
   }
   delete fitDoubleGauss;
   if(iK_cand > -1 && Ismear == 2){
      PTmuonSmear = PTmuonGen + ScaleFactor*(PTmuonReco - PTmuonGen);
   }
   ////// End Smearing parametrization for single muon:

   return PTmuonSmear;
 }//end PTsmear function
Esempio n. 22
0
void checkRsnPIDqa(TString filename, TString foldername, Bool_t savePng,
		   TString plotTPCpi, TString plotTPCka, TString plotTPCpro,
		   TString plotTTOFpi, TString plotTOFka, TString plotTOFpro)
{
  //Open input file 
  TFile * fin = TFile::Open(filename.Data());
  if (!fin) return 0x0;
  
  //Access output of specific wagon
  TList * list = (TList*) fin->Get(foldername.Data());
  if (!list) return 0x0;

  //Set range for fit
  Float_t RangeFitMomMin = 0.1; //range in momentum where to check the mean and pull
  Float_t RangeFitMomMax = 2.0;
  Int_t xbinFitMin = 0;
  Int_t xbinFitMax = -1;
  Float_t RangeFitNsigmaPIDmin = -2.0; //range in Nsigma where the fit is to be performed
  Float_t RangeFitNsigmaPIDmax = 2.0;

  //Set range for visualisation
  Float_t RangeShowTPC[2] = {0.1, 2.0}; 
  Float_t RangeShowTOF[2] = {0.25, 2.0};
    
  //--------------------------
  // TPC PID Nsigma
  // fit with simple gaussian
  //--------------------------
  //Gaussian function
  TF1 *fGaus = new TF1("f","gaus", -7.0, 7.0);

  //--- pions
  TH2F * hTPCsigmaPi = (TH2F*)list->FindObject(plotTPCpi.Data());
  hTPCsigmaPi->RebinX(2);
  hTPCsigmaPi->SetTitle("TPC Pions");
  MakeUpHisto(hTPCsigmaPi,"p_{TPC} (GeV/c)", "N#sigma_{TPC}", 1, kBlack, 2);
  hTPCsigmaPi->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTPCsigmaPi->GetXaxis()->SetRangeUser(RangeShowTPC[0], RangeShowTPC[1]);
  xbinFitMin = hTPCsigmaPi->GetXaxis()->FindBin(RangeFitMomMin);
  xbinFitMax = hTPCsigmaPi->GetXaxis()->FindBin(RangeFitMomMax);
  hTPCsigmaPi->FitSlicesY(fGaus, xbinFitMin, xbinFitMax );
  TH1D * hTPCsigmaPi_mean = ((TH1D*)gDirectory->FindObject(Form("%s_1", plotTPCpi.Data())))->Clone("hNsigmaTPCpi_mean");
  TH1D * hTPCsigmaPi_pull = ((TH1D*)gDirectory->FindObject(Form("%s_2", plotTPCpi.Data())))->Clone("hNsigmaTPCpi_pull");
  MakeUpHisto(hTPCsigmaPi_mean, "", "", 1, kBlack, 2);
  MakeUpHisto(hTPCsigmaPi_pull, "", "", 1, kRed+2, 2);

  //--- kaons
  TH2F * hTPCsigmaKa = (TH2F*)list->FindObject(plotTPCka.Data());
  hTPCsigmaKa->RebinX(2);
  hTPCsigmaKa->SetTitle("TPC Kaons");
  hTPCsigmaKa->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTPCsigmaKa->GetXaxis()->SetRangeUser(RangeShowTPC[0], RangeShowTPC[1]);
  hTPCsigmaKa->FitSlicesY(fGaus, xbinFitMin, xbinFitMax );
  MakeUpHisto(hTPCsigmaKa,"p_{TPC} (GeV/c)", "N#sigma_{TPC}", 1, kBlack, 2);
  TH1D * hTPCsigmaKa_mean = ((TH1D*)gDirectory->FindObject(Form("%s_1", plotTPCka.Data())))->Clone("hNsigmaTPCka_mean");
  TH1D * hTPCsigmaKa_pull = ((TH1D*)gDirectory->FindObject(Form("%s_2", plotTPCka.Data())))->Clone("hNsigmaTPCka_pull");
  MakeUpHisto(hTPCsigmaKa_mean, "", "", 1, kBlack, 2);
  MakeUpHisto(hTPCsigmaKa_pull, "", "", 1, kRed+2, 2);

  //--- protons
  TH2F * hTPCsigmaPro = (TH2F*)list->FindObject(plotTPCpro.Data());
  hTPCsigmaPro->RebinX(2);
  hTPCsigmaPro->SetTitle("TPC Protons");
  MakeUpHisto(hTPCsigmaPro,"p_{TPC} (GeV/c)", "N#sigma_{TPC}", 1, kBlack, 2);
  hTPCsigmaPro->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTPCsigmaPro->GetXaxis()->SetRangeUser(RangeShowTPC[0], RangeShowTPC[1]);
  hTPCsigmaPro->FitSlicesY(fGaus, xbinFitMin, xbinFitMax );
  TH1D * hTPCsigmaPro_mean = ((TH1D*)gDirectory->FindObject(Form("%s_1", plotTPCpro.Data())))->Clone("hNsigmaTPCpro_mean");
  TH1D * hTPCsigmaPro_pull = ((TH1D*)gDirectory->FindObject(Form("%s_2", plotTPCpro.Data())))->Clone("hNsigmaTPCpro_pull");
  MakeUpHisto(hTPCsigmaPro_mean, "", "", 1, kBlack, 2);
  MakeUpHisto(hTPCsigmaPro_pull, "", "", 1, kRed+2, 2);

   //--- plot TPC
  TLine *l11=new TLine(RangeShowTPC[0],0.,RangeShowTPC[1],0.); l11->SetLineWidth(1); l11->SetLineStyle(7);
  TLine *l12=new TLine(RangeShowTPC[0],1.,RangeShowTPC[1],1.); l12->SetLineWidth(1); l12->SetLineStyle(7);

  gStyle->SetOptStat(0);
  TCanvas *cPidPerformance4 = new TCanvas("cPIDperformance4","TPC PID",1200,500);
  cPidPerformance4->Divide(3,1);
  cPidPerformance4->cd(1);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTPCsigmaPi->DrawCopy("colz");
  hTPCsigmaPi_mean->DrawCopy("same");
  hTPCsigmaPi_pull->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance4->cd(2);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTPCsigmaKa->DrawCopy("colz");
  hTPCsigmaKa_mean->DrawCopy("same");
  hTPCsigmaKa_pull->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance4->cd(3);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTPCsigmaPro->DrawCopy("colz");
  hTPCsigmaPro_mean->DrawCopy("same");
  hTPCsigmaPro_pull->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  TLegend * pidLegTPC = new TLegend(0.15,0.8,0.88,0.88);
  pidLegTPC->SetBorderSize(0); pidLegTPC->SetFillStyle(1001); pidLegTPC->SetFillColor(kWhite);
  pidLegTPC->SetTextSize(0.04); pidLegTPC->SetNColumns(2);
  pidLegTPC->AddEntry(hTPCsigmaPro_mean,"Mean","lp");
  pidLegTPC->AddEntry(hTPCsigmaPro_pull,Form("#sigma, Gaus fit (%2.1f,%2.1f)",RangeFitNsigmaPIDmin,RangeFitNsigmaPIDmax),"lp");
  pidLegTPC->Draw("same");

  if (savePng) cPidPerformance4->SaveAs("RsnQA_TPC_Nsigma.png");
  
  //----------------------------------------------------
  // TOF
  // fit with signal model = gaussian + exponential tail
  //----------------------------------------------------
  //Signal model for TOF signal = gaus + exp tail
  const Int_t npars = 6;
  TF1 *fSignalModel = new TF1("fSignalModel", TOFsignal, -7.0, 7.0, npars);
  fSignalModel->SetTitle("TOF Signal");
  fSignalModel->SetParameter(0, 1.);
  fSignalModel->SetParameter(1, 0.);
  fSignalModel->SetParLimits(1, -2., 1.);
  fSignalModel->SetParameter(2, 1.);
  fSignalModel->SetParLimits(2, 0.5, 2.);
  fSignalModel->SetParameter(3, 1.);
  fSignalModel->SetParLimits(3, 0.5, 1.5);
  fSignalModel->SetParameter(4, 1.);
  fSignalModel->SetParLimits(4, 0., 1.e8);
  fSignalModel->SetParameter(5, 0.);
  fSignalModel->SetParLimits(5, -10., 10.);
  fSignalModel->SetNpx(2000);
  fSignalModel->SetParNames("Norm", "Mean", "Sigma", "Tail", "Shift", "Slope"/*, "Square"*/);
  fSignalModel->SetLineColor(kRed+1);

  //results
  TObjArray *results[3];
  for(Int_t i = 0; i < 3; i++){
    results[i] = new TObjArray(10);
  }
  TH1D * par[3][npars];
  //--- pions
  TH2F * hTOFsigmaPi = (TH2F*)list->FindObject(plotTOFpi.Data());
  hTOFsigmaPi->SetTitle("TOF Pions");
  hTOFsigmaPi->RebinX(2);
  MakeUpHisto(hTOFsigmaPi,"p (GeV/c)", "N#sigma_{TOF}", 1, kBlack, 2);
  hTOFsigmaPi->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTOFsigmaPi->GetXaxis()->SetRangeUser(RangeShowTOF[0], RangeShowTOF[1]);
  fSignalModel->SetParLimits(4, 0., hTOFsigmaPi->GetMaximum()*0.5);
  fSignalModel->SetParLimits(0, 0., hTOFsigmaPi->GetMaximum()*1.2);
  hTOFsigmaPi->FitSlicesY(fSignalModel, xbinFitMin, xbinFitMax, 0, "QR", results[0] );
  for(Int_t cc = 0; cc < npars ; cc++) {
    par[0][cc] = (TH1D*)gDirectory->FindObject(Form("%s_%i", plotTOFpi.Data(), cc));
  }
  MakeUpHisto(par[0][1], "", "", 1, kBlue, 2);
  MakeUpHisto(par[0][2], "", "", 1, kMagenta+2, 2);
  
  //--- KAONS
  TH2F * hTOFsigmaKa = (TH2F*)list->FindObject(plotTOFka.Data());
  hTOFsigmaKa->SetTitle("TOF Kaons");
  hTOFsigmaKa->RebinX(2);
  MakeUpHisto(hTOFsigmaKa,"p (GeV/c)", "N#sigma_{TOF}", 1, kBlack, 2);
  hTOFsigmaKa->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTOFsigmaKa->GetXaxis()->SetRangeUser(RangeShowTOF[0], RangeShowTOF[1]);
  fSignalModel->SetParLimits(4, 0., hTOFsigmaKa->GetMaximum()*0.5);
  fSignalModel->SetParLimits(0, 0., hTOFsigmaKa->GetMaximum()*1.2);
  hTOFsigmaKa->FitSlicesY(fSignalModel, xbinFitMin, xbinFitMax, 0, "QR", results[0] );
  for(Int_t cc = 0; cc < npars ; cc++) {
    par[1][cc] = (TH1D*)gDirectory->FindObject(Form("%s_%i", plotTOFka.Data(), cc));
  }
  MakeUpHisto(par[1][1], "", "", 1, kBlue, 2);
  MakeUpHisto(par[1][2], "", "", 1, kMagenta+2, 2);

  //--- protons
  TH2F * hTOFsigmaPro = (TH2F*)list->FindObject(plotTOFpro.Data());
  hTOFsigmaPro->SetTitle("TOF Protons");
  hTOFsigmaPro->RebinX(2);
  MakeUpHisto(hTOFsigmaPro,"p (GeV/c)", "N#sigma_{TOF}", 1, kBlack, 2);
  hTOFsigmaPro->GetYaxis()->SetRangeUser(-5.1,5.1);
  hTOFsigmaPro->GetXaxis()->SetRangeUser(RangeShowTOF[0], RangeShowTOF[1]);
  fSignalModel->SetParLimits(4, 0., hTOFsigmaPro->GetMaximum()*0.5);
  fSignalModel->SetParLimits(0, 0., hTOFsigmaPro->GetMaximum()*1.2);
  hTOFsigmaPro->FitSlicesY(fSignalModel, xbinFitMin, xbinFitMax, 0, "QR", results[0] );
  for(Int_t cc = 0; cc < npars ; cc++) {
    par[2][cc] = (TH1D*)gDirectory->FindObject(Form("%s_%i", plotTOFpro.Data(), cc));
  }
  MakeUpHisto(par[2][1], "", "", 1, kBlue, 2);
  MakeUpHisto(par[2][2], "", "", 1, kMagenta+2, 2);

  //--- plot TOF
  gStyle->SetOptStat(0);
  TCanvas *cPidPerformance3 = new TCanvas("cPidPerformance3","TOF PID performance",1200,500);
  cPidPerformance3->Divide(3,1);
  cPidPerformance3->cd(1);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTOFsigmaPi->DrawCopy("colz");
  if(par[0][1]) par[0][1]->DrawCopy("same");
  if(par[0][2]) par[0][2]->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance3->cd(2);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTOFsigmaKa->DrawCopy("colz");
  if(par[1][1]) par[1][1]->DrawCopy("same");
  if(par[1][2]) par[1][2]->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  cPidPerformance3->cd(3);
  gPad->SetLogz(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy();
  hTOFsigmaPro->DrawCopy("colz");
  if(par[2][1]) par[2][1]->DrawCopy("same");
  if(par[2][2]) par[2][2]->DrawCopy("same");
  l11->Draw("same"); l12->Draw("same");

  TLegend * pidLegTOF = new TLegend(0.15,0.8,0.88,0.88);
  pidLegTOF->SetBorderSize(0); pidLegTOF->SetFillStyle(1001); pidLegTOF->SetFillColor(kWhite);
  pidLegTOF->SetTextSize(0.04); pidLegTOF->SetNColumns(2);
  pidLegTOF->AddEntry(par[0][1],"Mean","lp");
  pidLegTOF->AddEntry(par[0][2], Form("#sigma, Gaus+Tail fit (%2.1f,%2.1f)",RangeFitNsigmaPIDmin, RangeFitNsigmaPIDmax),"lp");
  pidLegTOF->Draw("same");
  
  if (savePng) cPidPerformance3->Print("RsnQA_TOF_Nsigma.png");
  return;
}
TF1 *FitDoubleExpTenHist(TH1 *hist_to_fit, TH1 *geant_1, TH1 *geant_2,
    TH1 *geant_3, TH1 *geant_4, TH1 *geant_5, TH1* geant_6,
    TH1 *geant_7, TH1 *geant_8, TH1 *geant_9, TH1* geant_10,
    //                         Double_t gLowX, Double_t gUpX, Double_t *init=NULL){
    Double_t gLowX, Double_t gUpX){
      if(gLowX > gUpX){
        std::cout << "Your range is illogical" << std::endl;
        return NULL;
      }

      hist_to_fit->GetXaxis()->SetRangeUser(gLowX,gUpX);
      int gBinW = hist_to_fit->GetBinWidth(1);

      DoubleExpTenHist* deh10 = new DoubleExpTenHist(geant_1, geant_2, geant_3, geant_4, 
                                                     geant_5, geant_6, geant_7, 
                                                     geant_8, geant_9, geant_10);
      TF1* fitfunc = new TF1("double_exp_ten_hist",deh10, 0, 1, 14,"DoubleExpTenHist");
      TF1* fitfunc_to_draw = new TF1("double_exp_ten_hist_check",deh10, 0, 1, 14,"DoubleExpTenHist");

      //if (init==NULL){
      //std::cout << "Need initial parameters. Exiting." << std::endl;
      //return NULL;
      //}
      //if (init!=NULL){
      //fitfunc->SetParameters(init);
      //}

      //fitfunc->FixParameter(1,init[1]);
      //for (int i = 7; i < 11; i++){
      //fitfunc->FixParameter(i, init[i]);
      //}

      ////fitfunc->SetParLimits(0, 9e-04, 1.2e-03);
      //fitfunc->SetParLimits(2, 0, 1);
      //fitfunc->SetParLimits(3, 0, 1);
      ////  fitfunc->SetParLimits(4, 0, 1);
      //fitfunc->SetParLimits(5, 0, 1);
      //fitfunc->FixParameter(4,init[4]);
      ////  fitfunc->FixParameter(2,init[2]);
      ////  fitfunc->FixParameter(5,init[5]);

      ////fitfunc->SetRange(gLowX, gUpX);
      fitfunc->SetLineColor(4);
      fitfunc->SetLineWidth(3);
      hist_to_fit->SetLineColor(kBlue);
      geant_1->SetLineColor(kGreen+4);
      geant_2->SetLineColor(kRed);
      geant_3->SetLineColor(kMagenta);
      geant_4->SetLineColor(kOrange);
      geant_5->SetLineColor(kSpring);
      geant_6->SetLineColor(kViolet);
      geant_7->SetLineColor(kCyan);
      geant_8->SetLineColor(kYellow);
      geant_9->SetLineColor(kPink);
      geant_10->SetLineColor(kTeal);

      fitfunc->SetParameter(0, 0.2);
      fitfunc->SetParameter(1, 0.05);
      fitfunc->SetParameter(2, 0.2);
      fitfunc->SetParameter(3, 0.2);
      fitfunc->SetParameter(4, 1.5);
      fitfunc->SetParameter(5, 1);
      fitfunc->SetParameter(6, 1);
      fitfunc->SetParameter(7, 0.5);
      fitfunc->SetParameter(8, 0.1);
      fitfunc->SetParameter(9, 1);
      fitfunc->SetParameter(10, 1);
      fitfunc->SetParameter(11, 162808);
      fitfunc->SetParameter(12, -0.00210025);
      fitfunc->SetParameter(13, 486.425);
      fitfunc->SetParameter(14, 0.00161493);

      fitfunc->SetParName(0, "1082 Scaling    ");
      fitfunc->SetParName(1, "1320 Scaling    ");
      fitfunc->SetParName(2, "1848 Scaling    ");
      fitfunc->SetParName(3, "1906 Scaling    ");
      fitfunc->SetParName(4, "2360 Scaling    ");
      fitfunc->SetParName(5, "2560 Scaling    ");
      fitfunc->SetParName(6, "2930 Scaling    ");
      fitfunc->SetParName(7, "3754 Scaling    ");
      fitfunc->SetParName(8, "670  Scaling    ");
      fitfunc->SetParName(9, "824  Scaling    ");
      fitfunc->SetParName(10, "Double Exp. Scaling   ");
      fitfunc->SetParName(11, "Exp.Scaling         ");
      fitfunc->SetParName(12, "Exp.Decay.Const       ");
      fitfunc->SetParName(13, "2nd Exp. Scaling    ");
      fitfunc->SetParName(14, "2nd Exp. Decay Const  ");

      //hist_to_fit->Fit(fitfunc, "PRMEQ");
      hist_to_fit->Sumw2();
      hist_to_fit->Fit(fitfunc, "PMEOQ","",gLowX,gUpX);
      fitfunc_to_draw->SetRange(0,4096);
      fitfunc_to_draw->SetParameters(fitfunc->GetParameters());
      fitfunc_to_draw->SetChisquare(fitfunc->GetChisquare());
      fitfunc_to_draw->SetParError(0, fitfunc->GetParError(0));

      return fitfunc_to_draw;
    }
Esempio n. 24
0
int macro_004_8 ()
{
  TFile input ("../testBkg_004.root") ;

  //PG get the histograms
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  THStack * stack_m4_upper = (THStack *) input.Get ("stack_m4_upper") ;
  TH1F * m4_upper_total = (TH1F*) stack_m4_upper->GetStack ()->Last () ;
  TH1F * m4_upper_Wjet = (TH1F *) input.Get ("m4_upper_Wjet") ;
    
  THStack * stack_m4_lower = (THStack *) input.Get ("stack_m4_lower") ;
  TH1F * m4_lower_total = (TH1F *) stack_m4_lower->GetStack ()->Last () ;
  TH1F * m4_lower_Wjet = (TH1F *) input.Get ("m4_lower_Wjet") ;
    
  THStack * stack_m4_signal = (THStack *) input.Get ("stack_m4_signal") ;
  TH1F * m4_signal_total = (TH1F *) stack_m4_signal->GetStack ()->Last () ;
  TH1F * m4_signal_Wjet = (TH1F *) input.Get ("m4_signal_Wjet") ;

  THStack * stack_m4_sideband = (THStack *) input.Get ("stack_m4_sideband") ;
  TH1F * m4_sideband_total = (TH1F *) stack_m4_sideband->GetStack ()->Last () ;
  TH1F * m4_sideband_Wjet = (TH1F *) input.Get ("m4_sideband_Wjet") ;

  TH1F * m4_upper_DATA = (TH1F *) input.Get ("m4_upper_DATA") ;      
  TH1F * m4_signal_DATA = (TH1F *) input.Get ("m4_signal_DATA") ;    
  TH1F * m4_lower_DATA = (TH1F *) input.Get ("m4_lower_DATA") ;      
  TH1F * m4_sideband_DATA = (TH1F *) input.Get ("m4_sideband_DATA") ;

  //PG fit separately numerator and denominator
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  TF1 * numFitFunc = new TF1 ("numFitFunc", attenuatedCB, 0., 1000., 7) ;
  numFitFunc->SetLineWidth (1) ;
  numFitFunc->SetLineColor (kBlue+2) ;
  numFitFunc->SetNpx (10000) ;
  numFitFunc->SetParameter (0, m4_signal_total->Integral ()) ;  //PG N
  numFitFunc->SetParameter (1, 200.) ;                          //PG gaussian mean
  numFitFunc->SetParameter (2, 20.) ;                           //PG gaussian sigma
  numFitFunc->SetParameter (3, 0.1) ;                           //PG joint point
  numFitFunc->SetParameter (4, 10) ;                            //PG power law exponent
  numFitFunc->SetParameter (5, 200) ;                           //PG fermi E
  numFitFunc->SetParameter (6, 10) ;                            //PG kT
  m4_signal_total->Fit (numFitFunc, "L", "", 100., 800.) ;
  TH1F * num_fit_error = new TH1F ("num_fit_error", "", 70, 100., 800.) ;
  (TVirtualFitter::GetFitter ())->GetConfidenceIntervals (num_fit_error, 0.68) ;

  TF1 * denFitFunc = new TF1 ("denFitFunc", attenuatedCB, 0., 1000., 7) ;
  denFitFunc->SetLineWidth (1) ;
  denFitFunc->SetLineColor (kBlue+2) ;
  denFitFunc->SetNpx (10000) ;
  denFitFunc->SetParameter (0, m4_sideband_total->Integral ()) ;
  denFitFunc->SetParameter (1, 200.) ;
  denFitFunc->SetParameter (2, 20.) ;
  denFitFunc->SetParameter (3, 0.1) ;
  denFitFunc->SetParameter (4, 10) ;
  denFitFunc->SetParameter (5, 200) ;
  denFitFunc->SetParameter (6, 10) ;
  m4_sideband_total->Fit (denFitFunc, "L", "", 100., 800.) ;
  TH1F * den_fit_error = new TH1F ("den_fit_error", "", 70, 100., 800.) ;
  (TVirtualFitter::GetFitter ())->GetConfidenceIntervals (den_fit_error, 0.68) ;

  TCanvas c1 ;
  den_fit_error->SetFillColor (kGray+2) ;
  den_fit_error->Draw ("E3") ;
  m4_sideband_total->Draw ("same") ;
  c1.Print ("denominator_fit.pdf", "pdf") ;

  //PG calculate the ratio of the functions
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

  TH1F * func_ratio = (TH1F *) m4_signal_total->Clone ("func_ratio") ;
  func_ratio->Reset () ;
  for (int j = 1 ; j <= func_ratio->GetNbinsX () ; ++j)
    {
      double x = func_ratio->GetBinCenter (j) ;
      func_ratio->SetBinContent (j, numFitFunc->Eval (x) / denFitFunc->Eval (x)) ;
      double sqRelError = num_fit_error->GetBinError (j) * num_fit_error->GetBinError (j) / 
                           (num_fit_error->GetBinContent (j) * num_fit_error->GetBinContent (j)) +
                          den_fit_error->GetBinError (j) * den_fit_error->GetBinError (j) / 
                           (den_fit_error->GetBinContent (j) * den_fit_error->GetBinContent (j)) ;
      double error = sqrt (sqRelError) * func_ratio->GetBinContent (j) ;
      func_ratio->SetBinError (j, error) ;
    }

  //PG look at the ratio of the functions
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
  
  stack_m4_signal->Draw ("hist") ;
  c1.Print ("numerator.pdf", "pdf") ;

  stack_m4_sideband->Draw ("hist") ;
  c1.Print ("denominator.pdf", "pdf") ;

  TH1F * ratio_total = (TH1F *) m4_signal_total->Clone ("ratio") ;
  ratio_total->Divide (m4_sideband_total) ;
  
  func_ratio->SetLineColor (kBlue) ;
  func_ratio->SetFillStyle (0) ;
  
  c1.DrawFrame (100., 0., 1000., 2.) ;
  ratio_total->Draw ("same") ;
  func_ratio->Draw ("histE2same") ;
  c1.Print ("ratio.pdf", "pdf") ;
  
  //PG extrapolate the background from side-band
  //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
  
//  TH1F * extrapolated_bkg = m4_sideband_total->Clone ("extrapolated_bkg") ; //PG simil-closure test --> stats issue
  TH1F * extrapolated_bkg = m4_sideband_DATA->Clone ("extrapolated_bkg") ; //PG analysis
  extrapolated_bkg->Multiply (func_ratio) ;

  TLegend leg_compare (0.2, 0.2, 0.6, 0.4, NULL, "brNDC") ;
  leg_compare.SetBorderSize (0) ;
  leg_compare.SetTextFont (42) ;
  leg_compare.SetTextSize (0.04) ;
  leg_compare.SetLineColor (1) ;
  leg_compare.SetLineStyle (1) ;
  leg_compare.SetLineWidth (1) ;
  leg_compare.SetFillColor (0) ;
  leg_compare.SetFillStyle (0) ;
  leg_compare.AddEntry (m4_signal_total, "simulation in signal region", "lp") ;
  leg_compare.AddEntry (extrapolated_bkg, "extrapolated bkg in SR", "lp") ;

  c1.SetLogy () ;
  c1.DrawFrame (100, 0.1, 800, 5000) ;
  extrapolated_bkg->SetStats (0) ;
  extrapolated_bkg->SetTitle ("") ;
  extrapolated_bkg->SetLineColor (kRed) ;
  extrapolated_bkg->Draw ("same") ;
//  m4_signal_total->SetStats (0) ;
//  m4_signal_total->SetMarkerStyle (5) ;
//  m4_signal_total->SetMarkerColor (kBlack) ;
//  m4_signal_total->Draw ("same") ;
//  leg_compare.Draw () ;
  c1.Print ("compare_signal_region_new.pdf", "pdf") ;
 
}
TF1* fit_histo_poly3bkg_floatwidth_poly2bkg_combinemassvnfit( bool isPbPb, int centlow, int centhigh, TH1D * histo, TH1D * h_mc_matched_signal, TH1D * h_mc_matched_kpiswapped, int ipt, TString cfgname, bool get_sig_bkg_ratio = false, TH1D * Ratio_signal_foreground = NULL, TH1D * h_vnvsmass = NULL, TH1D * h_vnvspt = NULL, TString vnorder = "v2", TString EPorSP = "SP", TH1D * h_vnvspt_bkg = NULL)
{
	Double_t setparam0=100.;
	Double_t setparam1=1.8648;
	Double_t setparam2=0.03;
	Double_t setparam3=0.005;
	Double_t setparam4=0.1;
	Double_t setparam7=0.1;
	Double_t fixparam1=1.8648;

	double fit_range_low = generalfitrange_masslow;
	double fit_range_high = generalfitrange_masshigh;
	double histomassbinsize = histo->GetBinWidth(10);

	float ptmin = ptbins[ipt];
	float ptmax = ptbins[ipt+1];

	//remove the fit function from v2 fit when perform v3 fit
	if( histo->GetListOfFunctions()->FindObject(Form("fmass_combinemassvnfit_%s_%d",cfgname.Data(),ipt)) )
		histo->GetListOfFunctions()->Remove( histo->GetListOfFunctions()->FindObject(Form("fmass_combinemassvnfit_%s_%d",cfgname.Data(),ipt)) );

	TH1F* histo_copy_nofitfun = ( TH1F * ) histo->Clone("histo_copy_nofitfun");
	TH1F* histo_massfit = ( TH1F * ) histo->Clone("histo_massfit");

	TCanvas* cfg= new TCanvas(Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_%s_%d",cfgname.Data(),ipt),Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_%s_%d",cfgname.Data(),ipt),600,600);

    gPad->SetRightMargin(0.043);
    gPad->SetLeftMargin(0.18);
    gPad->SetTopMargin(0.1);
    gPad->SetBottomMargin(0.145);

    TF1* f = new TF1(Form("f_%s_%d",cfgname.Data(),ipt),"[0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x", fit_range_low, fit_range_high);

	f->SetParLimits(10,-1000,1000);
	f->SetParLimits(3,0.001,0.05);
	f->SetParLimits(2,0.01,0.1);
	f->SetParLimits(7,0.02,0.2);
	f->SetParLimits(5,0,1);
	f->SetParLimits(4,0,1);

	f->SetParameter(0,setparam0);
	f->SetParameter(1,setparam1);
	f->SetParameter(2,setparam2);
	f->SetParameter(3,setparam3);
	f->SetParameter(4,setparam4);

	f->FixParameter(7,setparam7);
	f->FixParameter(8,setparam1);
	f->FixParameter(5,1);
	f->FixParameter(1,fixparam1);
	f->FixParameter(9,0);
	f->FixParameter(10,0);
	f->FixParameter(11,0);
	f->FixParameter(12,0);
	f->FixParameter(6,0);

	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"q","",fit_range_low,fit_range_high);
	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"q","",fit_range_low,fit_range_high);
	f->ReleaseParameter(1);
	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L m","",fit_range_low,fit_range_high);

	f->FixParameter(1,f->GetParameter(1));
	f->FixParameter(2,f->GetParameter(2));
	f->FixParameter(3,f->GetParameter(3));
	f->FixParameter(4,f->GetParameter(4));
	f->FixParameter(5,0);
	f->ReleaseParameter(7);
	f->ReleaseParameter(8);
	f->SetParameter(7,setparam7);
    f->SetParameter(8,setparam1);//mean for swapped candidates
    //if want to fix parameter 8 to parameter 1
    //f->FixParameter(8,f->GetParameter(1));

	h_mc_matched_kpiswapped->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_kpiswapped->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_kpiswapped->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_kpiswapped->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L m","",fit_range_low,fit_range_high);

	f->FixParameter(5,h_mc_matched_signal->Integral(0,1000)/(h_mc_matched_kpiswapped->Integral(0,1000)+h_mc_matched_signal->Integral(0,1000)));
	f->FixParameter(7,f->GetParameter(7));
	f->FixParameter(8,f->GetParameter(8));
	f->ReleaseParameter(9);
	f->ReleaseParameter(10);
	f->ReleaseParameter(11);
	f->ReleaseParameter(12);

	f->SetLineColor(kRed);

	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"q","",fit_range_low,fit_range_high);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"q","",fit_range_low,fit_range_high);
	f->ReleaseParameter(1);
	////Release Parameter 6 to float signal width
	f->ReleaseParameter(6);
	f->SetParameter(6,0);
	f->SetParLimits(6,-1.0,1.0);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L m","",fit_range_low,fit_range_high);

	//begin combine fit
    TF1* fmass_combinemassvnfit = new TF1(Form("fmass_combinemassvnfit_%s_%d",cfgname.Data(),ipt),"[0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x", fit_range_low, fit_range_high);

	TF1* fvn_combinemassvnfit = new TF1(Form("fvn_combinemassvnfit_%s_%d",cfgname.Data(),ipt), "( ( [0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) ) / ( [0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x ) ) * [13] + ( 1.0 - ( ( [0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) ) / ( [0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x ) ) ) * ( [14] + [15] * x + [16] * x * x)", fit_range_low, fit_range_high);

	ROOT::Math::WrappedMultiTF1 wfmass_combinemassvnfit(*fmass_combinemassvnfit,1);
	ROOT::Math::WrappedMultiTF1 wfvn_combinemassvnfit(*fvn_combinemassvnfit,1);

	ROOT::Fit::DataOptions opt;
	ROOT::Fit::DataRange range_massfit;
	// set the data range
	range_massfit.SetRange(fit_range_low,fit_range_high);
	ROOT::Fit::BinData datamass(opt,range_massfit);
	ROOT::Fit::FillData(datamass, histo);

	ROOT::Fit::DataRange range_vnfit;
	range_vnfit.SetRange(fit_range_low,fit_range_high);
	ROOT::Fit::BinData datavn(opt,range_vnfit);
	ROOT::Fit::FillData(datavn, h_vnvsmass);

	ROOT::Fit::Chi2Function chi2_B(datamass, wfmass_combinemassvnfit);
	ROOT::Fit::Chi2Function chi2_SB(datavn, wfvn_combinemassvnfit);

	GlobalChi2_poly3bkg_floatwidth_poly2bkg globalChi2(chi2_B, chi2_SB);

	ROOT::Fit::Fitter fitter;

	const int Npar = 17;
	double par0[Npar];
	for( int ipar = 0; ipar < f->GetNpar(); ipar++ )
		par0[ipar] = f->GetParameter(ipar);
	par0[13] = 0.01;
	par0[14] = 0.10;
	par0[15] = 0.05;
	par0[16] = 0.05;

	// create before the parameter settings in order to fix or set range on them
	fitter.Config().SetParamsSettings(Npar,par0);
	// fix parameter
	fitter.Config().ParSettings(2).Fix();
	fitter.Config().ParSettings(3).Fix();
	fitter.Config().ParSettings(4).Fix();
	fitter.Config().ParSettings(5).Fix();
	fitter.Config().ParSettings(7).Fix();
	fitter.Config().ParSettings(8).Fix();
	// set limits on the third and 4-th parameter
	fitter.Config().ParSettings(1).SetLimits(1.7, 2.0);
	//fitter.Config().ParSettings(12).SetStepSize(0.005);
	//fitter.Config().UseWeightCorrection();

	fitter.Config().MinimizerOptions().SetPrintLevel(0);
	fitter.Config().SetMinimizer("Minuit2","Migrad");

	// fit FCN function directly
	// (specify optionally data size and flag to indicate that is a chi2 fit)
	//fitter.FitFCN(Npar,globalChi2,0,datamass.Size()+datavn.Size(),false);
	fitter.FitFCN(Npar,globalChi2,0,datamass.Size()+datavn.Size(),true);
	ROOT::Fit::FitResult result = fitter.Result();
	result.Print(std::cout);

	fmass_combinemassvnfit->SetFitResult( result, iparmassfit_poly3bkg_floatwidth_poly2bkg);
	fmass_combinemassvnfit->SetRange(range_massfit().first, range_massfit().second);
	fmass_combinemassvnfit->SetLineColor(kRed);
	histo->GetListOfFunctions()->Add(fmass_combinemassvnfit);

	fvn_combinemassvnfit->SetFitResult( result, iparvnfit_poly3bkg_floatwidth_poly2bkg);
	fvn_combinemassvnfit->SetRange(range_vnfit().first, range_vnfit().second);
	fvn_combinemassvnfit->SetLineColor(4.0);
	fvn_combinemassvnfit->SetLineStyle(2);
	h_vnvsmass->GetListOfFunctions()->Add(fvn_combinemassvnfit);

	h_vnvspt->SetBinContent( ipt+1, fvn_combinemassvnfit->GetParameter(13));
	h_vnvspt->SetBinError( ipt+1, fvn_combinemassvnfit->GetParError(13));

	//double x[2] = {1.73, 1.864};
	//double error[2];
	//does not work
	//result.GetConfidenceIntervals(2, 1, 1, x, error, 0.683, false);

	//h_vnvspt_bkg->SetBinContent( ipt+1, fvn_combinemassvnfit->GetParameter(13) + fvn_combinemassvnfit->GetParameter(14) * 1.864);
	//h_vnvspt_bkg->SetBinError( ipt+1, error[0]);
	h_vnvspt_bkg->SetBinContent( ipt+1, fvn_combinemassvnfit->GetParameter(14) + fvn_combinemassvnfit->GetParameter(15) * 1.864 + fvn_combinemassvnfit->GetParameter(16) * 1.864 * 1.864);
	h_vnvspt_bkg->SetBinError( ipt+1, 0. );

	TCanvas* cfg_massfit_combinemassvn = new TCanvas(Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_massfit_combinemassvn_%s_%d_%s_%s",cfgname.Data(),ipt,vnorder.Data(),EPorSP.Data()),Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_massfit_combinemassvn_%s_%d_%s_%s",cfgname.Data(),ipt,vnorder.Data(),EPorSP.Data()),600,600);

    gPad->SetRightMargin(0.043);
    gPad->SetLeftMargin(0.18);
//    gPad->SetTopMargin(0.1);
    gPad->SetBottomMargin(0.145);

	histo->SetXTitle("m_{#piK} (GeV/c^{2})");
	histo->SetYTitle("Entries / (5 MeV/c^{2})");
	histo->GetXaxis()->CenterTitle();
	histo->GetYaxis()->CenterTitle();
	//histo->SetAxisRange(0,histo->GetMaximum()*1.4*1.2,"Y");
	histo->GetXaxis()->SetRangeUser(fit_range_low+0.0001,fit_range_high-0.0001);
	histo->GetXaxis()->SetTitleOffset(1.3);
	histo->GetYaxis()->SetTitleOffset(1.8);
	histo->GetXaxis()->SetLabelOffset(0.007);
	histo->GetYaxis()->SetLabelOffset(0.007);
	histo->GetXaxis()->SetTitleSize(0.045);
	histo->GetYaxis()->SetTitleSize(0.045);
	histo->GetXaxis()->SetTitleFont(42);
	histo->GetYaxis()->SetTitleFont(42);
	histo->GetXaxis()->SetLabelFont(42);
	histo->GetYaxis()->SetLabelFont(42);
	histo->GetXaxis()->SetLabelSize(0.04);
	histo->GetYaxis()->SetLabelSize(0.04);
	histo->SetMarkerSize(0.8);
	histo->SetMarkerStyle(20);
	histo->SetStats(0);
	histo->Draw("e");
	
	TF1* background = new TF1(Form("background_%s_%d",cfgname.Data(),ipt),"[0]+[1]*x+[2]*x*x+[3]*x*x*x");
	background->SetParameter(0,fmass_combinemassvnfit->GetParameter(9));
	background->SetParameter(1,fmass_combinemassvnfit->GetParameter(10));
	background->SetParameter(2,fmass_combinemassvnfit->GetParameter(11));
	background->SetParameter(3,fmass_combinemassvnfit->GetParameter(12));
	background->SetLineColor(4);
	background->SetRange(fit_range_low,fit_range_high);
	background->SetLineStyle(2);

    TF1* mass = new TF1(Form("fmass_%s_%d",cfgname.Data(),ipt),"[0]*([5]*([4]*Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6]))))");
    mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(3),f->GetParameter(4),f->GetParameter(5),f->GetParameter(6));
    mass->SetParError(0,f->GetParError(0));
    mass->SetParError(1,f->GetParError(1));
    mass->SetParError(2,f->GetParError(2));
    mass->SetParError(3,f->GetParError(3));
    mass->SetParError(4,f->GetParError(4));
    mass->SetParError(5,f->GetParError(5));
    mass->SetParError(6,f->GetParError(6));
    mass->SetFillColor(kOrange-3);
    mass->SetFillStyle(3002);
    mass->SetLineColor(kOrange-3);
    mass->SetLineWidth(3);
    mass->SetLineStyle(2);

	TF1* massSwap = new TF1(Form("fmassSwap_%s_%d",cfgname.Data(),ipt),"[0]*(1-[2])*Gaus(x,[1],[3]*(1.0 +[4]))/(sqrt(2*3.14159)*[3]*(1.0 +[4]))");
	massSwap->SetParameters(fmass_combinemassvnfit->GetParameter(0),fmass_combinemassvnfit->GetParameter(8),fmass_combinemassvnfit->GetParameter(5),fmass_combinemassvnfit->GetParameter(7),fmass_combinemassvnfit->GetParameter(6));
	massSwap->SetParError(0,fmass_combinemassvnfit->GetParError(0));
	massSwap->SetParError(1,fmass_combinemassvnfit->GetParError(8));
	massSwap->SetParError(2,fmass_combinemassvnfit->GetParError(5));
	massSwap->SetParError(3,fmass_combinemassvnfit->GetParError(7));
	massSwap->SetParError(4,fmass_combinemassvnfit->GetParError(6));
	massSwap->SetFillColor(kGreen+4);
	massSwap->SetFillStyle(3005);
	massSwap->SetLineColor(kGreen+4);
	massSwap->SetLineWidth(3);
	massSwap->SetLineStyle(1);

	background->Draw("same");   
	mass->SetRange(fit_range_low,fit_range_high);	
	mass->Draw("same");
	massSwap->SetRange(fit_range_low,fit_range_high);
	massSwap->Draw("same");

	Double_t yield = mass->Integral(fit_range_low,fit_range_high)/histomassbinsize;
	Double_t yieldErr = mass->Integral(fit_range_low,fit_range_high)/histomassbinsize*mass->GetParError(0)/mass->GetParameter(0);

	TLegend* leg = new TLegend(0.65,0.58,0.82,0.88,NULL,"brNDC");
	leg->SetBorderSize(0);
	leg->SetTextSize(0.04);
	leg->SetTextFont(42);
	leg->SetFillStyle(0);
	leg->AddEntry(histo,"Data","pl");
	leg->AddEntry(fmass_combinemassvnfit,"Fit","l");
	leg->AddEntry(mass,"D^{0}+#bar{D^{#lower[0.2]{0}}} Signal","f");
	leg->AddEntry(massSwap,"K-#pi swapped","f");
	leg->AddEntry(background,"Combinatorial","l");
	leg->Draw("same");

	TLatex Tl;
	Tl.SetNDC();
	Tl.SetTextAlign(12);
	Tl.SetTextSize(0.05);
	Tl.SetTextFont(42);
	Tl.DrawLatex(0.18,0.965, "#font[61]{CMS}");
	if( isPbPb )
		Tl.DrawLatex(0.61,0.965, "#scale[0.8]{PbPb #sqrt{s_{NN}} = 5.02 TeV}");
	else
		Tl.DrawLatex(0.65,0.965, "#scale[0.8]{pp #sqrt{s_{NN}} = 5.02 TeV}");

	TLatex* tex;

	if( isPbPb )
	{
		tex = new TLatex(0.22,0.83,"|y| < 1.0");
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();

		tex = new TLatex(0.22,0.78,Form("Cent. %d-%d%%", centlow, centhigh));
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();

		tex = new TLatex(0.22,0.73,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();

		tex = new TLatex(0.22,0.68,Form("N_{sig}: %d #pm %d",int(yield),int(yieldErr)));
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();
	}
	else
	{
		tex = new TLatex(0.22,0.83,"|y| < 1.0");
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();

		tex = new TLatex(0.22,0.78,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();

		tex = new TLatex(0.22,0.73,Form("N_{sig}: %d #pm %d",int(yield),int(yieldErr)));
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();
	}

	histo_copy_nofitfun->Draw("esame");

	if( get_sig_bkg_ratio )
	{
		for(int ibin = 0; ibin < histo->GetNbinsX(); ibin++)
		{
			double foreground = 0.;
			double signal = 0.;
			double ratio = 0.;
			double ratioError = 999.;

			double massbinleftedge = massmin + histomassbinsize * ibin;
			double massbinrightedge = massmin + histomassbinsize * (ibin+1);

			if( massbinleftedge > (fit_range_low - 0.0002) && massbinrightedge < (fit_range_high + 0.0002) )
			{
				foreground = f->Integral(massbinleftedge, massbinrightedge)/histomassbinsize;
				//foregroundErr = f->IntegralError(massbinleftedge, massbinrightedge)/histomassbinsize;
				//foreground =  histo->Integral(ibin+1, ibin+1);
				signal = mass->Integral(massbinleftedge, massbinrightedge)/histomassbinsize + massSwap->Integral(massbinleftedge, massbinrightedge)/histomassbinsize;
				//signal = mass->Integral(massbinleftedge, massbinrightedge)/histomassbinsize;
				//signal = foreground - background->Integral(massbinleftedge, massbinrightedge)/histomassbinsize;
				//signalErr = signal * yieldErr/yield;
				if( foreground > 0 )
				{
					ratio = signal/foreground;
					ratioError = TMath::Sqrt( foreground * ratio * (1.0 - ratio) ) / foreground;
				}
				else
				{
					ratio = 0.5;
					ratioError = 0.5;
				}
			}
			else
			{
				ratio = 0.0;
				ratioError = 1.0;
			}

			Ratio_signal_foreground->SetBinContent(ibin+1, ratio);
			Ratio_signal_foreground->SetBinError(ibin+1, ratioError);
		}

		TF1* Func_Ratio_signal_foreground = new TF1(Form("Func_Ratio_signal_foreground_%s_%d",cfgname.Data(),ipt),"([0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))))/([0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x)", generalfitrange_masslow, generalfitrange_masshigh);
        for( int ipar = 0; ipar < 13; ipar++ )
        {
            Func_Ratio_signal_foreground->SetParameter( ipar, f->GetParameter(ipar));
            Func_Ratio_signal_foreground->SetParError(ipar, f->GetParError(ipar));
        }
		Func_Ratio_signal_foreground->SetLineColor(2.0);
		Ratio_signal_foreground->GetListOfFunctions()->Add(Func_Ratio_signal_foreground);
	}

	if(isPbPb)
	{
		cfg_massfit_combinemassvn->SaveAs(Form("Plots_vn/combinemassvnfit/DMass_combinemassvnfit_isPbPb%d_%s_cent%dto%d_%d_%s_%s_poly3bkg_floatwidth_poly2bkg_combinemassvnfit.pdf", isPbPb, cfgname.Data(), centlow, centhigh, ipt, vnorder.Data(),EPorSP.Data()));
		cfg_massfit_combinemassvn->SaveAs(Form("Plots_vn/combinemassvnfit/DMass_combinemassvnfit_isPbPb%d_%s_cent%dto%d_%d_%s_%s_poly3bkg_floatwidth_poly2bkg_combinemassvnfit.png", isPbPb, cfgname.Data(), centlow, centhigh, ipt, vnorder.Data(),EPorSP.Data()));
	}

	TCanvas* cfg_vnfit_combinemassvn = new TCanvas(Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_vnfit_combinemassvn_%s_%d_%s_%s",cfgname.Data(),ipt,vnorder.Data(),EPorSP.Data()),Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_vnfit_combinemassvn_%s_%d_%s_%s",cfgname.Data(),ipt,vnorder.Data(),EPorSP.Data()),600,600);

	h_vnvsmass->GetYaxis()->SetRangeUser(-0.2, 0.6);
	if( vnorder == "v2") h_vnvsmass->GetYaxis()->SetTitle("v_{2}");
	if( vnorder == "v3") h_vnvsmass->GetYaxis()->SetTitle("v_{3}");
	h_vnvsmass->GetXaxis()->SetTitle("m_{#piK} (GeV/c^{2})");
	h_vnvsmass->GetXaxis()->SetTitleSize(0.05);
	h_vnvsmass->GetYaxis()->SetTitleSize(0.05);

	h_vnvsmass->SetMarkerColor(4.0);
	h_vnvsmass->SetLineColor(4.0);
	h_vnvsmass->SetMarkerStyle(21);
	h_vnvsmass->SetMarkerSize(1.3);
	h_vnvsmass->Draw();

    TLatex Tl2; 
    Tl2.SetNDC();
    Tl2.SetTextAlign(12);
    Tl2.SetTextSize(0.05);
    Tl2.SetTextFont(42);
    Tl2.DrawLatex(0.125,0.965, "#font[61]{CMS}");
    Tl2.DrawLatex(0.57,0.965, "#scale[0.8]{PbPb #sqrt{s_{NN}} = 5.02 TeV}");

    tex = new TLatex(0.18,0.83,"|y| < 1.0");
    tex->SetNDC();
    tex->SetTextFont(42);
    tex->SetTextSize(0.04);
    tex->SetLineWidth(2);
    tex->Draw();

    tex = new TLatex(0.18,0.78,Form("Cent. %d-%d%%", centlow, centhigh));
    tex->SetNDC();
    tex->SetTextFont(42);
    tex->SetTextSize(0.04);
    tex->SetLineWidth(2);
    tex->Draw();

    tex = new TLatex(0.18,0.73,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
    tex->SetNDC();
    tex->SetTextFont(42);
    tex->SetTextSize(0.04);
    tex->SetLineWidth(2);
    tex->Draw();

    if( vnorder == "v2" ) 
        tex = new TLatex(0.55,0.83,Form("v_{2}^{sig} = %.3f #pm %.3f",fvn_combinemassvnfit->GetParameter(13), fvn_combinemassvnfit->GetParError(13)));
    else if( vnorder == "v3" )
        tex = new TLatex(0.55,0.83,Form("v_{3}^{sig} = %.3f #pm %.3f",fvn_combinemassvnfit->GetParameter(13), fvn_combinemassvnfit->GetParError(13)));

    tex->SetNDC();
    tex->SetTextFont(42);
    tex->SetTextSize(0.04);
    tex->SetLineWidth(2);
    tex->Draw();
	
	if(isPbPb)
	{
		cfg_vnfit_combinemassvn->SaveAs(Form("Plots_vn/combinemassvnfit/cfg_vnfit_combinemassvn_%s_cent%dto%d_%d_%s_%s_poly3bkg_floatwidth_poly2bkg_combinemassvnfit.pdf",cfgname.Data(),centlow,centhigh,ipt,vnorder.Data(),EPorSP.Data()));
		cfg_vnfit_combinemassvn->SaveAs(Form("Plots_vn/combinemassvnfit/cfg_vnfit_combinemassvn_%s_cent%dto%d_%d_%s_%s_poly3bkg_floatwidth_poly2bkg_combinemassvnfit.png",cfgname.Data(),centlow,centhigh,ipt,vnorder.Data(),EPorSP.Data()));
	}

	return mass;
}
Esempio n. 26
0
//void testFit(int count=3,Double_t ptmin=30.,Double_t ptmax=40,TString sample="PbPb")
void compareUpgrade(int option=2)
{

  int count; Double_t ptmin; Double_t ptmax; TString sample;
  int nmin,nmax,mymaxhisto;
  
  if (option==1)
  {count=3; ptmin=30.; ptmax=40; sample="PbPb"; mymaxhisto=2000;  };
  if (option==2)
  {count=1; ptmin=2.; ptmax=3; sample="PbPbMB"; mymaxhisto=600000;};


  TCanvas* c= new TCanvas(Form("c%d",count),"",600,600);
  TFile *file=new TFile(Form("FitsFiles/Fits_%s_%d.root",sample.Data(), count));
  TH1D* h = (TH1D*)file->Get(Form("h-%d",count));
  TH1D* hMCSignal = (TH1D*)file->Get(Form("hMCSignal-%d",count));
  TH1D* hMCSwapped = (TH1D*)file->Get(Form("hMCSwapped-%d",count));
    
  TF1* f = new TF1(Form("f%d",count),"[0]*([7]*([9]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[9])*Gaus(x,[1],[10])/(sqrt(2*3.14159)*[10]))+(1-[7])*Gaus(x,[1],[8])/(sqrt(2*3.14159)*[8]))+[3]+[4]*x+[5]*x*x+[6]*x*x*x", 1.7, 2.0);

  f->SetParLimits(4,-1000,1000);
  f->SetParLimits(10,0.001,0.05);
  f->SetParLimits(2,0.01,0.1);
  f->SetParLimits(8,0.02,0.2);
  f->SetParLimits(7,0,1);
  f->SetParLimits(9,0,1);
  
  f->SetParameter(0,setparam0);
  f->SetParameter(1,setparam1);
  f->SetParameter(2,setparam2);
  f->SetParameter(10,setparam10);
  f->SetParameter(9,setparam9);

  f->FixParameter(8,setparam8);
  f->FixParameter(7,1);
  f->FixParameter(1,fixparam1);
  f->FixParameter(3,0);
  f->FixParameter(4,0);
  f->FixParameter(5,0);
  f->FixParameter(6,0);
  h->GetEntries();
  
  hMCSignal->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
 
  f->ReleaseParameter(1);
  hMCSignal->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
  

  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(10,f->GetParameter(10));
  f->FixParameter(9,f->GetParameter(9));
  f->FixParameter(7,0);
  f->ReleaseParameter(8);
  f->SetParameter(8,setparam8);
  
  hMCSwapped->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
  
  f->FixParameter(7,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(8,f->GetParameter(8));
  f->ReleaseParameter(3);
  f->ReleaseParameter(4);
  f->ReleaseParameter(5);
  f->ReleaseParameter(6);

  f->SetLineColor(kRed);
  

  /*
  TCanvas*mycanvas=new TCanvas("mycanvas","mycanvas",1000,500);
  mycanvas->Divide(2,1);
  mycanvas->cd(1);
  hMCSignal->Draw();
  mycanvas->cd(2);
  hMCSwapped->Draw();
  mycanvas->SaveAs("mycanvas.pdf");
*/
  
  h->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  //f->ReleaseParameter(2);                                     // you need to release these two parameters if you want to perform studies on the sigma shape
  //f->ReleaseParameter(10);                                   // you need to release these two parameters if you want to perform studies on the sigma shape
  h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
  
  std::cout<<"parameter 10="<<f->GetParameter(10)<<std::endl;

  TF1* background = new TF1(Form("background%d",count),"[0]+[1]*x+[2]*x*x+[3]*x*x*x");
  background->SetParameter(0,f->GetParameter(3));
  background->SetParameter(1,f->GetParameter(4));
  background->SetParameter(2,f->GetParameter(5));
  background->SetParameter(3,f->GetParameter(6));
  background->SetLineColor(4);
  background->SetRange(minhisto,maxhisto);
  background->SetLineStyle(2);
  
  TF1* mass = new TF1(Form("fmass%d",count),"[0]*([3]*([4]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[4])*Gaus(x,[1],[5])/(sqrt(2*3.14159)*[5])))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(7));
  mass->SetParError(4,f->GetParError(9));
  mass->SetParError(5,f->GetParError(10));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);
  
  TF1* massSwap = new TF1(Form("fmassSwap%d",count),"[0]*(1-[2])*Gaus(x,[1],[3])/(sqrt(2*3.14159)*[3])");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8));
  massSwap->SetParError(0,f->GetParError(0));
  massSwap->SetParError(1,f->GetParError(1));
  massSwap->SetParError(2,f->GetParError(7));
  massSwap->SetParError(3,f->GetParError(8));
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);
  
  h->SetXTitle("m_{#piK} (GeV/c^{2})");
  h->SetYTitle("Entries / (5 MeV/c^{2})");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  h->SetAxisRange(0,h->GetMaximum()*1.4*1.2,"Y");
  h->GetXaxis()->SetTitleOffset(1.3);
  h->GetYaxis()->SetTitleOffset(1.8);
  h->GetXaxis()->SetLabelOffset(0.007);
  h->GetYaxis()->SetLabelOffset(0.007);
  h->GetXaxis()->SetTitleSize(0.045);
  h->GetYaxis()->SetTitleSize(0.045);
  h->GetXaxis()->SetTitleFont(42);
  h->GetYaxis()->SetTitleFont(42);
  h->GetXaxis()->SetLabelFont(42);
  h->GetYaxis()->SetLabelFont(42);
  h->GetXaxis()->SetLabelSize(0.04);
  h->GetYaxis()->SetLabelSize(0.04);
  h->SetMarkerSize(0.8);
  h->SetMarkerStyle(20);
  h->SetStats(0);
  h->Draw("e");

  background->Draw("same");   
  mass->SetRange(minhisto,maxhisto);	
  mass->Draw("same");
  massSwap->SetRange(minhisto,maxhisto);
  massSwap->Draw("same");
  f->Draw("same");
  
  Double_t yield = mass->Integral(minhisto,maxhisto)/binwidthmass;
  Double_t yieldtotal = f->Integral(minhisto,maxhisto)/binwidthmass;
  Double_t yieldErr = mass->Integral(minhisto,maxhisto)/binwidthmass*mass->GetParError(0)/mass->GetParameter(0);
  
  std::cout<<"yield signal="<<yield<<std::endl;
  std::cout<<"total counts="<<yieldtotal<<std::endl;

  TLegend* leg = new TLegend(0.65,0.58,0.82,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D^{0}+#bar{D^{#lower[0.2]{0}}} Signal","f");
  leg->AddEntry(massSwap,"K-#pi swapped","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  TLatex Tl;
  Tl.SetNDC();
  Tl.SetTextAlign(12);
  Tl.SetTextSize(0.04);
  Tl.SetTextFont(42);
  Tl.DrawLatex(0.18,0.93, "#scale[1.25]{CMS} Performance");
  Tl.DrawLatex(0.65,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));

  TLatex* tex;

  tex = new TLatex(0.22,0.78,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();

  tex = new TLatex(0.22,0.83,"|y| < 1.0");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();

  h->GetFunction(Form("f%d",count))->Delete();
  TH1F* histo_copy_nofitfun = ( TH1F * ) h->Clone("histo_copy_nofitfun");
  histo_copy_nofitfun->Draw("esame");

 TH1D* hTest = new TH1D("hTest","",nbinsmasshisto,minhisto,maxhisto);

 for (int m=0;m<yieldtotal;m++){
 double r = f->GetRandom();
 hTest->Fill(r);
 
 }

 TF1* ffaketotal=(TF1*)f->Clone("ffake");
 TF1* ffakemass=(TF1*)mass->Clone("ffakemass");
 TF1* ffakebackground=(TF1*)background->Clone("ffakebackground");
 TF1* ffakemassSwap=(TF1*)massSwap->Clone("ffakemassSwap");
 
 Double_t yieldtotal_original = ffaketotal->Integral(minhisto,maxhisto)/binwidthmass;
 Double_t yieldmass_original = ffakemass->Integral(minhisto,maxhisto)/binwidthmass;
 Double_t yieldbackground_original = ffakebackground->Integral(minhisto,maxhisto)/binwidthmass;
 Double_t yieldswapped_original = ffakemassSwap->Integral(minhisto,maxhisto)/binwidthmass;

 TH1D* hTestFake = new TH1D("hTestFake","",nbinsmasshisto,minhisto,maxhisto);
  ffakemass->SetParameter(2,ffaketotal->GetParameter(2)*0.8);
  ffakemass->SetParameter(10,ffaketotal->GetParameter(10)*0.8);
 
Double_t yieldmass_modified= ffakemass->Integral(minhisto,maxhisto)/binwidthmass;

cout<<"mass original="<<yieldmass_original<<endl;
cout<<"mass modified="<<yieldmass_modified<<endl;

 for (int m=0;m<yieldmass_original*scalefactor;m++){
   double r = ffakemass->GetRandom();
   hTestFake->Fill(r);
 }

  for (int m=0;m<(int)(yieldbackground_original*scalefactor*bkgreduction);m++){
   double r = ffakebackground->GetRandom();
   hTestFake->Fill(r);
 }
 
 for (int m=0;m<(int)(yieldswapped_original*scalefactor*bkgreduction);m++){
   double r = ffakemassSwap->GetRandom();
   hTestFake->Fill(r);
 }

 TCanvas*c2=new TCanvas("c2","c2",500,500);
 c2->cd();
 hTest->SetMaximum(2000);
  hTest->SetXTitle("m_{#piK} (GeV/c^{2})");
  hTest->SetYTitle("Entries / (5 MeV/c^{2})");
  hTest->GetXaxis()->CenterTitle();
  hTest->GetYaxis()->CenterTitle();
  hTest->SetAxisRange(0,hTest->GetMaximum()*1.*1.2,"Y");
  hTest->GetXaxis()->SetTitleOffset(1.3);
  hTest->GetYaxis()->SetTitleOffset(1.8);
  hTest->GetXaxis()->SetLabelOffset(0.007);
  hTest->GetYaxis()->SetLabelOffset(0.007);
  hTest->GetXaxis()->SetTitleSize(0.045);
  hTest->GetYaxis()->SetTitleSize(0.045);
  hTest->GetXaxis()->SetTitleFont(42);
  hTest->GetYaxis()->SetTitleFont(42);
  hTest->GetXaxis()->SetLabelFont(42);
  hTest->GetYaxis()->SetLabelFont(42);
  hTest->GetXaxis()->SetLabelSize(0.04);
  hTest->GetYaxis()->SetLabelSize(0.04);
  hTest->SetMarkerSize(0.8);
  hTest->SetMarkerStyle(20);
  hTest->SetStats(0);
  hTest->Draw("e");

 hTest->SetLineColor(1);
 hTest->SetMarkerColor(1);
  hTestFake->SetLineColor(2);
 hTestFake->SetMarkerColor(2);

 
 hTest->Draw("ep");
 hTestFake->Draw("epsame");

  TLegend* myleg = new TLegend(0.2177419,0.6292373,0.6633065,0.7266949,NULL,"brNDC");
  myleg->SetBorderSize(0);
  myleg->SetTextSize(0.04);
  myleg->SetTextFont(42);
  myleg->SetFillStyle(0);
  myleg->AddEntry(hTest,"Current CMS, |y|<1, L_{int}=0.5/nb","pl");
  myleg->AddEntry(hTestFake,"Upgraded CMS, |y|<2, L_{int}=1.5/nb","l");
  myleg->Draw("same");

  TLatex* mytex;

  mytex = new TLatex(0.22,0.83,Form("%.0f < p_{T} < %.0f GeV/c",ptmin,ptmax));
  mytex->SetNDC();
  mytex->SetTextFont(42);
  mytex->SetTextSize(0.04);
  mytex->SetLineWidth(2);
  mytex->Draw();
  
  TLatex* mychannel;

  mychannel = new TLatex(0.22,0.765,"D^{0} #rightarrow K#pi");
  mychannel->SetNDC();
  mychannel->SetTextFont(42);
  mychannel->SetTextSize(0.055);
  mychannel->SetLineWidth(2);
  mychannel->Draw();

  TLatex myTl;
  myTl.SetNDC();
  myTl.SetTextAlign(12);
  myTl.SetTextSize(0.04);
  myTl.SetTextFont(42);
  myTl.DrawLatex(0.2,0.90, "#scale[1.25]{CMS} Performance");
  myTl.DrawLatex(0.63,0.90, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));
  
  
  TFile*foutput=new TFile(Form("foutput_%s.root",sample.Data()),"recreate");
  foutput->cd();
  hTest->SetName("hTest");
  hTestFake->SetName("hTestFake");
  hTest->SetMaximum(mymaxhisto);
  hTest->Write();
  hTestFake->SetMaximum(mymaxhisto);
  hTestFake->Write();
  hMCSignal->Write();
  hMCSwapped->Write();
  c2->SaveAs(Form("PlotsUpgrade/canvasPerformance%s.pdf",sample.Data()));
  c2->SaveAs(Form("PlotsUpgrade/canvasPerformance%s.png",sample.Data()));

 
}
Esempio n. 27
0
float TrTasClusterR::GetXCofGTas()
{
  Status = 0;

  if (_nelem < 5) return 0;
  if (!TrTasPar::Head) return 0;

  int ilad = TrTasPar::Head->GetIlad(_tkid);
  if (ilad < 0) return 0;

  int ipk =  TrTasPar::Head->GetIpk(ilad, _address);
  if (ipk < 0) return 0;

  Int_t apk = (TrTasPar::Head->GetAmin(ilad, ipk)+
	       TrTasPar::Head->GetAmax(ilad, ipk))/2;
  Int_t ap1 = apk-20;
  Int_t ap2 = apk+20;

  TString hid = Form("hist%02d%d", ilad+1, ipk+1);

  TH1F *hist1 = (HistDir) ? (TH1F *)HistDir->Get(hid+"1") : 0;
  TH2F *hist2 = (HistDir) ? (TH2F *)HistDir->Get(hid+"2") : 0;

  if (!hist1 || !hist2) {
    if (!HistDir) {
      if (gFile) gFile->cd();
      else gROOT->cd();
      HistDir = new TDirectoryFile("tashist", "TAS histograms");
    }
    TDirectory *sdir = gDirectory;

    HistDir->cd();
    hist1 = new TH1F(hid+"1", Form("TkId %4d (%2d-%d)", _tkid, ilad, ipk),
		     41, ap1-0.5, ap2+0.5);
    hist2 = new TH2F(hid+"2", Form("TkId %4d (%2d-%d)", _tkid, ilad, ipk),
		     41, ap1-0.5, ap2+0.5, 500, 0, 5000);
    if (sdir) sdir->cd();
  }
  hist1->Reset();

  for (int i = 0; i < _nelem; i++)
    if (ap1 <= _address+i && _address+i <= ap2) {
      int addr = _address+i;
      int ib   = addr-ap1+1;
      hist1->SetBinContent(ib, _signal.at(i));
      hist1->SetBinError  (ib, 1);
      hist2->Fill(addr, _signal.at(i));
    }

  double pmax = hist1->GetMaximum();
  for (int i = 0; i < _nelem; i++)
    if (ap1 <= _address+i && _address+i <= ap2) {
      int addr = _address+i;
      int ib   = addr-ap1+1;
      double bc = hist1->GetBinContent(ib);

      if (TrTasPar::Head->IsMasked(ilad, ipk, addr) || bc < -100) {
	if (bc < pmax/2) {
	  bc = pmax/2;
	  hist1->SetBinContent(ib, bc);
	}
	hist1->SetBinError(ib, pmax-bc);
      }
    }

  Double_t xmin = _address-0.25;
  Double_t xmax = _address+_nelem-0.75;

  TF1 *func;
  if (fitmode == SGAUS) {
    func = SGaus(xmin, xmax);
    func->SetParameter(0, TrTasPar::Head->GetFpar(ilad, ipk, 0));
    func->SetParameter(1, TrTasPar::Head->GetFpar(ilad, ipk, 1));
    func->SetParameter(2, TrTasPar::Head->GetFpar(ilad, ipk, 2));
    func->SetParameter(3, TrTasPar::Head->GetFpar(ilad, ipk, 3));

    if (TrTasPar::Head->GetFpar(ilad, ipk, 3) == 0 && 
	TrTasPar::Head->GetFpar(ilad, ipk, 4) == 0) {
      func->FixParameter(3, 0);
      func->FixParameter(4, 0);
    }
    else {
      func->FixParameter(4, TrTasPar::Head->GetFpar(ilad, ipk, 4)); //50
      func->SetParLimits(0, 0, 25000);
      func->SetParLimits(3, 1000, 5000);
    }
  }
  else func = new TF1("func", "gaus", xmin, xmax);

  hist1->Fit(func, "q0R");
  float xmean = func->GetParameter(1);
  delete func;

  // The first sensor is TAS one
  int imult = TkCoo::GetMaxMult(_tkid, xmean);

  Status = TASCLS;
  return TkCoo::GetLocalCoo(_tkid, xmean, imult);
}
Esempio n. 28
0
TF1 *fit(TTree *nt,TTree *ntMC,double ptmin,double ptmax)
{   
   //cout<<cut.Data()<<endl;
   static int count=0;
   count++;
   TCanvas *c= new TCanvas(Form("c%d",count),"",600,600);
   TH1D *h = new TH1D(Form("h%d",count),"",24,5.03,5.99);
   TH1D *hMC = new TH1D(Form("hMC%d",count),"",24,5.03,5.99);
   // Fit function
   TString iNP="Gaus(x,5.36800e+00,5.77122e-02)/(sqrt(2*3.14159)*abs(5.77122e-02))";
   TF1 *f = new TF1(Form("f%d",count),"[0]*(Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2]))+ [3]+[4]*x+[5]*x*x + [11]*("+iNP+")");
   nt->Project(Form("h%d",count),"mass",Form("%s&&pt>%f&&pt<%f",seldata_2y.Data(),ptmin,ptmax));   
   ntMC->Project(Form("hMC%d",count),"mass",Form("%s&&pt>%f&&pt<%f",seldata_2y.Data(),ptmin,ptmax));   
   clean0(h);
   h->Draw();
   f->SetParLimits(4,-1000,0);
   f->SetParLimits(2,0.01,0.05);
   f->SetParameter(0,setparam0);
   f->SetParameter(1,setparam1);
   f->SetParameter(2,setparam2);
   f->FixParameter(1,fixparam1);
   f->SetParLimits(11,0,1000);
   f->SetParameter(11,10);
   f->FixParameter(11,0);
   f->FixParameter(9,0);
   h->GetEntries();

   hMC->Fit(Form("f%d",count),"q","",5,6);
   hMC->Fit(Form("f%d",count),"q","",5,6);
   f->ReleaseParameter(1);
   hMC->Fit(Form("f%d",count),"L q","",5,6);
   hMC->Fit(Form("f%d",count),"L q","",5,6);
   hMC->Fit(Form("f%d",count),"L q","",5,6);
   hMC->Fit(Form("f%d",count),"L m","",5,6);

   f->FixParameter(1,f->GetParameter(1));
   f->FixParameter(2,f->GetParameter(2));
   
   h->Fit(Form("f%d",count),"q","",5,6);
   h->Fit(Form("f%d",count),"q","",5,6);
   f->ReleaseParameter(1);
   h->Fit(Form("f%d",count),"L q","",5,6);
   h->Fit(Form("f%d",count),"L q","",5,6);
   h->Fit(Form("f%d",count),"L q","",5,6);
   h->Fit(Form("f%d",count),"L m","",5,6);
   h->SetMarkerSize(0.8);
   h->SetMarkerStyle(20);
   cout <<h->GetEntries()<<endl;

   // function for background shape plotting. take the fit result from f
   TF1 *background = new TF1(Form("background%d",count),"[0]+[1]*x+[2]*x*x");
   background->SetParameter(0,f->GetParameter(3));
   background->SetParameter(1,f->GetParameter(4));
   background->SetParameter(2,f->GetParameter(5));
   background->SetParameter(3,f->GetParameter(6));
   background->SetLineColor(4);
   background->SetRange(5,6);
   background->SetLineStyle(2);
   
   // function for signal shape plotting. take the fit result from f
   TF1 *Bkpi = new TF1(Form("fBkpi",count),"[0]*("+iNP+")");
   Bkpi->SetParameter(0,f->GetParameter(11));
   Bkpi->SetLineColor(kGreen+1);
   Bkpi->SetFillColor(kGreen+1);
//   Bkpi->SetRange(5.00,5.28);
   Bkpi->SetRange(5.00,6.00);
   Bkpi->SetLineStyle(1);
   Bkpi->SetFillStyle(3004);

   // function for signal shape plotting. take the fit result from f
   TF1 *mass = new TF1(Form("fmass",count),"[0]*(Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2]))");
   mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2));
   mass->SetParError(0,f->GetParError(0));
   mass->SetParError(1,f->GetParError(1));
   mass->SetParError(2,f->GetParError(2));
   mass->SetLineColor(2);
   mass->SetLineStyle(2);

//   cout <<mass->Integral(0,1.2)<<" "<<mass->IntegralError(0,1.2)<<endl;
   h->SetMarkerStyle(24);
   h->SetStats(0);
   h->Draw("e");
   h->SetXTitle("M_{B} (GeV/c^{2})");
   h->SetYTitle("Entries / (40 MeV/c^{2})");
   h->GetXaxis()->CenterTitle();
   h->GetYaxis()->CenterTitle();
   h->SetTitleOffset(1.,"Y");
   h->SetAxisRange(0,h->GetMaximum()*1.2,"Y");
   Bkpi->Draw("same");
   background->Draw("same");   
   mass->SetRange(5,6);
   mass->Draw("same");
   mass->SetLineStyle(2);
   mass->SetFillStyle(3004);
   mass->SetFillColor(2);
   f->Draw("same");

   double yield = mass->Integral(5,6)/0.040;
   double yieldErr = mass->Integral(5,6)/0.04*mass->GetParError(0)/mass->GetParameter(0);


   // Draw the legend:)   
   TLegend *leg = myLegend(0.50,0.5,0.86,0.89);
   leg->AddEntry(h,"CMS Preliminary","");
   leg->AddEntry(h,"p+Pb #sqrt{s_{NN}}= 5.02 TeV","");
   leg->AddEntry(h,Form("%.0f<p_{T}^{B}<%.0f GeV/c",ptmin,ptmax),"");
   leg->AddEntry(h,"Data","pl");
   leg->AddEntry(f,"Fit","l");
   leg->AddEntry(mass,"Signal","f");
   leg->AddEntry(background,"Combinatorial Background","l");
//   leg->AddEntry(Bkpi,"Non-prompt J/#psi","f");
   leg->Draw();
   TLegend *leg2 = myLegend(0.44,0.33,0.89,0.50);
   leg2->AddEntry(h,"B meson","");
   leg2->AddEntry(h,Form("M_{B}=%.2f #pm %.2f MeV/c^{2}",mass->GetParameter(1)*1000.,mass->GetParError(1)*1000.),"");
   leg2->AddEntry(h,Form("N_{B}=%.0f #pm %.0f", yield, yieldErr),"");
   leg2->Draw();

   c->SaveAs(Form("PDFVariation/data/2Gto1G/ResultsBs/BMass-%d.pdf",count));

   return mass;
}
Esempio n. 29
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;
  }
}
void calibration_plot_single(std::string ten_file_txt, std::string ten_file1_txt, std::string ten_file2_txt, std::string title, TCanvas &c3, TCanvas &croom, TCanvas &c00)
{
//Measurement Files


	std::ifstream ten_file(ten_file_txt.c_str()); //first run no cooling
	std::ifstream ten_file1(ten_file1_txt.c_str()); //second run with cooling
	std::ifstream ten_file2(ten_file2_txt.c_str()); //second run with cooling


	//measurement of 10 Min sample before heating: 6/8/16
//	std::ifstream ten_file("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160608_124028.txt"); //first run no cooling
//	std::ifstream ten_file1("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160608_135913.txt"); //second run with cooling
//	std::ifstream ten_file2("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160610_105850.txt"); //second run with cooling

	//measurement of 15 Min sample before heating: 6/8/16
//	std::ifstream ten_file("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160608_142717.txt"); //first run no cooling
//	std::ifstream ten_file1("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160608_144249.txt"); //second run with cooling
//	std::ifstream ten_file2("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160610_130301.txt"); //second run with cooling

	//measurement of 20 Min sample before heating: 6/8/16
//	std::ifstream ten_file("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160608_150113.txt"); //first run no cooling
//	std::ifstream ten_file1("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160608_151527.txt"); //second run with cooling
//	std::ifstream ten_file2("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160610_133314.txt"); //second run with cooling

	//Measurement of 30 min Sample before heating
//	std::ifstream ten_file("./6-3-16/DataFile_160603_141347.txt"); //first run no cooling
//	std::ifstream ten_file1("./6-3-16/DataFile_160603_143027.txt"); //second run with cooling
//	std::ifstream ten_file2("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160607_150843.txt"); //second run with cooling

	//measurement of 2 SC cylinders
//	std::ifstream ten_file("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160610_151411.txt"); //first run no cooling
//	std::ifstream ten_file1("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160610_153114.txt"); //overlapping cylinder
//	std::ifstream ten_file2("/home/josh/Dropbox/Stony\ Brook\ Research\ Team\ Folder/LabVIEW/DATA_Gaussmeter/DataFile_160610_160144.txt"); //non-overlapping cylinder

        std::string str;
        double ti, xi, yi;
        vector<double> ten_time, ten_field, ten_voltage;
        vector<double> ten_time_1, ten_field_1, ten_voltage_1;
        vector<double> ten_time_2, ten_field_2, ten_voltage_2;

        while (std::getline(ten_file, str))
        {
                if(ten_file >> ti >> xi >> yi)
                {
                        ten_time.push_back(ti); //Time
                        ten_voltage.push_back(TMath::Abs(xi)); //Current in mA -> Voltage in mV
                        ten_field.push_back(TMath::Abs(yi)); //Magnetic Field (mT)
                }
        }

        while (std::getline(ten_file1, str))
        {
                if(ten_file1 >> ti >> xi >> yi)
                {
                        ten_time_1.push_back(ti); //Time
                        ten_voltage_1.push_back(TMath::Abs(xi)); //Current in mA -> Voltage in mV
                        ten_field_1.push_back(TMath::Abs(yi)); //Magnetic Field (mT)
                }
        }

        while (std::getline(ten_file2, str))
        {
                if(ten_file2 >> ti >> xi >> yi)
                {
                        ten_time_2.push_back(ti); //Time
                        ten_voltage_2.push_back(TMath::Abs(xi)); //Current in mA -> Voltage in mV
                        ten_field_2.push_back(TMath::Abs(yi)); //Magnetic Field (mT)
                }
        }

	TCanvas *c1 = new TCanvas();
        gr1 = new TGraph(ten_time.size(),&(ten_voltage[0]),&(ten_field[0]));
                gr1->Draw("AP");
                gr1->GetXaxis()->SetTitle("Voltage (mV)");
                gr1->GetYaxis()->SetTitle("Magnitude of Magnetic Field (mT)");
                gr1->SetTitle("Voltage from Power Supply vs. Magnetic Field");
                gr1->SetMarkerColor(kRed);
        TF1 *fit1 = new TF1("fit1","pol1",13,300);
        gr1->Fit("fit1","R");
        TF1 *f1 = gr1->GetFunction("fit1");
                f1->SetName("f1");
                f1->SetLineColor(kRed-n);
                f1->SetRange(0,300);
                f1->Draw("SAME");
        c1->Update();

        gr2 = new TGraph(ten_time_1.size(),&(ten_voltage_1[0]),&(ten_field_1[0]));
                gr2->Draw("p SAME");
                gr2->GetXaxis()->SetTitle("Voltage (mV)");
                gr2->GetYaxis()->SetTitle("Magnitude of Magnetic Field (mT)");
                gr2->SetTitle("Voltage from Power Supply vs. Magnetic Field --- 10 minutes");
                gr2->SetMarkerColor(kBlue);
        TF1 *fit2 = new TF1("fit2","pol1",60,300);
        gr2->Fit("fit2","R");
        TF1 *f2 = gr2->GetFunction("fit2");
                f2->SetName("f2");
                f2->SetLineColor(kBlue-3);
                f2->SetRange(0,300);
                f2->Draw("SAME");
        c1->Update();

        gr3 = new TGraph(ten_time_2.size(),&(ten_voltage_2[0]),&(ten_field_2[0]));
                gr3->Draw("p SAME");
                gr3->GetXaxis()->SetTitle("Voltage (mV)");
                gr3->GetYaxis()->SetTitle("Magnitude of Magnetic Field (mT)");
                gr3->SetTitle("Voltage from Power Supply vs. Magnetic Field");
                gr3->SetMarkerColor(kGreen);
        TF1 *fit3 = new TF1("fit3","pol1",60,300);
        gr3->Fit("fit3","R");
        TF1 *f3 = gr3->GetFunction("fit3");
                f3->SetName("f2");
                f3->SetLineColor(kGreen-3);
                f3->SetRange(0,300);
                f3->Draw("SAME");
        c1->Update();

        leg3 = new TLegend(0.2,0.8,0.48,0.9);
                leg3->AddEntry(gr1,"Room Temperature","p");
                leg3->AddEntry(gr2,"Cryo","p");
                leg3->AddEntry(gr3,"Cryo After Baking","p");
        leg3->Draw();

	TCanvas *c2 = new TCanvas();
	gr4 = new TGraph(ten_time.size(),&(ten_voltage[0]),&(ten_field[0]));
                gr4->Draw("AP");
                gr4->SetMarkerColor(kRed);
	gr5 = new TGraph(ten_time.size(),&(ten_voltage[0]),&(ten_field[0]));
                gr5->Draw("P");
                gr5->SetMarkerColor(kRed);
	TF1 *fit4 = new TF1("fit4","pol1",11,300);
        gr5->Fit("fit4","R");
        TF1 *f4 = gr5->GetFunction("fit4");
                f4->SetName("f4");
                f4->SetLineColor(kBlue-3);
                f4->SetRange(11,300);
                f4->Draw("SAME");
        TF1 *fit5 = new TF1("fit5","pol2",9,11);
        gr4->Fit("fit5","R");
        TF1 *f5 = gr4->GetFunction("fit5");
                f5->SetName("f5");
                f5->SetLineColor(kGreen-3);
                f5->SetRange(9,11);
                f5->Draw("SAME");
	c2->Update();
	
	vector<double> ten_voltageTOfield_1;

	for(int i = 0; i < ten_voltage_1.size(); i++)
	{
		if(ten_voltage_1[i] < 2)
		{
			ten_voltageTOfield_1.push_back(0.00);
		}
		else if(ten_voltage_1[i] < 11)
		{
			ten_voltageTOfield_1.push_back(f5->Eval(ten_voltage_1[i]));
		}
		else
		{
			ten_voltageTOfield_1.push_back(f4->Eval(ten_voltage_1[i]));
		}
	}

	vector<double> ten_voltageTOfield_2;

	for(int i = 0; i < ten_voltage_2.size(); i++)
	{
		if(ten_voltage_2[i] < 2)
		{
			ten_voltageTOfield_2.push_back(0.00);
		}
		else if(ten_voltage_2[i] < 11)
		{
			ten_voltageTOfield_2.push_back(f5->Eval(ten_voltage_2[i]));
		}
		else
		{
			ten_voltageTOfield_2.push_back(f4->Eval(ten_voltage_2[i]));
		}
	}


	c1->Close();
	c2->Close();

	c3.cd();
        gr2 = new TGraph(ten_time_1.size(),&(ten_voltageTOfield_1[0]),&(ten_field_1[0]));
                gr2->Draw("AP");
                gr2->GetXaxis()->SetTitle("Applied Field (mT)");
                gr2->GetXaxis()->SetRangeUser(0,125);
                gr2->GetYaxis()->SetTitle("Magnetic Field within Shield (mT)");
                gr2->GetYaxis()->SetRangeUser(0,125);
                gr2->SetTitle(title.c_str());
                gr2->SetMarkerColor(kBlue);
        gr6 = new TGraph(ten_time_2.size(),&(ten_voltageTOfield_2[0]),&(ten_field_2[0]));
		gr6->SetMarkerColor(kRed);
		gr6->Draw("p SAME");
        TF1 *onetoone = new TF1("onetoone","pol1",0,150);
		onetoone->SetParameter(0,0);
		onetoone->SetParameter(1,1);
		onetoone->SetLineColor(kBlack);
		onetoone->SetLineStyle(7);
	onetoone->Draw("SAME");
        leg4 = new TLegend(0.2,0.8,0.48,0.9);
		leg4->AddEntry(gr2,"Shielding Before Baking","p");
		leg4->AddEntry(gr6,"Shielding After Baking","p");
//		leg4->AddEntry(gr2,"Overlapping Shielding","p");
//		leg4->AddEntry(gr6,"Non-Overlapping Shielding","p");
                leg4->AddEntry(onetoone,"1:1 Reference Line","l");
        leg4->Draw();

        c3.Update();

	c00.cd();
	gr2->SetMarkerColor(n);
	n++;	
	gr2->Draw("p SAME");
	onetoone->Draw("l SAME");
	c00.Update();

	croom.cd();
	gr1->SetMarkerColor(n);
	gr1->Draw("p SAME");

	cout << "All done with: " << title << endl;
}