Exemplo n.º 1
0
void candleplotoption()
{
   TCanvas *c1 = new TCanvas("c1","Candle Presets",1200,800);
   c1->Divide(3,2);

   TRandom *randnum = new TRandom();
   TH2I *h1 = new TH2I("h1","Sin",18,0,360,300,-1.5,1.5);
   h1->GetXaxis()->SetTitle("Deg");
   float myRand;
   for (int i = 0; i < 360; i+=10) {
      for (int j = 0; j < 100; j++) {
         myRand = randnum->Gaus(sin(i*3.14/180),0.2);
         h1->Fill(i,myRand);
      }
   }
   for (int i = 1; i < 7; i++) {
      c1->cd(i);
      char str[16];
      sprintf(str,"candlex%d",i);
      TH2I * myhist = (TH2I*)h1->DrawCopy(str);
      myhist->SetTitle(str);
   }

   TCanvas *c2 = new TCanvas("c2","Candle Individual",1200,800);
   c2->Divide(4,4);
   char myopt[16][8] = {"0","1","11","21","31","30","111","311","301","1111","2321","12111","112111","212111","312111"};
   for (int i = 0; i < 15; i++) {
      c2->cd(i+1);
      char str[16];
      sprintf(str, "candlex(%s)",myopt[i]);
      TH2I * myhist = (TH2I*)h1->DrawCopy(str);
      myhist->SetTitle(str);
   }
}
Exemplo n.º 2
0
void candlehisto()
{
   TCanvas *c1 = new TCanvas("c1","Candle Presets",800,600);
   c1->Divide(3,2);

   TRandom *rand = new TRandom();
   TH2I *h1 = new TH2I("h1","Sin",18,0,360,100,-1.5,1.5);
   h1->GetXaxis()->SetTitle("Deg");

   float myRand;
   for (int i = 0; i < 360; i+=10) {
      for (int j = 0; j < 100; j++) {
         myRand = rand->Gaus(sin(i*3.14/180),0.2);
         h1->Fill(i,myRand);
      }
   }

   for (int i = 1; i < 7; i++) {
      c1->cd(i);
      char str[16];
      sprintf(str,"CANDLEX%d",i);
      TH2I * myhist = (TH2I*)h1->DrawCopy(str);
      myhist->SetTitle(str);
   }

   TCanvas *c2 = new TCanvas("c2","Violin Presets",800,300);
   c2->Divide(2,1);

   for (int i = 1; i < 3; i++) {
      c2->cd(i);
      char str[16];
      sprintf(str,"VIOLINX%d",i);
      TH2I * myhist = (TH2I*)h1->DrawCopy(str);
      myhist->SetFillColor(kGray+2);
   }

   TCanvas *c3 = new TCanvas("c3","Playing with candle and violin-options",800,600);
   c3->Divide(3,2);
   char myopt[6][16] = {"1000000","2000000","3000000","1112111","112111","112111"};
   for (int i = 0; i < 6; i++) {
      c3->cd(i+1);
      char str[16];
      sprintf(str, "candlex(%s)",myopt[i]);
      TH2I * myhist = (TH2I*)h1->DrawCopy(str);
      myhist->SetFillColor(kYellow);
      if (i == 4) {
         TH2I * myhist2 = (TH2I*)h1->DrawCopy("candlex(1000000) same");
         myhist2->SetFillColor(kRed);
      }
      if (i == 5) {
         myhist->SetBarWidth(0.2);
         myhist->SetBarOffset(0.25);
         TH2I * myhist2 = (TH2I*)h1->DrawCopy("candlex(2000000) same");
         myhist2->SetFillColor(kRed);
         myhist2->SetBarWidth(0.6);
         myhist2->SetBarOffset(-0.5);
      }
      myhist->SetTitle(str);
   }
}
void TPTiming ()
{
    TAxis * ax = TPMatchEmul2D->GetZaxis() ;
    ax->SetRangeUser(-1,6) ;

    TCanvas* canv = new TCanvas("canv", "canv") ;
    canv->SetLogz(0) ;
    gStyle->SetOptStat(10) ;
    int color[10]= {1,10,3,4,5,6,7,8,9,2} ;
    gStyle->SetPalette(7, color) ;
    TPMatchEmul2D->GetXaxis()->SetTitle("Phi index");
    TPMatchEmul2D->GetYaxis()->SetTitle("Eta index");
    TPMatchEmul2D->Draw("colz") ;

    TH2I * label = new TH2I("label", "",72, 1, 73, 38, -19, 19) ;
    label->SetMarkerSize(0.6);
    label->SetBit(kCanDelete);
    for (int x=3 ; x<73 ; x+=4) {
        for (int y=21; y<=37; y++) {
            int towernb = 4*(y-21)+1 ;
            label->SetBinContent(x-1, y, towernb) ; //EB+
            label->SetBinContent(x, 40-y, towernb) ; //EB-
        }
    }
    label->Draw("same text") ;

    TLatex txt;
    txt.SetTextSize(0.02);
    TLine line;
    line.SetLineColor(1) ;
    line.SetLineStyle(1) ;
    line.SetLineWidth(1) ;
    TAxis* xAxis = TPMatchEmul2D->GetXaxis();
    TAxis* yAxis = TPMatchEmul2D->GetYaxis();

    // draw SM borders and numbers
    float sm ;
    for (int i=0; i<36 ; i++ ) {
        if (i<18) {
            sm = 4*i+3 ;
            line.DrawLine(sm, 1, sm, 18) ;
            txt.SetTextAlign(32);
            txt.DrawText(sm-1+0.3, -17.7, Form("-%d",i+1));
        }
        else {
            sm = 4*(i-18)+3 ;
            line.DrawLine(sm, 0, sm, -17) ;
            txt.SetTextAlign(12);
            txt.DrawText(sm-2+0.3, 18.5, Form("+%d",i-17));
        }
    }
    line.DrawLine(1, 0, 73, 0) ;
    line.DrawLine(1, -17, 73, -17) ;
    line.DrawLine(1, 1, 73, 1) ;
    line.DrawLine(1, 18, 73, 18) ;

}
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;
}
Exemplo n.º 5
0
int main (int argc, char** argv)
{

  if (argc < 3) {
    printHelp() ;
    exit (1) ;
  }

  std::string inputfiles, inputdir ;
  std::string outputRootName = "histoTPG.root" ;
  int verbose = 0 ;
  int occupancyCut = 0 ;
  std::string l1algo ; 

  bool ok(false) ;
  for (int i=0 ; i<argc ; i++) {
    if (argv[i] == std::string("-h") ) {
      printHelp() ;
      exit(1);
    }
    if (argv[i] == std::string("-i") && argc>i+1) {
      ok = true ;
      inputfiles = argv[i+1] ;
    }
    if (argv[i] == std::string("-d") && argc>i+1) inputdir = argv[i+1] ;
    if (argv[i] == std::string("-o") && argc>i+1) outputRootName = argv[i+1] ;
    if (argv[i] == std::string("-v") && argc>i+1) verbose = atoi(argv[i+1]) ;
    if (argv[i] == std::string("-l1") && argc>i+1) l1algo =  std::string(argv[i+1]) ;
    if (argv[i] == std::string("--cutTPOccup") && argc>i+1) occupancyCut = atoi(argv[i+1]) ;
  }
  if (!ok) {
    std::cout<<"No input files have been given: nothing to do!"<<std::endl ;
    printHelp() ;
    exit(1);
  }
  
  std::vector<int> algobits ;
  std::vector<std::string> algos = split(l1algo,",") ;
  for (unsigned int i=0 ; i<algos.size() ; i++) algobits.push_back(atoi(algos[i].c_str())) ;


  unsigned int ref = 2 ;



  ///////////////////////
  // book the histograms
  ///////////////////////

  TH2F * occupancyTP = new TH2F("occupancyTP", "Occupancy TP data", 72, 1, 73, 38, -19, 19) ;
  occupancyTP->GetYaxis()->SetTitle("eta index") ;
  occupancyTP->GetXaxis()->SetTitle("phi index") ;
  TH2F * occupancyTPEmul = new TH2F("occupancyTPEmul", "Occupancy TP emulator", 72, 1, 73, 38, -19, 19) ;
  occupancyTPEmul->GetYaxis()->SetTitle("eta index") ;
  occupancyTPEmul->GetXaxis()->SetTitle("phi index") ;

  TH1F * TP = new TH1F("TP", "TP", 256, 0., 256.) ;
  TP->GetXaxis()->SetTitle("TP (ADC)") ;
  TH1F * TPEmul = new TH1F("TPEmul", "TP Emulator", 256, 0., 256.) ;
  TPEmul->GetXaxis()->SetTitle("TP (ADC)") ;
  TH1F * TPEmulMax = new TH1F("TPEmulMax", "TP Emulator max", 256, 0., 256.) ;
  TPEmulMax->GetXaxis()->SetTitle("TP (ADC)") ;
  TH3F * TPspectrumMap3D = new TH3F("TPspectrumMap3D", "TP data spectrum map", 72, 1, 73, 38, -19, 19, 256, 0., 256.) ;
  TPspectrumMap3D->GetYaxis()->SetTitle("eta index") ;
  TPspectrumMap3D->GetXaxis()->SetTitle("phi index") ;

  TH1F * TPMatchEmul = new TH1F("TPMatchEmul", "TP data matching Emulator", 7, -1., 6.) ;
  TH1F * TPEmulMaxIndex = new TH1F("TPEmulMaxIndex", "Index of the max TP from Emulator", 7, -1., 6.) ;
  TH3I * TPMatchEmul3D = new TH3I("TPMatchEmul3D", "TP data matching Emulator", 72, 1, 73, 38, -19, 19, 7, -1, 6) ;
  TPMatchEmul3D->GetYaxis()->SetTitle("eta index") ;
  TPMatchEmul3D->GetXaxis()->SetTitle("phi index") ;

  TH2I * ttfMismatch = new TH2I("ttfMismatch", "TTF mismatch map",  72, 1, 73, 38, -19, 19) ;
  ttfMismatch->GetYaxis()->SetTitle("eta index") ;
  ttfMismatch->GetXaxis()->SetTitle("phi index") ;

  ///////////////////////
  // Chain the trees:
  ///////////////////////

  TChain * chain = new TChain ("EcalTPGAnalysis") ;
  std::vector<std::string> files ;
  if (inputfiles.find(std::string(",")) != std::string::npos) files = split(inputfiles,",") ;
  if (inputfiles.find(std::string(":")) != std::string::npos) {
    std::vector<std::string> filesbase = split(inputfiles,":") ;
    if (filesbase.size() == 4) {
      int first = atoi(filesbase[1].c_str()) ;
      int last = atoi(filesbase[2].c_str()) ;
      for (int i=first ; i<=last ; i++) {
	std::stringstream name ;
	name<<filesbase[0]<<i<<filesbase[3] ;
	files.push_back(name.str()) ;
      }
    }
  }
  for (unsigned int i=0 ; i<files.size() ; i++) {
    files[i] = inputdir+"/"+files[i] ;
    std::cout<<"Input file: "<<files[i]<<std::endl ;
    chain->Add (files[i].c_str()) ;
  }

  EcalTPGVariables treeVars ;
  setBranchAddresses (chain, treeVars) ;

  int nEntries = chain->GetEntries () ;
  std::cout << "Number of entries: " << nEntries <<std::endl ;    



  ///////////////////////
  // Main loop over entries
  ///////////////////////

  for (int entry = 0 ; entry < nEntries ; ++entry) {
    chain->GetEntry (entry) ;
    if (entry%1000==0) std::cout <<"------> "<< entry+1 <<" entries processed" << " <------\n" ; 
    if (verbose>0) std::cout<<"Run="<<treeVars.runNb<<" Evt="<<treeVars.runNb<<std::endl ;

    // trigger selection if any
    bool keep(false) ;
    if (!algobits.size()) keep = true ; // keep all events when no trigger selection
    for (unsigned int algo = 0 ; algo<algobits.size() ; algo++)
      for (unsigned int ntrig = 0 ; ntrig < treeVars.nbOfActiveTriggers ; ntrig++)
	if (algobits[algo] == treeVars.activeTriggers[ntrig]) keep = true ;
    if (!keep) continue ;
    
             
    // loop on towers
    for (unsigned int tower = 0 ; tower < treeVars.nbOfTowers ; tower++) {

      int tp = getEt(treeVars.rawTPData[tower]) ;
      int emul[5] = {getEt(treeVars.rawTPEmul1[tower]),
		     getEt(treeVars.rawTPEmul2[tower]),
		     getEt(treeVars.rawTPEmul3[tower]),
		     getEt(treeVars.rawTPEmul4[tower]),
		     getEt(treeVars.rawTPEmul5[tower])} ;
      int maxOfTPEmul = 0 ;
      int indexOfTPEmulMax = -1 ;
      for (int i=0 ; i<5 ; i++) if (emul[i]>maxOfTPEmul) {
	maxOfTPEmul = emul[i] ; 
	indexOfTPEmulMax = i ;
      }
      int ieta = treeVars.ieta[tower] ;
      int iphi = treeVars.iphi[tower] ;
      int nbXtals = treeVars.nbOfXtals[tower] ;
      int ttf = getTtf(treeVars.rawTPData[tower]) ;


      if (verbose>9 && (tp>0 || maxOfTPEmul>0)) {
	std::cout<<"(phi,eta, Nbxtals)="<<std::dec<<iphi<<" "<<ieta<<" "<<nbXtals<<std::endl ;
	std::cout<<"Data Et, TTF: "<<tp<<" "<<ttf<<std::endl ;
	std::cout<<"Emulator: " ;
	for (int i=0 ; i<5 ; i++) std::cout<<emul[i]<<" " ;
	std::cout<<std::endl ;
      }


      // Fill TP spctrum
      TP->Fill(tp) ;
      TPEmul->Fill(emul[ref]) ;
      TPEmulMax->Fill(maxOfTPEmul) ;
      TPspectrumMap3D->Fill(iphi, ieta, tp) ;


      // Fill TP occupancy
      if (tp>occupancyCut) occupancyTP->Fill(iphi, ieta) ;
      if (emul[ref]>occupancyCut) occupancyTPEmul->Fill(iphi, ieta) ;


      // Fill TP-Emulator matching
      // comparison is meaningful when:
      if (tp>0 && nbXtals == 25) {
	bool match(false) ;
	for (int i=0 ; i<5 ; i++) {
	  if (tp == emul[i]) {
	    TPMatchEmul->Fill(i+1) ;
	    TPMatchEmul3D->Fill(iphi, ieta, i+1) ;
	    match = true ;
	  }
	}
	if (!match) {
	  TPMatchEmul->Fill(-1) ;
	  TPMatchEmul3D->Fill(iphi, ieta, -1) ;
	  if (verbose>5) {
	    std::cout<<"MISMATCH"<<std::endl ;
	    std::cout<<"(phi,eta, Nbxtals)="<<std::dec<<iphi<<" "<<ieta<<" "<<nbXtals<<std::endl ;
	    std::cout<<"Data Et, TTF: "<<tp<<" "<<ttf<<std::endl ;
	    std::cout<<"Emulator: " ;
	    for (int i=0 ; i<5 ; i++) std::cout<<emul[i]<<" " ;
	    std::cout<<std::endl ;
	  }
	}
      }
      if (maxOfTPEmul>0) TPEmulMaxIndex->Fill(indexOfTPEmulMax+1) ;


      // Fill TTF mismatch
      if ((ttf==1 || ttf==3) && nbXtals != 25) ttfMismatch->Fill(iphi, ieta) ;


    } // end loop towers


  } // endloop entries

  

  ///////////////////////
  // Format & write histos
  ///////////////////////


  // 1. TP Spectrum  
  TProfile2D * TPspectrumMap = TPspectrumMap3D->Project3DProfile("yx") ;
  TPspectrumMap->SetName("TPspectrumMap") ;

  // 2. TP Timing
  TH2F * TPMatchEmul2D = new TH2F("TPMatchEmul2D", "TP data matching Emulator", 72, 1, 73, 38, -19, 19) ;
  TH2F * TPMatchFraction2D = new TH2F("TPMatchFraction2D", "TP data: fraction of non-single timing", 72, 1, 73, 38, -19, 19) ;
  TPMatchEmul2D->GetYaxis()->SetTitle("eta index") ; 
  TPMatchEmul2D->GetXaxis()->SetTitle("phi index") ;
  TPMatchEmul2D->GetZaxis()->SetRangeUser(-1,6) ;
  TPMatchFraction2D->GetYaxis()->SetTitle("eta index") ; 
  TPMatchFraction2D->GetXaxis()->SetTitle("phi index") ;
  for (int binx=1 ; binx<=72 ; binx++)    
    for (int biny=1 ; biny<=38 ; biny++) {
      int maxBinz = 5 ;
      double maxCell = TPMatchEmul3D->GetBinContent(binx, biny, maxBinz) ;
      double totalCell(0) ;
      for (int binz=1; binz<=7 ; binz++) {
	double content = TPMatchEmul3D->GetBinContent(binx, biny, binz) ;
	if (content>maxCell) {
	  maxCell = content ;
	  maxBinz = binz ;
	}
	totalCell += content ;
      }
      if (maxCell <=0) maxBinz = 2 ; // empty cell
      TPMatchEmul2D->SetBinContent(binx, biny, float(maxBinz)-2.) ; //z must be in [-1,5] 
      double fraction = 0 ;
      if (totalCell>0) fraction = 1.- maxCell/totalCell ;
      TPMatchFraction2D->SetBinContent(binx, biny, fraction) ;
      if (totalCell > maxCell && verbose>9) {
	std::cout<<"--->"<<std::endl ;	
	for (int binz=1; binz<=7 ; binz++) {	  
	  std::cout<< "(phi,eta, z): (" 
		   << TPMatchEmul3D->GetXaxis()->GetBinLowEdge(binx) 
		   << ", " << TPMatchEmul3D->GetYaxis()->GetBinLowEdge(biny) 
		   << ", " << TPMatchEmul3D->GetZaxis()->GetBinLowEdge(binz)		   
		   << ") Content="<<TPMatchEmul3D->GetBinContent(binx, biny, binz)		   
		   << ", erro="<<TPMatchEmul3D->GetBinContent(binx, biny, binz)	   
		   << std::endl ;	
	}
      }
    }



  TFile saving (outputRootName.c_str (),"recreate") ;
  saving.cd () ;
  
  occupancyTP->Write() ;
  occupancyTPEmul->Write() ;
  
  TP->Write() ;
  TPEmul->Write() ;
  TPEmulMax->Write() ;
  TPspectrumMap->Write() ;

  TPMatchEmul->Write() ; 
  TPMatchEmul3D->Write() ; 
  TPEmulMaxIndex->Write() ;
  TPMatchEmul2D->Write() ; 
  TPMatchFraction2D->Write() ; 

  ttfMismatch->Write() ; 

     
  saving.Close () ;
  delete chain ;

  return 0 ;
}
Exemplo n.º 6
0
void ReadTree_normDet(){

  bool testrun          = 0;
  const int norder_     = 4;
  const int QnBinOrder_ = 2;
  const double vtxCut   = 15.;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0; //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;
  double qnHFx_EP[NumEPNames];
  double qnHFy_EP[NumEPNames];
  double sumET_EP[NumEPNames];

  TFile * fQNDet;
  TH1D * hqnHFDet_x[NumEPNames];
  TH1D * hqnHFDet_y[NumEPNames];

  TFile * fQN;
  TH1D * hqbins[NCENT][NEPSymm];

  TFile * fVNDet;
  TH2D * hVNDetX_0[NQN];
  TH2D * hVNDetY_0[NQN];
  TH2D * hVNDetX_1[NQN];
  TH2D * hVNDetY_1[NQN];
  TH2D * hVNDetX_full[NQN];
  TH2D * hVNDetY_full[NQN];

  TFile * fHists;
  TDirectory * qwebye;
  TH2D * hVn2Dfull[NCENT][NEPSymm][NQN];
  TH2D * hVn2Dsub0[NCENT][NEPSymm][NQN];
  TH2D * hVn2Dsub1[NCENT][NEPSymm][NQN];
  TH2D * hVn2D0v1[NCENT][NEPSymm][NQN];
  TH1D * hVnFull[NCENT][NEPSymm][NQN];
  TH1D * hVnSub0[NCENT][NEPSymm][NQN];
  TH1D * hVnSub1[NCENT][NEPSymm][NQN];
  TH1I * Mult[NCENT][NEPSymm][NQN];
  TH2D * h2Vn2D0v1[NCENT][NEPSymm][NQN];
  TH1D * h2Vn2D0v1Magnitude[NCENT][NEPSymm][NQN];

  double VnRaw_x_0;
  double VnRaw_y_0;
  double VnRaw_x_1;
  double VnRaw_y_1;
  double VnRaw_x_full;
  double VnRaw_y_full;

  double sumw_0;
  double sumw_1;
  double sumw_full;

  double VnCorrected_x_0;
  double VnCorrected_y_0;
  double VnCorrected_x_1;
  double VnCorrected_y_1;
  double VnCorrected_x_full;
  double VnCorrected_y_full;

  int evtMult_0;
  int evtMult_1;
  int evtMult_full;

  //
  // MAIN
  //
  setTDRStyle();
  TH1D::SetDefaultSumw2();
  TH2D::SetDefaultSumw2();
  TH1I::SetDefaultSumw2();

  //-- Set up analyzer objects
  fAna = new TFile("/rfs/jcastle/PbPb2015/PixelTracking_MB2/EbyETree_pixel_noTeff.root");

  tree   = (TTree *) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);

  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);
  tree->SetBranchAddress("qnHFx_EP",                &qnHFx_EP);
  tree->SetBranchAddress("qnHFy_EP",                &qnHFy_EP);
  tree->SetBranchAddress("sumET_EP",                &sumET_EP);

  //-- Get the QN Detector histograms
  fQNDet = new TFile( Form("../../../../../v%i/eta2.4/AnalyzerResults/Q%iDet.root", QnBinOrder_, QnBinOrder_) );
  for(int iEP = 0; iEP < NumEPNames; iEP++){
    int EPbin  = EPSymmPartnerBin[iEP];
    if( EPbin != EPSymmBin ) continue;
    hqnHFDet_x[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_x_%s", EPNames[iEP].data()) );
    hqnHFDet_y[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_y_%s", EPNames[iEP].data()) );
  }

  //-- Setup the QN binning objects
  fQN = new TFile( Form( "../../../../../v%i/eta2.4/AnalyzerResults/q%iCuts.root", QnBinOrder_, QnBinOrder_) );
  for(int icent = 0; icent < NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      hqbins[icent][iEP] = (TH1D*) fQN->Get( Form("hqbins_%s_c%i", EPSymmNames[iEP].data(), icent) );
    }
  }

  //-- Set up VN detector objects 
  fVNDet = new TFile( Form("V%iDet.root", norder_ ) );
  for(int iqn = 0; iqn < NQN; iqn++){
    hVNDetX_0[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_0/hVNDetX_0_qbin%i",   iqn) );
    hVNDetY_0[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_0/hVNDetY_0_qbin%i",   iqn) );
    hVNDetX_1[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_1/hVNDetX_1_qbin%i",   iqn) );
    hVNDetY_1[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_1/hVNDetY_1_qbin%i",   iqn) );
    hVNDetX_full[iqn] = (TH2D*) fVNDet->Get( Form("FullEvt/hVNDetX_full_qbin%i", iqn) );
    hVNDetY_full[iqn] = (TH2D*) fVNDet->Get( Form("FullEvt/hVNDetY_full_qbin%i", iqn) );
  }

  //-- Setup the output objects
  fHists = new TFile("CastleEbyE.root","recreate");
  qwebye = (TDirectory*) fHists->mkdir("qwebye");

  for(int iqn = 0; iqn < NQN; iqn++){
    for(int icent = 0; icent < NCENT; icent++){
      for(int iEP = 0; iEP < NEPSymm; iEP++){    
	if( iEP != EPSymmBin ) continue;

	qwebye->cd();
	hVn2Dfull[icent][iEP][iqn]          = new TH2D(Form("hVn2Dfull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2Dfull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2Dfull[icent][iEP][iqn]->SetOption("colz");
	hVn2Dfull[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs}", norder_) );
	hVn2Dfull[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs}", norder_) );

	hVn2Dsub0[icent][iEP][iqn]          = new TH2D( Form("hVn2Dsub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2Dsub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2Dsub0[icent][iEP][iqn]->SetOption("colz");
	hVn2Dsub0[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a}", norder_) );
	hVn2Dsub0[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a}", norder_) );

	hVn2Dsub1[icent][iEP][iqn]          = new TH2D( Form("hVn2Dsub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2Dsub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2Dsub1[icent][iEP][iqn]->SetOption("colz");
	hVn2Dsub1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,b}", norder_) );
	hVn2Dsub1[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,b}", norder_) );

	hVn2D0v1[icent][iEP][iqn]           = new TH2D( Form("hVn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2D0v1[icent][iEP][iqn]->SetOption("colz");
	hVn2D0v1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b}", norder_, norder_) );
	hVn2D0v1[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b}", norder_, norder_) );

	hVnFull[icent][iEP][iqn]            = new TH1D( Form("hVnFull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVnFull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	hVnFull[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i}", norder_) );
	hVnFull[icent][iEP][iqn]->GetYaxis()->SetTitle( "Events" );

	hVnSub0[icent][iEP][iqn]            = new TH1D( Form("hVnSub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVnSub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	hVnSub0[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,a}", norder_) );

	hVnSub1[icent][iEP][iqn]            = new TH1D( Form("hVnSub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVnSub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	hVnSub1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,b}", norder_) );

	Mult[icent][iEP][iqn]               = new TH1I( Form("Mult_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("Mult_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 300, 1, 1500 );
	Mult[icent][iEP][iqn]->GetXaxis()->SetTitle("Multiplicity");

	h2Vn2D0v1[icent][iEP][iqn]          = new TH2D( Form("h2Vn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("h2Vn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	h2Vn2D0v1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2", norder_, norder_) );
	h2Vn2D0v1[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("(v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b})/2", norder_, norder_) );
	h2Vn2D0v1[icent][iEP][iqn]->SetOption("colz");

	h2Vn2D0v1Magnitude[icent][iEP][iqn] = new TH1D( Form("h2Vn2D0v1Magnitude_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("h2Vn2D0v1Magnitude_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	h2Vn2D0v1Magnitude[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("|(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2|", norder_, norder_) );

      }
    } 
  }
    
  //
  // Tree Loop
  //
    
  cout<<"Begin FINAL loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if( testrun ) N = 10000;
  else          N = tree->GetEntries();

  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout<<"Processing Event "<<ievent+1<<"\t"<<100.*(ievent+1)/(double)N<<"% Completed"<<endl;
      
    tree->GetEntry(ievent);

    //-- Vertex Cut
    if(TMath::Abs(vtx) > vtxCut) continue;

    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- begin EP loop
    for(int iEP = 0; iEP < NEP; iEP++){

      int EPbin  = EPSymmPartnerBin[iEP];
      if( EPbin != EPSymmBin ) continue;

      //-- Calculate qbin
      double qx    = qnHFx_EP[iEP];
      double qy    = qnHFy_EP[iEP];
      double qxDet = hqnHFDet_x[iEP]->GetBinContent(icent+1);
      double qyDet = hqnHFDet_y[iEP]->GetBinContent(icent+1);
      double sumET = sumET_EP[iEP];
      if(sumET == 0) continue;
      qx -= qxDet;
      qy -= qyDet;
      qx /= sumET;
      qy /= sumET;
      double qn = TMath::Sqrt( qx*qx + qy*qy );
      int   iqn = hqbins[icent][EPbin]->FindBin( qn ) - 1;
      if(iqn >= NQN) continue;

      //-- Reset raw and sumw values
      VnRaw_x_0    = 0;
      VnRaw_y_0    = 0;
      VnRaw_x_1    = 0;
      VnRaw_y_1    = 0;
      VnRaw_x_full = 0;
      VnRaw_y_full = 0;                

      sumw_0       = 0;
      sumw_1       = 0;
      sumw_full    = 0;

      evtMult_0    = 0;
      evtMult_1    = 0;
      evtMult_full = 0;

      //-- Begin analyzer histogram loops
      for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
	for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){

	  if(sumw->GetBinContent(ipt+1,ieta+1) !=0){

	    //-- Subevent 0 (eta >= 0)
	    if(etabinsDefault[ieta] >= 0){
	      VnRaw_x_0     += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VnRaw_y_0     += sumwqy->GetBinContent(ipt+1,ieta+1);
	      sumw_0        += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_0     += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Subevent 1 (eta < 0)
	    else{
	      VnRaw_x_1     += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VnRaw_y_1     += sumwqy->GetBinContent(ipt+1,ieta+1);
	      sumw_1        += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_1     += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Full Event
	    VnRaw_x_full    += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VnRaw_y_full    += sumwqy->GetBinContent(ipt+1,ieta+1);
	    sumw_full       += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_full    += hMult->GetBinContent(ipt+1,ieta+1);

	  }

	} //-- End eta loop
      } //-- End pt loop

      //-- Fill Histograms, only use events that have at least two tracks in each SE
      if(sumw_0 == 0 || sumw_1 == 0 || evtMult_1 < 2 || evtMult_full < 2) continue;

      VnRaw_x_full /= sumw_full;
      VnRaw_y_full /= sumw_full;
	
      VnRaw_x_0 /= sumw_0;
      VnRaw_y_0 /= sumw_0;
	
      VnRaw_x_1 /= sumw_1;
      VnRaw_y_1 /= sumw_1;
                
      //-- Full Tracker
      VnCorrected_x_full = VnRaw_x_full - hVNDetX_full[iqn]->GetBinContent(icent+1, EPbin+1);
      VnCorrected_y_full = VnRaw_y_full - hVNDetY_full[iqn]->GetBinContent(icent+1, EPbin+1);
      double vn_full     = TMath::Sqrt( VnCorrected_x_full * VnCorrected_x_full +  VnCorrected_y_full * VnCorrected_y_full);

      hVnFull[icent][EPbin][iqn]   -> Fill( vn_full );
      hVn2Dfull[icent][EPbin][iqn] -> Fill(VnCorrected_x_full, VnCorrected_y_full);

      Mult[icent][EPbin][iqn]->Fill(evtMult_full);

      //-- SubEvt 0 (Eta > 0)
      VnCorrected_x_0 = VnRaw_x_0 - hVNDetX_0[iqn]->GetBinContent(icent+1, EPbin+1);
      VnCorrected_y_0 = VnRaw_y_0 - hVNDetY_0[iqn]->GetBinContent(icent+1, EPbin+1);
      double vn_0     = TMath::Sqrt( VnCorrected_x_0 * VnCorrected_x_0 + VnCorrected_y_0 * VnCorrected_y_0 );

      hVnSub0[icent][EPbin][iqn]   -> Fill( vn_0 );
      hVn2Dsub0[icent][EPbin][iqn] -> Fill(VnCorrected_x_0, VnCorrected_y_0);
                
      //-- SubEvt 1 (Eta < 0)
      VnCorrected_x_1 = VnRaw_x_1 - hVNDetX_1[iqn]->GetBinContent(icent+1, EPbin+1);
      VnCorrected_y_1 = VnRaw_y_1 - hVNDetY_1[iqn]->GetBinContent(icent+1, EPbin+1);
      double vn_1     = TMath::Sqrt( VnCorrected_x_1 * VnCorrected_x_1 + VnCorrected_y_1 *VnCorrected_y_1 );

      hVnSub1[icent][EPbin][iqn]   -> Fill( vn_1 );
      hVn2Dsub1[icent][EPbin][iqn] -> Fill(VnCorrected_x_1, VnCorrected_y_1);

      //-- SubEvt Difference
      double vn0m1_x = VnCorrected_x_0 - VnCorrected_x_1;
      double vn0m1_y = VnCorrected_y_0 - VnCorrected_y_1;
      hVn2D0v1[icent][EPbin][iqn]->Fill(vn0m1_x, vn0m1_y);	

      //-- SubEvt Difference for DD response
      double vn0m1_x2 = (VnCorrected_x_0 - VnCorrected_x_1) / 2.;
      double vn0m1_y2 = (VnCorrected_y_0 - VnCorrected_y_1) / 2.;
      h2Vn2D0v1[icent][EPbin][iqn]->Fill(vn0m1_x2, vn0m1_y2);

      double vn0m12 = TMath::Sqrt( pow(vn0m1_x2, 2) + pow(vn0m1_y2, 2) );
      h2Vn2D0v1Magnitude[icent][EPbin][iqn]->Fill(vn0m12);

    } //-- End EP loop        

  } //-- End Event loop

  cout<<"End FINAL loop!"<<endl;
        
  fHists->Write();
  cout<<"File written, process completed"<<endl;
    
}
// Do the extraction of the actual constants
void ExtractCDCDeformation(TString filename = "hd_root.root"){

    // Open our input and output file
    thisFile = TFile::Open(filename);
    TFile *outputFile = TFile::Open("CDCDeformation_Results.root", "RECREATE");

    // Check to make sure it is open
    if (thisFile == 0) {
        cout << "Unable to open file " << filename.Data() << "...Exiting" << endl;
        return;
    }

    // This stream will be for outputting the results in a format suitable for the CCDB
    // Will wait to open until needed
    ofstream textFile;
    textFile.open("CDC_Deformation.txt");

    // We want to display the direction of the shift as well as the magnitude in the "CDC view"
    // Let's make it happen
    int straw_offset[29] = {0,0,42,84,138,192,258,324,404,484,577,670,776,882,1005,1128,1263,1398,1544,1690,1848,2006,2176,2346,2528,2710,2907,3104,3313};
    int Nstraws[28] = {42, 42, 54, 54, 66, 66, 80, 80, 93, 93, 106, 106, 123, 123, 135, 135, 146, 146, 158, 158, 170, 170, 182, 182, 197, 197, 209, 209};
    double radius[28] = {10.72134, 12.08024, 13.7795, 15.14602, 18.71726, 20.2438, 22.01672, 23.50008, 25.15616, 26.61158, 28.33624, 29.77388, 31.3817, 32.75838, 34.43478, 35.81146, 38.28542, 39.7002, 41.31564, 42.73042, 44.34078, 45.75302, 47.36084, 48.77054, 50.37582, 51.76012, 53.36286, 54.74716};
    double phi[28] = {0, 0.074707844, 0.038166294, 0.096247609, 0.05966371, 0.012001551, 0.040721951, 0.001334527, 0.014963808, 0.048683644, 0.002092645, 0.031681749, 0.040719354, 0.015197341, 0.006786058, 0.030005892, 0.019704045, -0.001782064, -0.001306618, 0.018592421, 0.003686784, 0.022132975, 0.019600866, 0.002343723, 0.021301449, 0.005348855, 0.005997358, 0.021018761};

    TH2D * Amplitude_view[29];
    TH2D * Direction_view[29];
    TH2D * Vertical_view[29];
    TH2D * Horizontal_view[29];

    outputFile->mkdir("PerRing");
    outputFile->cd("PerRing");
    for(unsigned int iring=0; iring<28; iring++){
        double r_start = radius[iring] - 0.8;
        double r_end = radius[iring] + 0.8;
        double phi_start = phi[iring]; 
        double phi_end = phi_start + TMath::TwoPi();

        char hname[256];
        sprintf(hname, "Amplitude_view_ring[%d]", iring+1);
        Amplitude_view[iring+1] = new TH2D(hname, "", Nstraws[iring], phi_start, phi_end, 1, r_start, r_end);
        sprintf(hname, "Direction_view_ring[%d]", iring+1);
        Direction_view[iring+1] = new TH2D(hname, "", Nstraws[iring], phi_start, phi_end, 1, r_start, r_end);
        sprintf(hname, "Vertical_view_ring[%d]", iring+1);
        Vertical_view[iring+1] = new TH2D(hname, "", Nstraws[iring], phi_start, phi_end, 1, r_start, r_end);
        sprintf(hname, "Horizontal_view_ring[%d]", iring+1);
        Horizontal_view[iring+1] = new TH2D(hname, "", Nstraws[iring], phi_start, phi_end, 1, r_start, r_end);
    }

    //Fit function for 
    TF1 *f1 = new TF1("f1", "[0] + [1] * TMath::Cos(x + [2])", -3.14, 3.14);
    f1->SetParLimits(0, 0.5, 1.0);
    f1->SetParLimits(1, 0.0, 0.35);
    //f1->SetParLimits(2, -3.14, 3.14);
    f1->SetParameters(0.78, 0.0, 0.0);

    outputFile->cd();
    outputFile->mkdir("FitParameters");
    outputFile->cd("FitParameters");

    // Make some histograms to get the distributions of the fit parameters
    TH1I *h1_c0 = new TH1I("h1_c0", "Distribution of Constant", 100, 0.5, 1.0);
    TH1I *h1_c1 = new TH1I("h1_c1", "Distribution of Amplitude", 100, 0.0, 0.35);
    TH1I *h1_c2 = new TH1I("h1_c2", "Direction of Longest Drift Time", 100, -3.14, 3.14);
    TH1F *h1_c2_weighted = new TH1F("h1_c2_weighted", "Distribution of Direction weighted by amplitude", 100, -3.14, 3.14);
    TH2I *h2_c0_c1 = new TH2I("h2_c0_c1", "c_{1} Vs. c_{0}; c_{0}; c_{1}", 100, 0.5, 1.0, 100, 0, 0.35);
    TH2I *h2_c0_c2 = new TH2I("h2_c0_c2", "c_{2} Vs. c_{0}; c_{0}; c_{2}", 100, 0.5, 1.0, 100, -10, 10);
    TH2I *h2_c1_c2 = new TH2I("h2_c1_c2", "c_{2} Vs. c_{1}; c_{1}; c_{2}", 100, 0.0, 0.35, 100, -10, 10);

    outputFile->cd();
    outputFile->mkdir("Fits");
    outputFile->cd("Fits");

    // Now we want to loop through all available module/layer/sector and try to make a fit of each one
    int ring = 1, straw = 1;
    while (ring <= 28){
        cout << "Entering Fit " << endl;
        char folder[100];
        sprintf(folder, "Ring %.2i", ring);
        char strawname[100];
        sprintf(strawname,"Straw %.3i Predicted Drift Distance Vs phi_DOCA", straw);
        TH2I *thisStrawHistogram = Get2DHistogram("CDC_Cosmic_Per_Straw",folder,strawname);

        if (thisStrawHistogram != NULL) {

            // Now to do our fits. This time we know there are 16 bins.
            double percentile95[16], percentile97[16], percentile99[16]; // Location of 95, 97,and 99th percentile bins
            double binCenter[16];
            char name[100];
            sprintf(name,"Ring %.2i Straw %.3i", ring, straw);
            TH1D *extractedPoints = new TH1D(name, name, 16, -3.14, 3.14);
            for (int i = 1; i <= thisStrawHistogram->GetNbinsX() ; i++){
                TH1D *projY = thisStrawHistogram->ProjectionY(" ", i, i);
                binCenter[i-1] = thisStrawHistogram->GetXaxis()->GetBinCenter(i);
                int nbins = projY->GetNbinsX();
                //Get the total nubmer of entries
                int nEntries = projY->GetEntries();
                if (nEntries == 0) continue;
                double errorFraction = TMath::Sqrt(nEntries) / nEntries;
                double perc95 = 0.95*nEntries, perc97 = 0.97 * nEntries, perc99 = 0.99 * nEntries;
                //Accumulate from the beginning to get total, mark 95, 97, 99% location
                int total = 0;
                for (int j = 0; j <= nbins; j++){
                    total += projY->GetBinContent(j);
                    if (total > perc99) percentile99[i-1] = projY->GetBinCenter(j);
                    else if (total > perc97) {
                        percentile97[i-1] = projY->GetBinCenter(j);
                        extractedPoints->SetBinContent(i, projY->GetBinCenter(j));
                        extractedPoints->SetBinError(i, errorFraction * projY->GetBinCenter(j));
                    }
                    else if (total > perc95) percentile95[i-1] = projY->GetBinCenter(j);
                }
            }
            f1->SetParameters(0.78, 0.0, 0.0);
            TFitResultPtr fr = extractedPoints->Fit(f1, "SR");
            Int_t fitStatus = fr;
            if (fitStatus == 0){
                double c0 = fr->Parameter(0);
                double c1 = fr->Parameter(1);
                double c2 = fr->Parameter(2);
                // Move c2 to fit on our range
                while (c2 > TMath::Pi()) c2 -= 2 * TMath::Pi();
                while (c2 < -1* TMath::Pi()) c2 += 2 * TMath::Pi();
                h1_c0->Fill(c0); h1_c1->Fill(c1); h1_c2->Fill(-1*c2); h1_c2_weighted->Fill(-1*c2,c1);
                h2_c0_c1->Fill(c0,c1); h2_c0_c2->Fill(c0,c2); h2_c1_c2->Fill(c1,c2);
                Amplitude_view[ring]->SetBinContent(straw,1,c1);
                Direction_view[ring]->SetBinContent(straw,1,-1*c2);
                Vertical_view[ring]->SetBinContent(straw,1,c1*TMath::Sin(-1*c2));
                Horizontal_view[ring]->SetBinContent(straw,1,c1*TMath::Cos(-1*c2));
                textFile << c1 << " " << c2 << endl;
            }
            else {
                cout << "WARNING: Fit Status "<< fitStatus << " for ring " << ring << " straw " << straw << endl;
                textFile << "0.0 0.0" << endl;
            }

        }
        else{
            textFile << "0.0 0.0" << endl;
        }

        // On to the next one
        straw++;
        if(straw > Nstraws[ring-1]){
            straw = 1;
            ring++;
        } 
    }

    outputFile->cd();
    outputFile->mkdir("2D");
    outputFile->cd("2D");

    TCanvas *c_Amplitude  = Plot2DCDC(Amplitude_view,"c_Amplitude", "Amplitude of Sinusoid", 0.0, 0.3);
    TCanvas *c_Direction  = Plot2DCDC(Direction_view,"c_Direction", "Direction of #delta", -3.14, 3.14);
    TCanvas *c_Vertical   = Plot2DCDC(Vertical_view,"c_Vertical", "Vertical Projection of Delta", -0.3, 0.3);
    TCanvas *c_Horizontal = Plot2DCDC(Horizontal_view,"c_Horizontal", "Horizontal Projection of Delta", -0.3, 0.3);

    c_Amplitude->Write();
    c_Direction->Write();
    c_Horizontal->Write();
    c_Vertical->Write();

    cout << "Closing Files..." << endl;
    outputFile->Write();
    thisFile->Close();
    textFile.close();
    return;
}
Exemplo n.º 8
0
void ReadTree_normDet(){

  bool testrun          = 0;
  const int norder_     = 2;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0; //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;

  TFile * fVNDet;
  TH1D * hVNDetX_0;
  TH1D * hVNDetY_0;
  TH1D * hVNDetX_1;
  TH1D * hVNDetY_1;
  TH1D * hVNDetX_full;
  TH1D * hVNDetY_full;

  TFile * fHists;
  TDirectory * qwebye;
  TH2D * hVn2Dfull[NCENT];
  TH2D * hVn2Dsub0[NCENT];
  TH2D * hVn2Dsub1[NCENT];
  TH2D * hVn2D0v1[NCENT];
  TH1D * hVnFull[NCENT];
  TH1D * hVnSub0[NCENT];
  TH1D * hVnSub1[NCENT];
  TH1I * Mult[NCENT];
  TH2D * h2Vn2D0v1[NCENT];
  TH1D * h2Vn2D0v1Magnitude[NCENT];

  double VnRaw_x_0;
  double VnRaw_y_0;
  double VnRaw_x_1;
  double VnRaw_y_1;
  double VnRaw_x_full;
  double VnRaw_y_full;

  double sumw_0;
  double sumw_1;
  double sumw_full;

  double VnCorrected_x_0;
  double VnCorrected_y_0;
  double VnCorrected_x_1;
  double VnCorrected_y_1;
  double VnCorrected_x_full;
  double VnCorrected_y_full;

  int evtMult_0;
  int evtMult_1;
  int evtMult_full;

  //
  // MAIN
  //
  setTDRStyle();
  TH1D::SetDefaultSumw2();
  TH2D::SetDefaultSumw2();
  TH1I::SetDefaultSumw2();

  //-- Set up analyzer objects
  fAna = new TFile(fAnaTreeName);

  tree   = (TTree *) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);

  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);

  //-- Set up VN detector objects 
  fVNDet = new TFile( Form("V%iDet.root", norder_ ) );
  hVNDetX_0    = (TH1D*) fVNDet->Get("SubEvt_0/hVNDetX_0");
  hVNDetY_0    = (TH1D*) fVNDet->Get("SubEvt_0/hVNDetY_0");
  hVNDetX_1    = (TH1D*) fVNDet->Get("SubEvt_1/hVNDetX_1");
  hVNDetY_1    = (TH1D*) fVNDet->Get("SubEvt_1/hVNDetY_1");
  hVNDetX_full = (TH1D*) fVNDet->Get("FullEvt/hVNDetX_full");
  hVNDetY_full = (TH1D*) fVNDet->Get("FullEvt/hVNDetY_full");

  //-- Setup the output objects
  fHists = new TFile("CastleEbyE.root","recreate");
  qwebye = (TDirectory*) fHists->mkdir("qwebye");

  for(int icent = 0; icent < NCENT; icent++){

    qwebye->cd();
    hVn2Dfull[icent]          = new TH2D(Form("hVn2Dfull_c%i", icent), Form("hVn2Dfull_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2Dfull[icent]->SetOption("colz");
    hVn2Dfull[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs}", norder_) );
    hVn2Dfull[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs}", norder_) );

    hVn2Dsub0[icent]          = new TH2D( Form("hVn2Dsub0_c%i", icent), Form("hVn2Dsub0_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2Dsub0[icent]->SetOption("colz");
    hVn2Dsub0[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a}", norder_) );
    hVn2Dsub0[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a}", norder_) );

    hVn2Dsub1[icent]          = new TH2D( Form("hVn2Dsub1_c%i", icent), Form("hVn2Dsub1_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2Dsub1[icent]->SetOption("colz");
    hVn2Dsub1[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,b}", norder_) );
    hVn2Dsub1[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,b}", norder_) );

    hVn2D0v1[icent]           = new TH2D( Form("hVn2D0v1_c%i", icent), Form("hVn2D0v1_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2D0v1[icent]->SetOption("colz");
    hVn2D0v1[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b}", norder_, norder_) );
    hVn2D0v1[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b}", norder_, norder_) );

    hVnFull[icent]            = new TH1D( Form("hVnFull_c%i", icent), Form("hVnFull_c%i", icent), NBins, 0., vnMax[norder_] );
    hVnFull[icent]->GetXaxis()->SetTitle( Form("v_{%i}", norder_) );
    hVnFull[icent]->GetYaxis()->SetTitle( "Events" );

    hVnSub0[icent]            = new TH1D( Form("hVnSub0_c%i", icent), Form("hVnSub0_c%i", icent), NBins, 0., vnMax[norder_] );
    hVnSub0[icent]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,a}", norder_) );

    hVnSub1[icent]            = new TH1D( Form("hVnSub1_c%i", icent), Form("hVnSub1_c%i", icent), NBins, 0., vnMax[norder_] );
    hVnSub1[icent]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,b}", norder_) );
    
    Mult[icent]               = new TH1I( Form("Mult_c%i", icent), Form("Mult_c%i", icent), 250, 1, 10000 );
    Mult[icent]->GetXaxis()->SetTitle("Multiplicity");
	
    h2Vn2D0v1[icent]          = new TH2D( Form("h2Vn2D0v1_c%i", icent), Form("h2Vn2D0v1_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    h2Vn2D0v1[icent]->GetXaxis()->SetTitle( Form("(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2", norder_, norder_) );
    h2Vn2D0v1[icent]->GetYaxis()->SetTitle( Form("(v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b})/2", norder_, norder_) );
    h2Vn2D0v1[icent]->SetOption("colz");

    h2Vn2D0v1Magnitude[icent] = new TH1D( Form("h2Vn2D0v1Magnitude_c%i", icent), Form("h2Vn2D0v1Magnitude_c%i", icent), NBins, 0., vnMax[norder_] );
    h2Vn2D0v1Magnitude[icent]->GetXaxis()->SetTitle( Form("|(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2|", norder_, norder_) );

  }
    
  //
  // Tree Loop
  //
    
  cout<<"Begin FINAL loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if( testrun ) N = 10000;
  else          N = tree->GetEntries();

  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout<<"Processing Event "<<ievent+1<<"\t"<<100.*(ievent+1)/(double)N<<"% Completed"<<endl;
      
    tree->GetEntry(ievent);

    //-- Vertex Cut
    if(TMath::Abs(vtx) < 3.0 || TMath::Abs(vtx) > 15.0) continue;

    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- Reset raw and sumw values
    VnRaw_x_0    = 0;
    VnRaw_y_0    = 0;
    VnRaw_x_1    = 0;
    VnRaw_y_1    = 0;
    VnRaw_x_full = 0;
    VnRaw_y_full = 0;                

    sumw_0       = 0;
    sumw_1       = 0;
    sumw_full    = 0;

    evtMult_0    = 0;
    evtMult_1    = 0;
    evtMult_full = 0;

    //-- Begin analyzer histogram loops
    for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
      for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){

	if(sumw->GetBinContent(ipt+1,ieta+1) !=0){

	  //-- Subevent 0 (eta >= 0)
	  if(etabinsDefault[ieta] >= 0){
	    VnRaw_x_0     += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VnRaw_y_0     += sumwqy->GetBinContent(ipt+1,ieta+1);
	    sumw_0        += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_0     += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Subevent 1 (eta < 0)
	  else{
	    VnRaw_x_1     += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VnRaw_y_1     += sumwqy->GetBinContent(ipt+1,ieta+1);
	    sumw_1        += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_1     += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Full Event
	  VnRaw_x_full    += sumwqx->GetBinContent(ipt+1,ieta+1);
	  VnRaw_y_full    += sumwqy->GetBinContent(ipt+1,ieta+1);
	  sumw_full       += sumw->GetBinContent(ipt+1,ieta+1);
	  evtMult_full    += hMult->GetBinContent(ipt+1,ieta+1);

	}

      } //-- End eta loop
    } //-- End pt loop

    //-- Fill Histograms, only use events that have at least two tracks in each SE
    if(sumw_0 == 0 || sumw_1 == 0 || evtMult_1 < 2 || evtMult_full < 2) continue;

    VnRaw_x_full /= sumw_full;
    VnRaw_y_full /= sumw_full;
    
    VnRaw_x_0 /= sumw_0;
    VnRaw_y_0 /= sumw_0;
	
    VnRaw_x_1 /= sumw_1;
    VnRaw_y_1 /= sumw_1;
                
    //-- Full Tracker
    VnCorrected_x_full = VnRaw_x_full - hVNDetX_full->GetBinContent(icent+1);
    VnCorrected_y_full = VnRaw_y_full - hVNDetY_full->GetBinContent(icent+1);
    double vn_full     = TMath::Sqrt( VnCorrected_x_full * VnCorrected_x_full +  VnCorrected_y_full * VnCorrected_y_full);

    hVnFull[icent]   -> Fill( vn_full );
    hVn2Dfull[icent] -> Fill(VnCorrected_x_full, VnCorrected_y_full);

    Mult[icent]->Fill(evtMult_full);

    //-- SubEvt 0 (Eta > 0)
    VnCorrected_x_0 = VnRaw_x_0 - hVNDetX_0->GetBinContent(icent+1);
    VnCorrected_y_0 = VnRaw_y_0 - hVNDetY_0->GetBinContent(icent+1);
    double vn_0     = TMath::Sqrt( VnCorrected_x_0 * VnCorrected_x_0 + VnCorrected_y_0 * VnCorrected_y_0 );

    hVnSub0[icent]   -> Fill( vn_0 );
    hVn2Dsub0[icent] -> Fill(VnCorrected_x_0, VnCorrected_y_0);
                
    //-- SubEvt 1 (Eta < 0)
    VnCorrected_x_1 = VnRaw_x_1 - hVNDetX_1->GetBinContent(icent+1);
    VnCorrected_y_1 = VnRaw_y_1 - hVNDetY_1->GetBinContent(icent+1);
    double vn_1     = TMath::Sqrt( VnCorrected_x_1 * VnCorrected_x_1 + VnCorrected_y_1 *VnCorrected_y_1 );

    hVnSub1[icent]   -> Fill( vn_1 );
    hVn2Dsub1[icent] -> Fill(VnCorrected_x_1, VnCorrected_y_1);

    //-- SubEvt Difference
    double vn0m1_x = VnCorrected_x_0 - VnCorrected_x_1;
    double vn0m1_y = VnCorrected_y_0 - VnCorrected_y_1;
    hVn2D0v1[icent]->Fill(vn0m1_x, vn0m1_y);	

    //-- SubEvt Difference for DD response
    double vn0m1_x2 = (VnCorrected_x_0 - VnCorrected_x_1) / 2.;
    double vn0m1_y2 = (VnCorrected_y_0 - VnCorrected_y_1) / 2.;
    h2Vn2D0v1[icent]->Fill(vn0m1_x2, vn0m1_y2);

    double vn0m12 = TMath::Sqrt( pow(vn0m1_x2, 2) + pow(vn0m1_y2, 2) );
    h2Vn2D0v1Magnitude[icent]->Fill(vn0m12);

  } //-- End Event loop

  cout<<"End FINAL loop!"<<endl;
        
  fHists->Write();
  cout<<"File written, process completed"<<endl;
   
}
Exemplo n.º 9
0
void ExtractTrackBasedTiming(int runNumber){

    TString fileName = Form ("Run%i/TrackBasedTiming.root", runNumber);
    TString prefix = Form ("Run%i/constants/TrackBasedTiming/",runNumber);
    TString inputPrefix = Form ("Run%i/constants/TDCADCTiming/",runNumber);

    thisFile = TFile::Open( fileName , "UPDATE");
    if (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;

    double sc_t_base_fadc;
    double sc_t_base_tdc;
    double tof_t_base_fadc;
    double tof_t_base_tdc;
    double bcal_t_base_fadc;
    double bcal_t_base_tdc;
    double tagm_t_base_fadc;
    double tagm_t_base_tdc;
    double tagh_t_base_fadc;
    double tagh_t_base_tdc;
    double fcal_t_base;
    double cdc_t_base;

    ifstream inFile;
    inFile.open(inputPrefix + "sc_tdc_timing_offsets.txt");
    string line;
    if (inFile.is_open()){
        while (getline (inFile, line)){
            sc_tdc_time_offsets.push_back(atof(line.data()));
        }
    }
    inFile.close();

    ifstream inFile;
    inFile.open(inputPrefix + "sc_adc_timing_offsets.txt");
    string line;
    if (inFile.is_open()){
        while (getline (inFile, line)){
            sc_fadc_time_offsets.push_back(atof(line.data()));
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tof_tdc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            tof_tdc_time_offsets.push_back(atof(line.data()));
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tof_adc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            tof_fadc_time_offsets.push_back(atof(line.data()));
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagm_tdc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double r, c, offset;
            while (iss>>r>>c>>offset){
                //if (row != 0) continue;
                tagm_tdc_time_offsets.push_back(offset);
            }
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagm_adc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double r, c, offset;
            while (iss>>r>>c>>offset){
                //if (row != 0) continue;
                tagm_fadc_time_offsets.push_back(offset);
            }
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagh_tdc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double counter, offset;
            while (iss>>counter>>offset){
                tagh_tdc_time_offsets.push_back(offset);
            }
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagh_adc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double counter, offset;
            while (iss>>counter>>offset){
                tagh_fadc_time_offsets.push_back(offset);
            }
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tof_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            iss>>tof_t_base_fadc>>tof_t_base_tdc;
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "sc_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            iss>>sc_t_base_fadc>>sc_t_base_tdc;
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "bcal_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double adc_offset, tdc_offset;
            iss>>adc_offset>>tdc_offset; // TDC not used currently
            bcal_t_base_fadc = adc_offset;
            bcal_t_base_tdc = tdc_offset;
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagm_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double adc_offset, tdc_offset;
            iss>>adc_offset>>tdc_offset; // TDC not used currently
            tagm_t_base_fadc = adc_offset;
            tagm_t_base_tdc = tdc_offset;
        }
    }

    inFile.close();
    inFile.open(inputPrefix + "tagh_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double adc_offset, tdc_offset;
            iss>>adc_offset>>tdc_offset; // TDC not used currently
            tagh_t_base_fadc = adc_offset;
            tagh_t_base_tdc = tdc_offset;
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "fcal_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            iss>>fcal_t_base; 
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "cdc_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            iss>>cdc_t_base; 
        }
    }
    inFile.close();


    // 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;
    double RF_Period = 4.0080161;
    TH1I *testHist = 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.
        useRF = true;
    }
    ofstream outFile;
    TH2I *thisHist; 
    thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGM - SC Target Time");
    if (useRF) thisHist = 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);
            }
        }
        /*
        if (!useRF){
            //TFitResultPtr fr1 = selectedTAGMOffset->Fit("pol1", "SQ", "", 0.5, nBinsX + 0.5);
            TFitResultPtr fr1 = selectedTAGMOffset->Fit("pol1", "SQ", "", 5, 50);

            for (int i = 1 ; i <= nBinsX; i++){
                double x0 = fr1->Parameter(0);
                double x1 = fr1->Parameter(1);
                //double x2 = fr1->Parameter(2);
                //double fitResult = x0 + i*x1 + i*i*x2;
                double fitResult = x0 + i*x1;

                double outlierCut = 20;
                double valueToUse = selectedTAGMOffset->GetBinContent(i);
                if (fabs(selectedTAGMOffset->GetBinContent(i) - fitResult) > outlierCut && valueToUse != 0.0){
                    valueToUse = fitResult;
                }

                selectedTAGMOffset->SetBinContent(i, valueToUse);
                if (valueToUse != 0 ) TAGMOffsetDistribution->Fill(valueToUse);
            }
        }
*/
        double meanOffset = TAGMOffsetDistribution->GetMean();
        // This might be in units of beam bunches, so we need to convert
        if (useRF) meanOffset *= RF_Period;
        /*
           for (int i = 1 ; i <= nBinsX; i++){
           double valueToUse = selectedTAGMOffset->GetBinContent(i);
           if (useRF) valueToUse *= RF_Period;
           if (valueToUse == 0) valueToUse = meanOffset;
           outFile.open(prefix + "tagm_tdc_timing_offsets.txt", ios::out | ios::app);
           outFile << "0 " << i << " " << valueToUse + tagm_tdc_time_offsets[i-1] - meanOffset<< endl;
           if (i == 7 || i == 25 || i == 79 || i == 97){
           for(int j = 1; j <= 5; j++){
           outFile << j << " " << i << " " << valueToUse + tagm_tdc_time_offsets[i-1] - meanOffset<< endl;
           }
           }
           outFile.close();
        // Apply the same shift to the adc offsets
        outFile.open(prefix + "tagm_adc_timing_offsets.txt", ios::out | ios::app);
        outFile << "0 " << i << " " << valueToUse + tagm_fadc_time_offsets[i-1] - meanOffset<< endl;
        if (i == 7 || i == 25 || i == 79 || i == 97){
        for(int j = 1; j <= 5; j++){
        outFile << j << " " << i << " " << valueToUse + tagm_fadc_time_offsets[i-1] - meanOffset<< endl;
        }
        }
        outFile.close();
        }
        */

        outFile.open(prefix + "tagm_adc_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_fadc_time_offsets[index-1] - meanOffset<< endl;
            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;
                }
            }
        }
        outFile.close();

        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 (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;
                }
            }
        }
        outFile.close();
        outFile.open(prefix + "tagm_base_time.txt", ios::out);
        outFile << tagm_t_base_fadc - meanOffset << " " << tagm_t_base_tdc - meanOffset << endl;
        outFile.close();

    }

    thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGH - SC Target Time");
    if (useRF) thisHist = 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

        int nBinsX = thisHist->GetNbinsX();
        int nBinsY = thisHist->GetNbinsY();
        TH1D * selectedTAGHOffset = new TH1D("selectedTAGHOffset", "Selected TAGH Offset; ID; Offset [ns]", nBinsX, 0.5, nBinsX + 0.5);
        TH1I * TAGHOffsetDistribution = new TH1I("TAGHOffsetDistribution", "TAGH Offset; TAGH 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 = 2; //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(useRF) {
                int beamBucket = int((maxMean / RF_Period) + 0.5); // +0.5 to handle rounding correctly
                selectedTAGHOffset->SetBinContent(i, beamBucket);
                TAGHOffsetDistribution->Fill(beamBucket);
            }
            else{
                selectedTAGHOffset->SetBinContent(i, maxMean);
            }
            /*
               outFile.open("tagh_tdc_timing_offsets.txt", ios::out | ios::app);
               outFile << i << " " << maxMean + tagh_tdc_time_offsets[i] << endl;
               outFile.close();
               outFile.open("tagh_adc_timing_offsets.txt", ios::out | ios::app);
               outFile << i << " " << maxMean + tagh_fadc_time_offsets[i] << endl;
               outFile.close();
               */
        }

        // Fit 1D histogram. If value is far from the fit use the fitted value
        // Two behaviors above and below microscope
        // This isn't working well, so removing...
        /*
           TFitResultPtr fr1 = selectedTAGHOffset->Fit("pol2", "SQ", "", 0.5, 131.5);
           TFitResultPtr fr2 = selectedTAGHOffset->Fit("pol2", "SQ", "", 182.5, 274.5);        

           for (int i = 1 ; i <= nBinsX; i++){
           double fitResult = 0.0;
           if (i < 150){
           double x0 = fr1->Parameter(0);
           double x1 = fr1->Parameter(1);
           double x2 = fr1->Parameter(2);
           fitResult = x0 + i*x1 + i*i*x2;
           }
           else{
           double x0 = fr2->Parameter(0);
           double x1 = fr2->Parameter(1);
           double x2 = fr2->Parameter(2);
           fitResult = x0 + i*x1 + i*i*x2;
           }

           double outlierCut = 7;
           double valueToUse = selectedTAGHOffset->GetBinContent(i);
           if (fabs(selectedTAGHOffset->GetBinContent(i) - fitResult) > outlierCut && valueToUse != 0.0){
           valueToUse = fitResult;
           }

           selectedTAGHOffset->SetBinContent(i, valueToUse);
           if(valueToUse != 0) TAGHOffsetDistribution->Fill(valueToUse);
           }
           */
        double meanOffset = TAGHOffsetDistribution->GetMean();
        if (useRF) meanOffset *= RF_Period;
        for (int i = 1 ; i <= nBinsX; i++){
            valueToUse = selectedTAGHOffset->GetBinContent(i);
            if (useRF) valueToUse *= RF_Period;
            if (valueToUse == 0) valueToUse = meanOffset;
            outFile.open(prefix + "tagh_tdc_timing_offsets.txt", ios::out | ios::app);
            outFile << i << " " << valueToUse + tagh_tdc_time_offsets[i-1] - meanOffset << endl;
            outFile.close();
            outFile.open(prefix + "tagh_adc_timing_offsets.txt", ios::out | ios::app);
            outFile << i << " " << valueToUse + tagh_fadc_time_offsets[i-1] - meanOffset << endl;
            outFile.close();
        }

        outFile.open(prefix + "tagh_base_time.txt", ios::out);
        outFile << tagh_t_base_fadc - meanOffset << " " << tagh_t_base_tdc - meanOffset << endl;
        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 = 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();
        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;
        }
        outFile.close();
        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;
        }
        outFile.close();
        
        outFile.open(prefix + "sc_base_time.txt");
        outFile << sc_t_base_fadc - meanSCOffset << " " << sc_t_base_tdc - meanSCOffset << endl;
        outFile.close();
    }

    TH1I *this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "TOF - SC Target 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");
        outFile << tof_t_base_fadc - mean - meanSCOffset<< " " << tof_t_base_tdc - mean - meanSCOffset<< endl;
        outFile.close();
    }

    this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "BCAL - SC Target 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");
        outFile << bcal_t_base_fadc - mean - meanSCOffset << " " << bcal_t_base_tdc - mean - meanSCOffset << endl; // TDC info not used
        outFile.close();
    }

    this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "FCAL - SC Target 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");
        outFile << fcal_t_base - mean - meanSCOffset<< endl; 
        outFile.close();
    }

    this1DHist = 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");
        outFile << cdc_t_base - mean - meanSCOffset << endl;
        outFile.close();
    }
    thisFile->Write();
    return;
    }
Exemplo n.º 10
0
int frameStack2_Mall(char* arg){
	//Take the arguments and save them into respective strings
	std::string infileName, outfileName0, outAllfileName0, outfileName1, outAllfileName1;
	std::string inF, outF0, outF1, outAll0, outAll1;
	std::string inPrefix, outPrefix;
	std::string runs, layers;
	std::string runCount;
	std::istringstream stm(arg);

	inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/rawRoot/";
	outPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/images/";

	outAll0 = "sliceXCuts_allLayers.png";
	outAllfileName0 = outPrefix + outAll0;
	std::cout << outAll0 << " created\n";
	outAll1 = "projYCuts_allLayers.png";
	outAllfileName1 = outPrefix + outAll1;
	std::cout << outAll1 << " created\n";

	const int width=480;	//width of the raw image
	const int height=640;	//height of the raw image
	
	TH2I *frameHistoAll = new TH2I("frameHistoAll","Stacked Frames After Edge Cuts",width/4,0,width,height/4,0,height);	//histogram for the stacked images
	TH1I *chamber1All = new TH1I("chamber1All","Chamber 1 After Edge Cuts",width/4,0,width);//histogram for chamber 1 (the top one)
	TH1I *chamber2All = new TH1I("chamber2All","Chamber 2 After Edge Cuts",width/4,0,width);//histogram for chamber 2
	TH1I *chamber3All = new TH1I("chamber3All","Chamber 3 After Edge Cuts",width/4,0,width);//histogram for chamber 3
	TH1I *chamber4All = new TH1I("chamber4All","Chamber 4 After Edge Cuts",width/4,0,width);//histogram for chamber 4 (the bottom one)

	TCanvas *projCAll = new TCanvas("projCAll","",0,0,800,600);
	TCanvas *pc2All = new TCanvas("pc2All", "Stack of 4 Layer Runs", 0, 0, 800, 600);
	
	while (true) {	
		if (std::getline(stm, layers, ' ')) {

			//create the output root file
			outF0 = "sliceXCuts_" + layers + "layers.png";
			outfileName0 = outPrefix + outF0;
			std::cout << outF0 << " created\n";
			outF1 = "projYCuts_" + layers + "layers.png";
			outfileName1 = outPrefix + outF1;
			std::cout << outF1 << " created\n";
			
			//load the input root files
			TChain *chain = new TChain("fourChamTree");

			for (int i=0; ; i++) {
				runCount = std::to_string(i);
				inF = "run" + runCount + "_" + layers + "layers.root";
				infileName = inPrefix + inF;
				ifstream fin;
				fin.open(infileName.c_str());
				if (!fin.fail()) {
					fin.close();
					chain->Add(infileName.c_str());
					std::cout << "Got " << inF << std::endl;
				} else break;
			}


			int x=-10;	//x from file
			int y=-10;	//y from file
			int intensity=-10;	//pixle intensity from file
			int pNum=0;//the order in which the frame was processed

			//the 2d array which will store each frame of image data.
			int frame[480][640]={0};

			//variables
			int UNIXtime=0;
			float tdc[2]={-10,-10};

			//TTree *T = new TTree("T","TTree of muplus data");
			//add the 'branches' to the tree we will now read in
			chain->SetBranchAddress("pNum",&pNum);	//branch for the frame number
			chain->SetBranchAddress("frame",&frame);	//branch for frame data


			TH2I *frameHisto = new TH2I("frameHisto","Stacked Frames After Edge Cuts",width/4,0,width,height/4,0,height);	//histogram for the stacked images
			TH1I *chamber1 = new TH1I("chamber1","Chamber 1 After Edge Cuts",width/4,0,width);//histogram for chamber 1 (the top one)
			TH1I *chamber2 = new TH1I("chamber2","Chamber 2 After Edge Cuts",width/4,0,width);//histogram for chamber 2
			TH1I *chamber3 = new TH1I("chamber3","Chamber 3 After Edge Cuts",width/4,0,width);//histogram for chamber 3
			TH1I *chamber4 = new TH1I("chamber4","Chamber 4 After Edge Cuts",width/4,0,width);//histogram for chamber 4 (the bottom one)

			//loop over all data in chain
			Int_t nevent = chain->GetEntries();	//get the number of entries in the TChain
			for (Int_t i=0;i<nevent;i++) {
				chain->GetEntry(i);
				for(int x=0;x<width;x++){
					for(int y=0;y<height;y++){
						if(frame[x][y]>0){
							frameHisto->Fill(x,y,frame[x][y]);
							frameHistoAll->Fill(x,y,frame[x][y]);
							if(y>580 && y<610){
								chamber1->Fill(x,frame[x][y]);
								chamber1All->Fill(x,frame[x][y]);
							}
							else if(y>400 && y<440){
								chamber2->Fill(x,frame[x][y]);
								chamber2All->Fill(x,frame[x][y]);
							}
							else if(y>240 && y<280){
								chamber3->Fill(x,frame[x][y]);
								chamber3All->Fill(x,frame[x][y]);
							}
							else if(y>50 && y<100){
								chamber4->Fill(x,frame[x][y]);
								chamber4All->Fill(x,frame[x][y]);
							}

						}

					}
				}
				cout << "Stacking frame number " << pNum << "\r";//this overwrites the line every time
			}
			cout << endl;

			//output the plot of the stacked images
			TCanvas *pc2 = new TCanvas("pc2","Stacked Frames",0,0,600,800);
			pc2->cd();
			frameHisto->SetStats(false);
			frameHisto->Draw("colz");
			frameHisto->GetXaxis()->SetTitle("X position (px)");
			//frameHisto->GetXaxis()->SetTitleSize(0.055);
			//frameHisto->GetXaxis()->SetTitleOffset(1.0);
			//frameHisto->GetXaxis()->SetLabelSize(0.055);
			frameHisto->GetXaxis()->CenterTitle();

			frameHisto->GetYaxis()->SetTitle("Y position (px)");
			//frameHisto->GetYaxis()->SetTitleSize(0.055);
			//frameHisto->GetYaxis()->SetTitleOffset(0.9);
			//frameHisto->GetYaxis()->SetLabelSize(0.055);
			frameHisto->GetYaxis()->CenterTitle();
			gPad->Update();
//			pc2->Print("chamberStack.png");//output to a graphics file 

			//plot the projection onto the Y axis (so we can find our cuts in Y to select each chamber)
			TCanvas *projC = new TCanvas("projC","",0,0,800,600);
			projC->cd();
			TH1D *ydist = frameHisto->ProjectionY("ydist");
			ydist->Draw();
			ydist->GetYaxis()->SetTitle("Entries");
			ydist->GetYaxis()->CenterTitle();

			TCanvas *sliceX = new TCanvas("sliceX","",0,0,800,600);

			sliceX->Divide(2,2);
			
			sliceX->cd(1);
			chamber1->Draw();
			chamber1->GetXaxis()->SetTitle("X position (px)");
			chamber1->GetXaxis()->CenterTitle();
			chamber1->GetYaxis()->SetTitle("Y position (px)");
			chamber1->GetYaxis()->CenterTitle();
		//	chamber1->GetYaxis()->SetMaxDigits(2);
			
			sliceX->cd(2);
			chamber2->Draw();
			chamber2->GetXaxis()->SetTitle("X position (px)");
			chamber2->GetXaxis()->CenterTitle();
			chamber2->GetYaxis()->SetTitle("Y position (px)");
			chamber2->GetYaxis()->CenterTitle();
		//	chamber2->GetYaxis()->SetMaxDigits(2);
			
			sliceX->cd(3);
			chamber3->Draw();
			chamber3->GetXaxis()->SetTitle("X position (px)");
			chamber3->GetXaxis()->CenterTitle();
			chamber3->GetYaxis()->SetTitle("Y position (px)");
			chamber3->GetYaxis()->CenterTitle();
		//	chamber3->GetYaxis()->SetMaxDigits(2);
			
			sliceX->cd(4);
			chamber4->Draw();
			chamber4->GetXaxis()->SetTitle("X position (px)");
			chamber4->GetXaxis()->CenterTitle();
			chamber4->GetYaxis()->SetTitle("Y position (px)");
			chamber4->GetYaxis()->CenterTitle();
		//	chamber4->GetYaxis()->SetMaxDigits(2);

			gPad->Update();
			
			projC->Print(outfileName1.c_str());
			sliceX->Print(outfileName0.c_str());

			frameHisto->Reset();	
			chamber1->Reset();
			chamber2->Reset();
			chamber3->Reset();
			chamber4->Reset();
		} else break;
	}
	
	projCAll->cd();
	TH1D *ydistAll = frameHistoAll->ProjectionY("ydist");
	ydistAll->Draw();
	ydistAll->GetYaxis()->SetTitle("Entries");
	ydistAll->GetYaxis()->CenterTitle();
	
	TCanvas *sliceXAll = new TCanvas("sliceXAll","",0,0,800,600);

	sliceXAll->Divide(2,2);
	
	sliceXAll->cd(1);
	chamber1All->Draw();
	chamber1All->GetXaxis()->SetTitle("X position (px)");
	chamber1All->GetXaxis()->CenterTitle();
	chamber1All->GetYaxis()->SetTitle("Y position (px)");
	chamber1All->GetYaxis()->CenterTitle();
//	chamber1->GetYaxis()->SetMaxDigits(2);
	
	sliceXAll->cd(2);
	chamber2All->Draw();
	chamber2All->GetXaxis()->SetTitle("X position (px)");
	chamber2All->GetXaxis()->CenterTitle();
	chamber2All->GetYaxis()->SetTitle("Y position (px)");
	chamber2All->GetYaxis()->CenterTitle();
//	chamber2->GetYaxis()->SetMaxDigits(2);
	
	sliceXAll->cd(3);
	chamber3All->Draw();
	chamber3All->GetXaxis()->SetTitle("X position (px)");
	chamber3All->GetXaxis()->CenterTitle();
	chamber3All->GetYaxis()->SetTitle("Y position (px)");
	chamber3All->GetYaxis()->CenterTitle();
//	chamber3->GetYaxis()->SetMaxDigits(2);
	
	sliceXAll->cd(4);
	chamber4All->Draw();
	chamber4All->GetXaxis()->SetTitle("X position (px)");
	chamber4All->GetXaxis()->CenterTitle();
	chamber4All->GetYaxis()->SetTitle("Y position (px)");
	chamber4All->GetYaxis()->CenterTitle();
//	chamber4->GetYaxis()->SetMaxDigits(2);

	gPad->Update();
	
	projCAll->Print(outAllfileName1.c_str());
	sliceXAll->Print(outAllfileName0.c_str());
	
	pc2All->cd();
	frameHistoAll->SetStats(false);
	frameHistoAll->Draw("colz");
	frameHistoAll->GetXaxis()->SetTitle("X position (px)");
	//frameHisto->GetXaxis()->SetTitleSize(0.055);
	//frameHisto->GetXaxis()->SetTitleOffset(1.0);
	//frameHisto->GetXaxis()->SetLabelSize(0.055);
	frameHistoAll->GetXaxis()->CenterTitle();

	frameHistoAll->GetYaxis()->SetTitle("Y position (px)");
	//frameHisto->GetYaxis()->SetTitleSize(0.055);
	//frameHisto->GetYaxis()->SetTitleOffset(0.9);
	//frameHisto->GetYaxis()->SetLabelSize(0.055);
	frameHistoAll->GetYaxis()->CenterTitle();
	gPad->Update();

	return 0;  
}
void plot_pad_size_in_layer(TString digiPar="trd.v13/trd_v13g.digi.par", Int_t nlines=1, Int_t nrows_in_sec=0, Int_t alllayers=1) 
{

  gStyle->SetPalette(1,0);
  gROOT->SetStyle("Plain");
  gStyle->SetPadTickX(1);                        
  gStyle->SetPadTickY(1); 
  gStyle->SetOptStat(kFALSE);
  gStyle->SetOptTitle(kFALSE);

  Bool_t read = false;
  TH2I *fLayerDummy = new TH2I("LayerDummy","",1200,-600,600,1000,-500,500);
  fLayerDummy->SetXTitle("x-coordinate [cm]");
  fLayerDummy->SetYTitle("y-coordinate [cm]");
  fLayerDummy->GetXaxis()->SetLabelSize(0.02);
  fLayerDummy->GetYaxis()->SetLabelSize(0.02);
  fLayerDummy->GetZaxis()->SetLabelSize(0.02);
  fLayerDummy->GetXaxis()->SetTitleSize(0.02);
  fLayerDummy->GetXaxis()->SetTitleOffset(1.5);
  fLayerDummy->GetYaxis()->SetTitleSize(0.02);
  fLayerDummy->GetYaxis()->SetTitleOffset(2);
  fLayerDummy->GetZaxis()->SetTitleSize(0.02);
  fLayerDummy->GetZaxis()->SetTitleOffset(-2);

  TString title;
  TString title1, title2, title3;
  TString buffer;
  TString firstModule = "";
  Int_t blockCounter(0), startCounter(0); // , stopCounter(0);
  Double_t msX(0), msY(0), mpX(0), mpY(0), mpZ(0), psX(0), psY(0);
  Double_t ps1X(0), ps1Y(0), ps2X(0), ps2Y(0), ps3X(0), ps3Y(0);
  Int_t modId(0), layerId(0);
  Double_t sec1(0), sec2(0), sec3(0);
  Double_t row1(0), row2(0), row3(0);
  std::map<float, TCanvas*> layerView;// map key is z-position of modules
  std::map<float, TCanvas*>::iterator it;
  ifstream digipar;

  digipar.open(digiPar.Data(), ifstream::in);
  while (digipar.good()) {
    digipar >> buffer;
    //cout << "(" << blockCounter << ")    " << buffer << endl;
    if (blockCounter == 19)
      firstModule = buffer;
    if (buffer == (firstModule + ":")){
      //cout << buffer << " <===========================================" << endl;
      read = true;
    }
    if (read) {
      startCounter++;
      if (startCounter == 1)   // position of module position in x
      {
	modId = buffer.Atoi();
        layerId = (modId & (15 << 4)) >> 4;  // from CbmTrdAddress.h
      }

      if (startCounter == 5)   // position of module position in x
	mpX = buffer.Atof();
      if (startCounter == 6)   // position of module position in y
	mpY = buffer.Atof();
      if (startCounter == 7)   // position of module position in z
	mpZ = buffer.Atof();
      if (startCounter == 8)   // position of module size in x
	msX = buffer.Atof();
      if (startCounter == 9)   // position of module size in y
	msY = buffer.Atof();

      if (startCounter == 12)   // sector 1 size in y
	sec1 = buffer.Atof();
      if (startCounter == 13)   // position of pad size in x - do not take the backslash (@14)
	ps1X = buffer.Atof();
      if (startCounter == 15)   // position of pad size in y
	ps1Y = buffer.Atof();

      if (startCounter == 17)   // sector 2 size in y
	sec2 = buffer.Atof();
      if (startCounter == 18)   // position of pad size in x
      {
	ps2X = buffer.Atof();
        psX = ps2X;   // for backwards compatibility - sector 2 is default sector
      }
      if (startCounter == 19)   // position of pad size in y
      {
	ps2Y = buffer.Atof();
        psY = ps2Y;   // for backwards compatibility - sector 2 is default sector
      }

      if (startCounter == 21)   // sector 3 size in y
	sec3 = buffer.Atof();
      if (startCounter == 22)   // position of pad size in x
	ps3X = buffer.Atof();
      if (startCounter == 23)   // position of pad size in y
	ps3Y = buffer.Atof();

//      if (startCounter == 23)   // last element
//      {
//        printf("moduleId         : %d, %d\n", modId, layerId);
//        printf("pad size sector 1: (%.2f cm, %.2f cm) pad area: %.2f cm2\n", ps1X, ps1Y, ps1X*ps1Y);
//        printf("pad size sector 2: (%.2f cm, %.2f cm) pad area: %.2f cm2\n", ps2X, ps2Y, ps2X*ps2Y);
//        printf("pad size sector 3: (%.2f cm, %.2f cm) pad area: %.2f cm2\n", ps3X, ps3Y, ps3X*ps3Y);
//        printf("rows per sector  : %.1f %.1f %.1f\n", sec1/ps1Y, sec2/ps2Y, sec3/ps3Y);
//        printf("\n");
//      }

      //printf("module position: (%.1f, %.1f, %.1f) module size: (%.1f, %.1f) pad size: (%.2f, %.2f) pad area: %.2f\n",mpX,mpY,mpZ,2*msX,2*msY,psX,psY,psX*psY);

      if (startCounter == 23) { // if last element is reached
	startCounter = 0; // reset

        if ( alllayers == 0 )   
          if ( !((layerId == 0) || (layerId == 4) || (layerId == 8)) )   // plot only 1 layer per station
            continue;

        row1 = sec1 / ps1Y;
        row2 = sec2 / ps2Y;
        row3 = sec3 / ps3Y;

	it = layerView.find(mpZ);
	if (it == layerView.end()){	
	  //	  title.Form("pad_size_layer_at_z_%.2fm",mpZ);  
	  title.Form("%02d_pad_size_layer%02d", layerId, layerId);  
	  layerView[mpZ] = new TCanvas(title,title,1200,1000);
	  fLayerDummy->DrawCopy("");

        // now print cm2 in the center
	layerView[mpZ]->cd();
	title.Form("cm^{2}");  // print cm2
	TPaveText *text = new TPaveText(0 - 28.5,
					0 - 28.5,
					0 + 28.5,
					0 + 28.5
					);
	text->SetFillStyle(1001);
	text->SetLineColor(1);
        text->SetFillColor(kWhite);
	text->AddText(title);
	text->Draw("same");
	}

        // print pad size in each module
	layerView[mpZ]->cd();
	//	title.Form("%2.0fcm^{2}",psX*psY);  // print pad size
	//	title.Form("%.0f",psX*psY);  // print pad size - 1 digit
	TPaveText *text = new TPaveText(mpX - msX,
					mpY - msY,
					mpX + msX,
					mpY + msY
					);
	text->SetFillStyle(1001);
	text->SetLineColor(1);
	//        text->SetFillColor(kViolet);

	// vary background color
//        if ((int)(psX*psY+.5) == 2)
//        {
//          text->SetFillColor(kOrange + 9);
//        } 
//        else 
        if (psX*psY <= 1.1)
        {
          text->SetFillColor(kOrange + 10);
        }
        else if (psX*psY <= 2.1)
        {
          text->SetFillColor(kOrange -  3);
        }
        else if (psX*psY <= 3.1)
        {
          text->SetFillColor(kOrange -  4);
        }
        else if (psX*psY <= 5)
        {
          text->SetFillColor(kOrange + 10 - ((int)(psX*psY+.5)-1) * 2);
//        printf("%2.1f: %d\n", psX*psY, 10 - ((int)(psX*psY+.5)-1) * 2);
        } 
        else if (psX*psY <= 10)
	{
          text->SetFillColor(kSpring + 10 - ((int)(psX*psY+.5)-4) * 2);
//        printf("%2.1f: %d\n", psX*psY, 10 - ((int)(psX*psY+.5)-4) * 2);
        } 
        else if (psX*psY > 10)
	{
          text->SetFillColor(kGreen);
//        printf("%2.1f: %s\n", psX*psY, "green");
        } 

        if (nrows_in_sec == 1)   // print number of rows in sector
	{
   	  title1.Form("%3.1f - %2.0f", ps1X*ps1Y, row1);  // print pad size and nrows - 2 digits - sector 1
	  title2.Form("%3.1f - %2.0f", ps2X*ps2Y, row2);  // print pad size and nrows - 2 digits - sector 2
	  title3.Form("%3.1f - %2.0f", ps3X*ps3Y, row3);  // print pad size and nrows - 2 digits - sector 3
	}
        else
	{
   	  title1.Form("%3.1f",ps1X*ps1Y);  // print pad size - 2 digits - sector 1
	  title2.Form("%3.1f",ps2X*ps2Y);  // print pad size - 2 digits - sector 2
	  title3.Form("%3.1f",ps3X*ps3Y);  // print pad size - 2 digits - sector 3
	}

        if (nlines==1)   // plot pad size for central sector only
	{
	  text->AddText(title2);
        }
        else   // plot pad size for all 3 sectors
	{
	  text->AddText(title1);
	  text->AddText(title2);
	  text->AddText(title3);
        }
	text->Draw("same");
	//layerView[mpZ]->Update();
      }
    }  
    blockCounter++;
  }
Exemplo n.º 12
0
void makeVNDet(){

  bool testrun          = 0;
  const int norder_     = 2;
  const double vtxCut   = 15.;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0;  //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;

  TFile * fSplit;
  TTree * treeSplit;
  int iSplit;

  TFile * fOut;

  TH1D * hVNDetX_0[NSPLIT];
  TH1D * hVNDetY_0[NSPLIT];
  TH1D * hVNDetX_1[NSPLIT];
  TH1D * hVNDetY_1[NSPLIT];
  TH1D * hVNDetX_full[NSPLIT];
  TH1D * hVNDetY_full[NSPLIT];

  double VNDetX_0[NCENT][NSPLIT];
  double VNDetY_0[NCENT][NSPLIT];
  double VNDetX_1[NCENT][NSPLIT];
  double VNDetY_1[NCENT][NSPLIT];
  double VNDetX_full[NCENT][NSPLIT];
  double VNDetY_full[NCENT][NSPLIT];

  int Nevents[NCENT][NSPLIT];
  int NFails[NCENT][NSPLIT];

  //
  // MAIN
  //


  //-- Set up the analyzer objects
  fAna = new TFile("/rfs/jcastle/PbPb2015/PixelTracking_MB2/EbyETree_pixel_noTeff.root");

  tree = (TTree*) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
    
  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);

  //-- Set up the file splitter
  fSplit = new TFile(fileSplit);
  treeSplit = (TTree*) fSplit->Get("SplitTree");
  treeSplit->SetBranchAddress("iSplit", &iSplit);

  //-- Setup the output objects
  fOut     = new TFile( Form("V%iDet.root", norder_), "recreate" );
  for(int iS = 0; iS < NSPLIT; iS++){
    fOut->cd();
    hVNDetX_0[iS]    = new TH1D( Form("hVNDetX_0_Split%i", iS),    Form("hVNDetX_0_Split%i", iS),    NCENT, centbinsDefault);
    hVNDetX_0[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetY_0[iS]    = new TH1D( Form("hVNDetY_0_Split%i", iS),    Form("hVNDetY_0_Split%i", iS),    NCENT, centbinsDefault);
    hVNDetY_0[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetX_1[iS]    = new TH1D( Form("hVNDetX_1_Split%i", iS),    Form("hVNDetX_1_Split%i", iS),    NCENT, centbinsDefault);
    hVNDetX_1[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetY_1[iS]    = new TH1D( Form("hVNDetY_1_Split%i", iS),    Form("hVNDetY_1_Split%i", iS),    NCENT, centbinsDefault);
    hVNDetY_1[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetX_full[iS] = new TH1D( Form("hVNDetX_full_Split%i", iS), Form("hVNDetX_full_Split%i", iS), NCENT, centbinsDefault);
    hVNDetX_full[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetY_full[iS] = new TH1D( Form("hVNDetY_full_Split%i", iS), Form("hVNDetY_full_Split%i", iS), NCENT, centbinsDefault);
    hVNDetY_full[iS]->GetXaxis()->SetTitle("Centrality %");
  }    

  //-- initialize all variables
  for(int icent = 0; icent<NCENT; icent++){
    for(int iS = 0; iS < NSPLIT; iS++){

      VNDetX_0[icent][iS]     = 0.;
      VNDetY_0[icent][iS]     = 0.;
      VNDetX_1[icent][iS]     = 0.;
      VNDetY_1[icent][iS]     = 0.;
      VNDetX_full[icent][iS]  = 0.;
      VNDetY_full[icent][iS]  = 0.;

      Nevents[icent][iS]      = 0;
      NFails[icent][iS]       = 0;

    }
  }
    
  //
  // Calculate Vn_det
  //
    
  cout<<"Begin DETECTOR loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if(testrun) N = 10000; 
  else        N = tree->GetEntries();

  //-- Begin event loop
  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout << "Processing Event " << ievent+1 << "\t" << (100.*(ievent+1)/N) << "% Completed" << endl;
        
    int itree = tree->GetEntry(ievent);
    if(itree < 0){
      std::cout<<"!!! BAD EVENT !!!"<<std::endl;
      continue;
    }

    treeSplit->GetEntry(ievent);

    //-- Vertex Cut
    if(TMath::Abs(vtx) > vtxCut) continue;
      
    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = (centval - cent_min[0]) / centBinWidth;

    //-- Reset Raw and sumw values
    double VNRawX_0     = 0.;
    double VNRawY_0     = 0.;
    double VNRawX_1     = 0.;
    double VNRawY_1     = 0.;
    double VNRawX_full  = 0.;
    double VNRawY_full  = 0.;            
	
    double sumw_0       = 0.;
    double sumw_1       = 0.;
    double sumw_full    = 0.;
      
    double evtMult_0    = 0;
    double evtMult_1    = 0;
    double evtMult_full = 0;
      
    Nevents[icent][iSplit]++;

    //-- Begin analyzer histogram loops
    for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
      for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){
	  
	if(sumw->GetBinContent(ipt+1,ieta+1) !=0){
	    
	  //-- Subevent 0 (eta >= 0)
	  if(etabinsDefault[ieta] >= 0){
	    VNRawX_0   += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VNRawY_0   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	    sumw_0     += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_0  += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Subevent 1 (eta < 0)
	  else{
	    VNRawX_1   += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VNRawY_1   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	    sumw_1     += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_1  += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Full Event
	  VNRawX_full  += sumwqx->GetBinContent(ipt+1,ieta+1);
	  VNRawY_full  += sumwqy->GetBinContent(ipt+1,ieta+1);
	    
	  sumw_full    += sumw->GetBinContent(ipt+1,ieta+1);
	  evtMult_full += hMult->GetBinContent(ipt+1,ieta+1);
	}
	  
      } //-- End eta loop
      
    } //-- End pt loop
    
    //-- Only use events that have tracks in all subevents AND subevents that have at least two tracks to determine VN
    if( sumw_0 == 0 || sumw_1 == 0 || evtMult_0 < 2 || evtMult_1 < 2 ){
	NFails[icent][iSplit]++;
    }
    else{      
      VNDetX_0[icent][iSplit]    += VNRawX_0    / sumw_0;
      VNDetY_0[icent][iSplit]    += VNRawY_0    / sumw_0;
      VNDetX_1[icent][iSplit]    += VNRawX_1    / sumw_1;
      VNDetY_1[icent][iSplit]    += VNRawY_1    / sumw_1;
      VNDetX_full[icent][iSplit] += VNRawX_full / sumw_full;
      VNDetY_full[icent][iSplit] += VNRawY_full / sumw_full;
    }

  } //-- End event loop
    
  std::cout<<"End DETECTOR loop"<<std::endl;

  //-- Average VNDet over all events for each centrality, EP and, qn bin
  for(int icent = 0; icent < NCENT; icent++){
    for(int iS = 0; iS < NSPLIT; iS++){
   
      double  Neffective = (double) Nevents[icent][iS] - (double) NFails[icent][iS];
      if( Neffective == 0 ) continue;
    
      VNDetX_0[icent][iS]    /= Neffective;
      VNDetY_0[icent][iS]    /= Neffective;
      VNDetX_1[icent][iS]    /= Neffective;
      VNDetY_1[icent][iS]    /= Neffective;
      VNDetX_full[icent][iS] /= Neffective;
      VNDetY_full[icent][iS] /= Neffective;

      //-- Populate histograms that will be used by ReadTree_normDet.C
      hVNDetX_0[iS]    -> SetBinContent(icent+1, VNDetX_0[icent][iS]);
      hVNDetX_1[iS]    -> SetBinContent(icent+1, VNDetX_1[icent][iS]);
      hVNDetX_full[iS] -> SetBinContent(icent+1, VNDetX_full[icent][iS]);
      
      hVNDetY_0[iS]    -> SetBinContent(icent+1, VNDetY_0[icent][iS]);
      hVNDetY_1[iS]    -> SetBinContent(icent+1, VNDetY_1[icent][iS]);
      hVNDetY_full[iS] -> SetBinContent(icent+1, VNDetY_full[icent][iS]);

    }
  }
  fOut->Write();
  cout<<"File written, process completed"<<endl;

}
Exemplo n.º 13
0
void makePUM0Table()
{
  const TString l1_input = "/mnt/hadoop/cms/store/user/luck/L1Emulator/minbiasHIanalyzer_withregions.root";
  TFile *lFile = TFile::Open(l1_input);
  TTree *l1Tree = (TTree*)lFile->Get("L1UpgradeAnalyzer/L1UpgradeTree");

  Int_t l1_event, l1_run;
  Int_t l1_num;
  Int_t region_hwPt[NREG], region_hwEta[NREG], region_hwPhi[NREG], region_tauVeto[NREG];

  l1Tree->SetBranchAddress("event",&l1_event);
  l1Tree->SetBranchAddress("run",&l1_run);
  l1Tree->SetBranchAddress("nRegions",&l1_num);
  l1Tree->SetBranchAddress("region_hwPt",region_hwPt);
  l1Tree->SetBranchAddress("region_hwEta",region_hwEta);
  l1Tree->SetBranchAddress("region_hwPhi",region_hwPhi);
  l1Tree->SetBranchAddress("region_tauVeto",region_tauVeto);

  const TString forest_input = "/mnt/hadoop/cms/store/user/luck/L1Emulator/minbiasForest_merged_v2/HiForest_PbPb_Data_minbias_fromSkim.root";
  TFile *fFile = TFile::Open(forest_input);
  TTree *fEvtTree = (TTree*)fFile->Get("hiEvtAnalyzer/HiTree");
  TTree *fSkimTree = (TTree*)fFile->Get("skimanalysis/HltTree");

  Int_t f_evt, f_run, f_lumi;
  Int_t hiBin;
  fEvtTree->SetBranchAddress("evt",&f_evt);
  fEvtTree->SetBranchAddress("run",&f_run);
  fEvtTree->SetBranchAddress("lumi",&f_lumi);
  fEvtTree->SetBranchAddress("hiBin",&hiBin);

  Int_t pcollisionEventSelection, pHBHENoiseFilter;
  fSkimTree->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection);
  fSkimTree->SetBranchAddress("pHBHENoiseFilter",&pHBHENoiseFilter);

  TFile *outFile = new TFile("HI_PUM0_evtsel_out.root","RECREATE");

  std::map<Long64_t, Long64_t> kmap;

  // choose loop over l1 tree first (smaller)
  //std::cout << "Begin making map." << std::endl;
  Long64_t l_entries = l1Tree->GetEntries();
  for(Long64_t j = 0; j < l_entries; ++j)
  {
    l1Tree->GetEntry(j);
    Long64_t key = makeKey(l1_run, l1_event);

    std::pair<Long64_t,Long64_t> p(key,j);
    kmap.insert(p);
  }
  //std::cout << "Finished making map." << std::endl;

  outFile->cd();

  TH1I *hists[22][18]; // [eta][pu bin], arbitrary value of 18 for # bins in pu
  for(int i = 0; i < 22; ++i)
    for(int j = 0; j < 18; ++j)
    {
      hists[i][j] = new TH1I(Form("hist_%d_%d",i,j),"", 1024,0,1024);
    }

  TH2I *centPUM = new TH2I("cenPUM","",200,0,200,396,0,396);
  int count = 0;

  Long64_t entries = fEvtTree->GetEntries();
  for(Long64_t j = 0; j < entries; ++j)
  {
    //if(j % 10000 == 0)
    //  printf("%lld / %lld\n",j,entries);

    fEvtTree->GetEntry(j);
    Long64_t key = makeKey(f_run, f_evt);

    std::map<Long64_t,Long64_t>::const_iterator got = kmap.find(key);
    if(got == kmap.end() ) {
      continue;
    } else {
      l1Tree->GetEntry(got->second);
      kmap.erase(key);
      count++;

      fSkimTree->GetEntry(j);
      if((pcollisionEventSelection == 1) && (pHBHENoiseFilter == 1))
      {

	//int pubin = (int) ( (double)hiBin * (18.0/200.0));
	int PUM0 = 0;
	for(int i = 0; i < NREG; ++i)
	{
	  if(region_hwPt[i] > 0)
	    ++PUM0;
	}
	int pubin = PUM0/22;
	if(pubin == 18) pubin = 17; //special case for every region firing
	for(int i = 0; i < NREG; ++i)
	{
	  hists[region_hwEta[i]][pubin]->Fill(region_hwPt[i]);
	}
	centPUM->Fill(hiBin,PUM0);

      }
    }
  }

  std::cout << "cms.vdouble(";
  TH1D *hists_eta[22];
  for(int i = 0; i < 22; ++i)
  {
    hists_eta[i] = new TH1D(Form("hists_eta_%d",i),"",18,0,17);
    for(int j = 0; j < 18; ++j)
    {
      double Mean = hists[i][j]->GetMean();
      double MeanError = hists[i][j]->GetMeanError();
      hists_eta[i]->SetBinContent(j,Mean);
      hists_eta[i]->SetBinError(j,MeanError);
      std::cout << Mean*0.5;
      if(!((i == 21) && (j == 17))) std::cout << ", ";
    }
  }
  std::cout << ")" << std::endl;

  for(int i = 0; i < 22; ++i)
  {
    hists_eta[i]->Write();
    for(int j = 0; j < 18; ++j)
    {
      hists[i][j]->Write();
    }
  }
  centPUM->Write();


  //std::cout << "Matching entries: " << count << std::endl;

  lFile->Close();
  fFile->Close();
  outFile->Close();
}
Exemplo n.º 14
0
void* Monitoring::MonitorThread(void* arg){
  
  //std::cout<<"d1"<<std::endl;
  monitor_thread_args* args= static_cast<monitor_thread_args*>(arg);  

  std::string outpath=args->outputpath;
  zmq::socket_t Ireceive (*(args->context), ZMQ_PAIR);
  Ireceive.connect("inproc://MonitorThread");
  
  //  std::vector<CardData*> carddata;

  std::map<int,std::vector<TH1F> > PedTime;
  std::map<int,std::vector<TH1F> > PedRMSTime;
  std::vector<TH1F> rates;
  std::vector<TH1F> averagesize;

  std::vector<TH1I> tfreqplots;
  std::map<int,std::vector<std::vector<float > > > pedpars;
  TCanvas c1("c1","c1",600,400);
  
  
  bool running=true;
  bool init=true;    

  std::vector<PMT> PMTInfo;
  /////////////////// Connect to sql ///////////////////////
//std::cout<<"d2"<<std::endl;

  pqxx::connection *C;
  std::stringstream tmp;
  tmp<<"dbname=annie"<<" hostaddr=127.0.0.1"<<" port=5432" ;
  C=new pqxx::connection(tmp.str().c_str());
  if (C->is_open()) {
    // std::cout << "Opened database successfully: " << C->dbname() << std::endl;
  }
  else {
    std::cout << "Can't open database" << std::endl;
    return false;
  }

  tmp.str("");

  pqxx::nontransaction N(*C);

  tmp<<"select gx,gy,gz,vmecard,vmechannel from pmtconnections order by channel; ";


  /* Execute SQL query */
  pqxx::result R( N.exec( tmp.str().c_str() ));

  //pqxx::result::const_iterator c = R.begin();


  ///////// Fill PMT Info//////////////// 
  for ( pqxx::result::const_iterator c = R.begin(); c != R.end(); ++c) {

    PMT tmp;
    tmp.gx= c[0].as<int>();
    tmp.gy= c[1].as<int>();
    tmp.gz= c[2].as<int>();
    tmp.card= c[3].as<int>();
    tmp.channel= c[4].as<int>()-1;
    PMTInfo.push_back(tmp);
  }

//std::cout<<"d3"<<std::endl;

  
  while (running){
    //std::cout<<"d4"<<std::endl;

    
    zmq::message_t comm;
    Ireceive.recv(&comm);
	
    std::istringstream iss(static_cast<char*>(comm.data()));
    std::string arg1="";
    iss>>arg1;

    //std::cout<<"d5"<<std::endl;
    

    if(arg1=="Data"){

      ////////// Setting up plots/////////
      std::vector<TGraph2D*> mg;
      TH2I EventDisplay ("Event Display", "Event Display", 10, -1, 8, 10, -1, 8);
      TH2I RMSDisplay ("RMS Display", "RMS Display", 10, -1, 8, 10, -1, 8);
      std::vector<TH1F> temporalplots;
      std::vector<TH1I> freqplots;
      CardData* carddata;
      int size=0;
      iss>>size;  
      
      //freqplots.clear();
  //std::cout<<"d6"<<std::endl;
  
      for(int i=0;i<size;i++){
	//std::cout<<"d7"<<std::endl;

	long long unsigned int pointer;
	iss>>std::hex>>pointer;
	
	carddata=(reinterpret_cast<CardData *>(pointer));
	
	if(init){ ////make initial freq  plot and ped vector ped time and ped rms////
	  for(int j=0;j<carddata->channels;j++){
	    std::stringstream tmp;
	    tmp<<"Channel "<<(i*4)+j<<" frequency";
	    TH1I tmpfreq(tmp.str().c_str(),tmp.str().c_str(),10,0,9);
	    tfreqplots.push_back(tmpfreq);

	    tmp.str("");
	    tmp<<"Channel "<<(i*4)+j<<" Pedistal";
	    TH1F tmppedtime(tmp.str().c_str(),tmp.str().c_str(),100,0,99);
	    PedTime[carddata->CardID].push_back(tmppedtime);

	    tmp.str("");
	    tmp<<"Channel "<<(i*4)+j<<" Pedistal RMS";
	    TH1F tmppedrmstime(tmp.str().c_str(),tmp.str().c_str(),100,0,99);
	    PedRMSTime[carddata->CardID].push_back(tmppedrmstime);
	    std::vector<float> tmppedpars;
	    tmppedpars.push_back(0);
	    tmppedpars.push_back(0);
	    pedpars[carddata->CardID].push_back(tmppedpars);
	  }
	  if(i==size-1)init=false;
	}

	//std::cout<<"d8"<<std::endl;

	//	std::cout<<"d1"<<std::endl;

	///////Make temporal plot //////////
	for(int j=0;j<carddata->channels;j++){
	  std::stringstream tmp;
	  tmp<<"Channel "<<(i*4)+j<<" temporal";
	  
	  TH1F temporal(tmp.str().c_str(),tmp.str().c_str(),carddata->buffersize,0,carddata->buffersize-1);
	  long sum=0;

	  //////////Make freq plot///////////////
	  tmp.str("");
	  tmp<<"Channel "<<(i*4)+j<<" frequency";
	  TH1I freq(tmp.str().c_str(),tmp.str().c_str(),200,200,399);

	
	  //  std::cout<<"d2"<<std::endl;

	  //std::cout<<"d9"<<std::endl;

	
	  ///// Calculate sum for event dispkay and fill freq plots /////////


	for(int k=0;k<carddata->buffersize;k++){
	  //std::cout<<"d10"<<std::endl;

	  //	  std::cout<<"i="<<i<<" j="<<j<<std::endl;
	  //std::cout<<"d2.5 "<<(i*4)+j<<" feqplot.size = "<<freqplots.size()<<std::endl;
	  if(carddata->Data[(j*carddata->buffersize)+k]>pedpars[carddata->CardID].at(j).at(0)+(pedpars[carddata->CardID].at(j).at(1)*5))sum+=carddata->Data[(j*carddata->buffersize)+k];  
	  freq.Fill(carddata->Data[(j*carddata->buffersize)+k]);

	  //temporal.SetBinContent(k,carddata->Data[(j*carddata->buffersize)+k]);	      
	}

	freqplots.push_back(freq);
	//////// find pedistall fill ped temporals//////////
	freq.Fit("gaus");
	TF1 *gaus = freq.GetFunction("gaus");
        pedpars[carddata->CardID].at(j).at(0)=(gaus->GetParameter(1));
        pedpars[carddata->CardID].at(j).at(1)=(gaus->GetParameter(2));
	gaus->SetLineColor(j+1);
       
	//std::cout<<"d11"<<std::endl;

	for(int bin=99;bin>0;bin--){
	  PedTime[carddata->CardID].at(j).SetBinContent(bin,PedTime[carddata->CardID].at(j).GetBinContent(bin-1));
	  PedRMSTime[carddata->CardID].at(j).SetBinContent(bin,PedRMSTime[carddata->CardID].at(j).GetBinContent(bin-1));
	}
	PedTime[carddata->CardID].at(j).SetBinContent(0, pedpars[carddata->CardID].at(j).at(0));
	PedRMSTime[carddata->CardID].at(j).SetBinContent(0, pedpars[carddata->CardID].at(j).at(1));

	//////// fill temporal plot/////////
	for(int k=0;k<carddata->buffersize/4;k++){
	  //std::cout<<"d12"<<std::endl;

          //std::cout<<"j*4 = "<<j*4<<std::endl;
          //std::cout<<"(i*BufferSize)+(j*4) = "<<(i*BufferSize)+(j*4)<<std::endl;
          //std::cout<<"i*BufferSize)+(j*4)+(BufferSize/2) = "<<(i*BufferSize)+(j*4)+(BufferSize/2)<<std::endl;
          //std::cout<<"(i*BufferSize)+(j*4)+(BufferSize/2)+1 = "<<(i*BufferSize)+(j*4)+(BufferSize/2)+1<<std::endl;
	  int offset=pedpars[carddata->CardID].at(j).at(0);
          double conversion=2.415/pow(2.0, 12.0);
	  temporal.SetBinContent(k*4,(carddata->Data[(j*carddata->buffersize)+(k*2)]-offset)*conversion);
	  temporal.SetBinContent((k*4)+1,(carddata->Data[(j*carddata->buffersize)+(k*2)+1]-offset)*conversion);
	  temporal.SetBinContent((k*4)+2,(carddata->Data[(j*carddata->buffersize)+(k*2)+(carddata->buffersize/2)]-offset)*conversion);
	  temporal.SetBinContent((k*4)+3,(carddata->Data[(j*carddata->buffersize)+(k*2)+(carddata->buffersize/2)+1]-offset)*conversion);

        }

	//std::cout<<"d13"<<std::endl;

	//std::cout<<"d3"<<std::endl;
	
	temporalplots.push_back(temporal);


	////// find x,y,z fill event display /////////
	int x=-10;
	int z=-10;
	int y=-10;
	for(int pmt=0;pmt<PMTInfo.size();pmt++){
	  //std::cout<<"d4"<<std::endl;

	  if(PMTInfo.at(pmt).card==carddata->CardID && PMTInfo.at(pmt).channel==j){
	    x=PMTInfo.at(pmt).gx;
	    z=PMTInfo.at(pmt).gz;
	    y=PMTInfo.at(pmt).gy;
	    //std::cout<<"d15"<<std::endl;
	  
}
	}

	/*
	int x=(((i*4)+j)%8);
	int y=(floor(((i*4)+j)/8.0));
	if(x==0 && y==0){x=-10;y=-10;}
	if(x==7 && y==0){x=-10;y=-10;}
	if(x==0 && y==7){x=-10;y=-10;}
	if(x==7 && y==7){x=-10;y=-10;}
	if (y>7){x=-10;y=-10;}
	std::cout<<"i="<<i<<" j="<<j<<" (i*4)+j)="<<((i*4)+j)<<" x="<<x<<" y="<<y<<" sum="<<sum<<std::endl;
	EventDisplay.SetBinContent(x+1,y+1,sum);
	//EventDisplay.SetBinContent(((i*4)+j),sum);
	*/
	//std::cout<<"d16"<<std::endl;

	if(x!=-10 && z!=-10){
	  //std::cout<<"d17"<<std::endl;

	  //std::cout<<"gx = "<<x<<" , gz="<<z<<std::endl;
	  EventDisplay.SetBinContent(x+2,z+2,sum);
	  RMSDisplay.SetBinContent(x+2,z+2,gaus->GetParameter(2)*100);

	  //// Attempted 2ne event display ///
	  TGraph2D *dt=new TGraph2D(1);
	  dt->SetPoint(0,x,z,z);
	  dt->SetMarkerStyle(20);
	  //dt->GetXaxis()->SetRangeUser(-1,8);
	  // dt->GetYaxis()->SetRangeUser(-1,8);
	  //dt->GetZaxis()->SetRangeUser(-1,8);
	  mg.push_back(dt);
	}	
	
	}
	
	//std::cout<<"d18"<<std::endl;

	

	///////Find max freq for scaling//////////

	int maxplot=0;
	long maxvalue=0;
	
	//std::cout<<"i="<<i<<" (i*4)="<<(i*4)<<" (i*4)+4="<<(i*4)+4<<" size="<<freqplots.size()<<std::endl;
	for(int j=(i*4);j<(i*4)+4;j++){
	  if (freqplots.at(j).GetMaximum()>maxvalue){
	    //std::cout<<"d19"<<std::endl;
	 
   maxvalue=freqplots.at(j).GetMaximum();
	    maxplot=j;
	  }
	}
	

	//std::cout<<"d20"<<std::endl;

	////////Find current time and plot frewuency plot

	time_t t = time(0);   // get time now
	struct tm * now = localtime( & t );
	std::stringstream title;
	title<<"Card "<<carddata->CardID<<" frequency: "<<(now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' <<  now->tm_mday<<','<<now->tm_hour<<':'<<now->tm_min<<':'<<now->tm_sec;
	//std::cout<<"d21"<<std::endl;
	freqplots.at(maxplot).SetTitle(title.str().c_str());
	freqplots.at(maxplot).GetXaxis()->SetTitle("ADC Value");
	freqplots.at(maxplot).GetYaxis()->SetTitle("Frequency");	
	freqplots.at(maxplot).SetLineColor((maxplot%4)+1);
	freqplots.at(maxplot).Draw();
	TLegend leg(0.8,0.4,1.0,0.7);
	//leg.SetHeader("The Legend Title");
	
	//std::cout<<"d22"<<std::endl;
for(int j=(i*4);j<(i*4)+4;j++){
  //std::cout<<"d23"<<std::endl;
	  std::stringstream legend;
	  legend<<"Channel "<<j-(i*4);
	  leg.AddEntry(&freqplots.at(j),legend.str().c_str(),"l");	  
	  freqplots.at(j).SetLineColor((j%4)+1);
	  if(j==maxplot){;}//freqplots.at(i).Draw();                                  
	  else freqplots.at(j).Draw("same");
	  
	}
	leg.Draw();
	//std::cout<<"d24"<<std::endl;
	std::stringstream tmp;
	tmp<<outpath<<carddata->CardID<<"freq.jpg";
	c1.SaveAs(tmp.str().c_str());


	//std::cout<<"d25"<<std::endl;



	///////find max tmporal plot for scaling
	
	///temporal
	maxplot=0;
	maxvalue=0;

	//std::cout<<"i="<<i<<" (i*4)="<<(i*4)<<" (i*4)+4="<<(i*4)+4<<" size="<<freqplots.size()<<std::endl;
        for(int j=(i*4);j<(i*4)+4;j++){
	  //std::cout<<"d26"<<std::endl;
          if (temporalplots.at(j).GetMaximum()>maxvalue){
            maxvalue=temporalplots.at(j).GetMaximum();
            maxplot=j;
          }
        }

	//std::cout<<"d27"<<std::endl;


	//////// Find time and plot temporal plot

	t = time(0);   // get time now
        now = localtime( & t );
	std::stringstream title2;
        title2<<"Card "<<carddata->CardID<<" Temporal: "<<(now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' <<  now->tm_mday<<','<<now->tm_hour<<':'<<now->tm_min<<':'<<now->tm_sec;
	//std::cout<<"d28"<<std::endl;
        temporalplots.at(maxplot).SetTitle(title2.str().c_str());
	temporalplots.at(maxplot).GetXaxis()->SetTitle("Samples");
	temporalplots.at(maxplot).GetYaxis()->SetTitle("Volate (V)");
        temporalplots.at(maxplot).SetLineColor((maxplot%4)+1);
        temporalplots.at(maxplot).Draw();
	TLegend leg2(0.8,0.4,1.0,0.7);
	//std::cout<<"d29"<<std::endl;
	for(int j=(i*4);j<(i*4)+4;j++){
	  //std::cout<<"d30"<<std::endl;
	  std::stringstream legend;
	  legend<<"Channel "<<j-(i*4);	  
	  leg2.AddEntry(&temporalplots.at(j),legend.str().c_str(),"l");
	  temporalplots.at(j).SetLineColor((j%4)+1);
	  if(j==0){;}
	  else temporalplots.at(j).Draw("same");

	}
	//std::cout<<"d31"<<std::endl;
	leg2.Draw();
	//std::cout<<"d6"<<std::endl;

	std::stringstream tmp2;
	tmp2<<outpath<<carddata->CardID<<"temporal.jpg";
	c1.SaveAs(tmp2.str().c_str());
	//std::cout<<"d32"<<std::endl;


	///////plotting PED time and ped rms time //////
        maxplot=0;
        maxvalue=0;

      
        for(int j=0;j<4;j++){
          //std::cout<<"d26"<<std::endl;
          if ( PedTime[carddata->CardID].at(j).GetMaximum()>maxvalue){
            maxvalue=PedTime[carddata->CardID].at(j).GetMaximum();
            maxplot=j;
          }
        }

	t = time(0);   // get time now
        now = localtime( & t );
	title2.str("");
        title2<<"Card "<<carddata->CardID<<" Pedistal Variation: "<<(now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' <<  now->tm_mday<<','<<now->tm_hour<<':'<<now->tm_min<<':'<<now->tm_sec;
        //std::cout<<"d28"<<std::endl;
        PedTime[carddata->CardID].at(maxplot).SetTitle(title2.str().c_str());
	PedTime[carddata->CardID].at(maxplot).GetXaxis()->SetTitle("Samples");
	PedTime[carddata->CardID].at(maxplot).GetYaxis()->SetTitle("ADC Value");
	PedTime[carddata->CardID].at(maxplot).SetLineColor((maxplot%4)+1);
	PedTime[carddata->CardID].at(maxplot).Draw();
        TLegend leg3(0.8,0.4,1.0,0.7);
        //std::cout<<"d29"<<std::endl;
	for(int j=0;j<4;j++){
          //std::cout<<"d30"<<std::endl;
	  std::stringstream legend;
          legend<<"Channel "<<j;
          leg3.AddEntry(&PedTime[carddata->CardID].at(j),legend.str().c_str(),"l");
	  PedTime[carddata->CardID].at(j).SetLineColor((j%4)+1);
          PedTime[carddata->CardID].at(j).Draw("same");

        }
        //std::cout<<"d31"<<std::endl;
        leg3.Draw();
        //std::cout<<"d6"<<std::endl;

	tmp2.str("");
	tmp2<<outpath<<"plots2/"<<carddata->CardID<<"PedTime.jpg";
	c1.SaveAs(tmp2.str().c_str());



	PedRMSTime[carddata->CardID].at(0).Draw();
	for (int channel=1;channel<4;channel++){
	  PedRMSTime[carddata->CardID].at(channel).Draw("same");
	}
	tmp2.str("");
	tmp2<<outpath<<"plots2/"<<carddata->CardID<<"PedRMSTime.jpg";
	c1.SaveAs(tmp2.str().c_str());

	delete carddata;

	
      } /// size i
      
      /*
      //std::cout<<"d4"<<std::endl;

      int maxplot=0;
      long maxvalue=0;
      for(int i=0;i<freqplots.size();i++){
	if (freqplots.at(i).GetMaximum()>maxvalue){
	  maxvalue=freqplots.at(i).GetMaximum();
	  maxplot=i;
	}
      }

      freqplots.at(maxplot).SetLineColor(maxplot+1);
      freqplots.at(maxplot).Draw();
      for(int i=0;i<freqplots.size();i++){

	//	Double_t scale = 1/freqplots.at(i).GetMaximum();
	//	freqplots.at(i).Scale(scale);
	freqplots.at(i).SetLineColor(i+1);
	if(i==maxplot);//freqplots.at(i).Draw();
	else freqplots.at(i).Draw("same");

	//freqplots.at(i).Scale((1.0/scale));
      }
      std::cout<<"d5"<<std::endl;

      std::stringstream tmp;
      tmp<<outpath<<"freq.jpg";
      c1.SaveAs(tmp.str().c_str());
      
      for(int i=0;i<temporalplots.size();i++){
	temporalplots.at(i).SetLineColor(i+1);
	if(i==0)temporalplots.at(i).Draw();
	else temporalplots.at(i).Draw("same");
	
      }	  

      std::cout<<"d6"<<std::endl;

      std::stringstream tmp2;
      tmp2<<outpath<<"temporal.jpg";
      c1.SaveAs(tmp2.str().c_str());
      */
      //std::cout<<"d33"<<std::endl;


      /////////plot event display /////////

      EventDisplay.Draw("COLZ");
      std::stringstream tmp3;
      tmp3<<outpath<<"0EventDisplay.jpg";
      c1.SaveAs(tmp3.str().c_str());
      

      //std::cout<<"d34 ="<<mg.size()<<std::endl;

/////////plot RMS display /////////
      RMSDisplay.Draw("COLZ");
      tmp3.str("");
      tmp3<<outpath<<"0RMSDisplay.jpg";
      c1.SaveAs(tmp3.str().c_str());

      ///plot  atempted 3d event display///////

      tmp3.str("");
      if(mg.size()>0)      mg.at(0)->Draw();
      for(int plots=1;plots<mg.size();plots++){
	mg.at(plots)->Draw("same");
	//std::cout<<"d35"<<std::endl;
      }
      tmp3<<outpath<<"0EventDisplay3D.jpg";
      //c1.SaveAs(tmp3.str().c_str());





    }
    
    
    
    else if(arg1=="Quit"){
Exemplo n.º 15
0
void makeVNDet(){

  bool testrun          = 0;
  const int norder_     = 2;
  const int QnBinOrder_ = 2;
  const double vtxCut   = 15.;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0; //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;
  double qnHFx_EP[NumEPNames];
  double qnHFy_EP[NumEPNames];
  double sumET_EP[NumEPNames];

  TFile * fQNDet;
  TH1D * hqnHFDet_x[NumEPNames];
  TH1D * hqnHFDet_y[NumEPNames];

  TFile * fQN;
  TH1D * hqbins[NCENT][NEPSymm];

  TFile * fOut;
  TDirectory * SubEvt_0;
  TDirectory * SubEvt_1;
  TDirectory * FullEvt;

  TH2D * hVNDetX_0[NQN];
  TH2D * hVNDetY_0[NQN];
  TH2D * hVNDetX_1[NQN];
  TH2D * hVNDetY_1[NQN];
  TH2D * hVNDetX_full[NQN];
  TH2D * hVNDetY_full[NQN];

  double VNRawX_0[NCENT][NEPSymm][NQN];
  double VNRawY_0[NCENT][NEPSymm][NQN];
  double VNRawX_1[NCENT][NEPSymm][NQN];
  double VNRawY_1[NCENT][NEPSymm][NQN];
  double VNRawX_full[NCENT][NEPSymm][NQN];
  double VNRawY_full[NCENT][NEPSymm][NQN];

  double sumw_0[NCENT][NEPSymm][NQN];
  double sumw_1[NCENT][NEPSymm][NQN];
  double sumw_full[NCENT][NEPSymm][NQN];

  int evtMult_0[NCENT][NEPSymm][NQN];
  int evtMult_1[NCENT][NEPSymm][NQN];
  int evtMult_full[NCENT][NEPSymm][NQN];
 
  double VNDetX_0[NCENT][NEPSymm][NQN];
  double VNDetY_0[NCENT][NEPSymm][NQN];
  double VNDetX_1[NCENT][NEPSymm][NQN];
  double VNDetY_1[NCENT][NEPSymm][NQN];
  double VNDetX_full[NCENT][NEPSymm][NQN];
  double VNDetY_full[NCENT][NEPSymm][NQN];

  int Nevents[NCENT][NEPSymm][NQN];
  int NFails[NCENT][NEPSymm][NQN];

  //
  // MAIN
  //


  //-- Set up the analyzer objects
  fAna = new TFile(fAnaTreeName);

  tree = (TTree*) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
    
  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);
  tree->SetBranchAddress("qnHFx_EP",                &qnHFx_EP);
  tree->SetBranchAddress("qnHFy_EP",                &qnHFy_EP);
  tree->SetBranchAddress("sumET_EP",                &sumET_EP);

  //-- Get the QN Detector histograms                                                                                                                                                                                             
  fQNDet = new TFile( Form("../../../../../../v%i/eta2.4/systematicStudies/vtxCut/vtx3_15/AnalyzerResults/Q%iDet.root", QnBinOrder_, QnBinOrder_) );
  for(int iEP = 0; iEP < NumEPNames; iEP++){
    int EPbin  = EPSymmPartnerBin[iEP];
    if( EPbin != EPSymmBin ) continue;
    hqnHFDet_x[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_x_%s", EPNames[iEP].data()) );
    hqnHFDet_y[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_y_%s", EPNames[iEP].data()) );
  }

  //-- Setup the QN binning objects
  fQN = new TFile( Form( "../../../../../../v%i/eta2.4/systematicStudies/vtxCut/vtx3_15/AnalyzerResults/q%iCuts.root", QnBinOrder_, QnBinOrder_) );
  for(int icent = 0; icent < NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      hqbins[icent][iEP] = (TH1D*) fQN->Get( Form("hqbins_%s_c%i", EPSymmNames[iEP].data(), icent) );
    }
  }

  //-- Setup the output objects
  fOut     = new TFile( Form("V%iDet.root", norder_), "recreate" );
  SubEvt_0 = fOut->mkdir("SubEvt_0");
  SubEvt_1 = fOut->mkdir("SubEvt_1");
  FullEvt  = fOut->mkdir("FullEvt");
    
  for(int iqn = 0; iqn < NQN; iqn++){
    SubEvt_0->cd();
    hVNDetX_0[iqn]    = new TH2D( Form("hVNDetX_0_qbin%i", iqn),    Form("hVNDetX_0_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetX_0[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetX_0[iqn]->SetOption("colz");
    
    hVNDetY_0[iqn]    = new TH2D( Form("hVNDetY_0_qbin%i", iqn),    Form("hVNDetY_0_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetY_0[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetY_0[iqn]->SetOption("colz");
    
    SubEvt_1->cd();
    hVNDetX_1[iqn]    = new TH2D( Form("hVNDetX_1_qbin%i", iqn),    Form("hVNDetX_1_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetX_1[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetX_1[iqn]->SetOption("colz");
    
    hVNDetY_1[iqn]    = new TH2D( Form("hVNDetY_1_qbin%i", iqn),    Form("hVNDetY_1_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetY_1[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetY_1[iqn]->SetOption("colz");
  
    FullEvt->cd();
    hVNDetX_full[iqn] = new TH2D( Form("hVNDetX_full_qbin%i", iqn), Form("hVNDetX_full_qbin%i", iqn), NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetX_full[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetX_full[iqn]->SetOption("colz");
    
    hVNDetY_full[iqn] = new TH2D( Form("hVNDetY_full_qbin%i", iqn), Form("hVNDetY_full_qbin%i", iqn), NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetY_full[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetY_full[iqn]->SetOption("colz");
    
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      hVNDetX_0[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetY_0[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetX_1[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetY_1[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetX_full[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetY_full[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
    }

  }
    
  //-- initialize all variables
  for(int icent = 0; icent<NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      for(int iqn = 0; iqn < NQN; iqn++){

	VNDetX_0[icent][iEP][iqn]     = 0.;
	VNDetY_0[icent][iEP][iqn]     = 0.;
	VNDetX_1[icent][iEP][iqn]     = 0.;
	VNDetY_1[icent][iEP][iqn]     = 0.;
	VNDetX_full[icent][iEP][iqn]  = 0.;
	VNDetY_full[icent][iEP][iqn]  = 0.;

	evtMult_0[icent][iEP][iqn]    = 0;
	evtMult_1[icent][iEP][iqn]    = 0;
	evtMult_full[icent][iEP][iqn] = 0;

	Nevents[icent][iEP][iqn]      = 0;
	NFails[icent][iEP][iqn]       = 0;

      }
    }
  }
    
    
  //
  // Calculate Vn_det
  //
    
  cout<<"Begin DETECTOR loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if(testrun) N = 10000; 
  else        N = tree->GetEntries();


  //-- Begin event loop
  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout << "Processing Event " << ievent+1 << "\t" << (100.*(ievent+1)/N) << "% Completed" << endl;
        
    tree->GetEntry(ievent);
      
    //-- Vertex Cut
    if(TMath::Abs(vtx) < 3. || TMath::Abs(vtx) > 15.) continue;
      
    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- begin EP loop
    for(int iEP = 0; iEP < NEP; iEP++){

      int EPbin  = EPSymmPartnerBin[iEP];
      if( EPbin != EPSymmBin ) continue;

      //-- Calculate qbin
      double qx    = qnHFx_EP[iEP];
      double qy    = qnHFy_EP[iEP];
      double qxDet = hqnHFDet_x[iEP]->GetBinContent(icent+1);
      double qyDet = hqnHFDet_y[iEP]->GetBinContent(icent+1);
      double sumET = sumET_EP[iEP];
      if(sumET == 0) continue;
      qx -= qxDet;
      qy -= qyDet;
      qx /= sumET;
      qy /= sumET;
      double qn = TMath::Sqrt( qx*qx + qy*qy );
      int   iqn = hqbins[icent][EPbin]->FindBin( qn ) - 1;
      if(iqn >= NQN) continue;

      //-- Reset Raw and sumw values
      VNRawX_0[icent][EPbin][iqn]     = 0.;
      VNRawY_0[icent][EPbin][iqn]     = 0.;
      VNRawX_1[icent][EPbin][iqn]     = 0.;
      VNRawY_1[icent][EPbin][iqn]     = 0.;
      VNRawX_full[icent][EPbin][iqn]  = 0.;
      VNRawY_full[icent][EPbin][iqn]  = 0.;            
	
      sumw_0[icent][EPbin][iqn]       = 0.;
      sumw_1[icent][EPbin][iqn]       = 0.;
      sumw_full[icent][EPbin][iqn]    = 0.;
      
      evtMult_0[icent][EPbin][iqn]    = 0;
      evtMult_1[icent][EPbin][iqn]    = 0;
      evtMult_full[icent][EPbin][iqn] = 0;
      
      Nevents[icent][EPbin][iqn]++;

      //-- Begin analyzer histogram loops
      for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
	for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){
	  
	  if(sumw->GetBinContent(ipt+1,ieta+1) !=0){
	    
	    //-- Subevent 0 (eta >= 0)
	    if(etabinsDefault[ieta] >= 0){
	      VNRawX_0[icent][EPbin][iqn]   += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VNRawY_0[icent][EPbin][iqn]   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	      sumw_0[icent][EPbin][iqn]     += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_0[icent][EPbin][iqn]  += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Subevent 1 (eta < 0)
	    else{
	      VNRawX_1[icent][EPbin][iqn]   += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VNRawY_1[icent][EPbin][iqn]   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	      sumw_1[icent][EPbin][iqn]     += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_1[icent][EPbin][iqn]  += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Full Event
	    VNRawX_full[icent][EPbin][iqn]  += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VNRawY_full[icent][EPbin][iqn]  += sumwqy->GetBinContent(ipt+1,ieta+1);
	    
	    sumw_full[icent][EPbin][iqn]    += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_full[icent][EPbin][iqn] += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  
	} //-- End eta loop
	
      } //-- End pt loop
      
      //-- Only use events that have tracks in all subevents AND subevents that have at least two tracks to determine VN
      if( sumw_0[icent][EPbin][iqn] == 0 || sumw_1[icent][EPbin][iqn] == 0 || evtMult_0[icent][EPbin][iqn] < 2 || evtMult_1[icent][EPbin][iqn] < 2 ){
	NFails[icent][EPbin][iqn]++;
      }
      else{      
	VNDetX_0[icent][EPbin][iqn]    += VNRawX_0[icent][EPbin][iqn]    / sumw_0[icent][EPbin][iqn];
	VNDetY_0[icent][EPbin][iqn]    += VNRawY_0[icent][EPbin][iqn]    / sumw_0[icent][EPbin][iqn];
	VNDetX_1[icent][EPbin][iqn]    += VNRawX_1[icent][EPbin][iqn]    / sumw_1[icent][EPbin][iqn];
	VNDetY_1[icent][EPbin][iqn]    += VNRawY_1[icent][EPbin][iqn]    / sumw_1[icent][EPbin][iqn];
	VNDetX_full[icent][EPbin][iqn] += VNRawX_full[icent][EPbin][iqn] / sumw_full[icent][EPbin][iqn];
	VNDetY_full[icent][EPbin][iqn] += VNRawY_full[icent][EPbin][iqn] / sumw_full[icent][EPbin][iqn];
      }

    } //-- End EP loop

  } //-- End event loop
    
  std::cout<<"End DETECTOR loop"<<std::endl;

  //-- Average VNDet over all events for each centrality, EP and, qn bin
  for(int iqn = 0; iqn < NQN; iqn++){
    for(int icent = 0; icent < NCENT; icent++){
      for(int iEP = 0; iEP < NEPSymm; iEP++){
	if( iEP != EPSymmBin ) continue;

	double  Neffective = (double) Nevents[icent][iEP][iqn] - (double) NFails[icent][iEP][iqn];
	if( Neffective == 0) continue;

	VNDetX_0[icent][iEP][iqn]    /= Neffective;
	VNDetY_0[icent][iEP][iqn]    /= Neffective;
	VNDetX_1[icent][iEP][iqn]    /= Neffective;
	VNDetY_1[icent][iEP][iqn]    /= Neffective;
	VNDetX_full[icent][iEP][iqn] /= Neffective;
	VNDetY_full[icent][iEP][iqn] /= Neffective;

	//-- Populate histograms that will be used by ReadTree_normDet.C
	hVNDetX_0[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetX_0[icent][iEP][iqn]);
	hVNDetX_1[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetX_1[icent][iEP][iqn]);
	hVNDetX_full[iqn] -> SetBinContent(icent+1, iEP+1, VNDetX_full[icent][iEP][iqn]);
        
	hVNDetY_0[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetY_0[icent][iEP][iqn]);
	hVNDetY_1[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetY_1[icent][iEP][iqn]);
	hVNDetY_full[iqn] -> SetBinContent(icent+1, iEP+1, VNDetY_full[icent][iEP][iqn]);

      }
    }
  } //-- END TRIPLE LOOP

  fOut->Write();
  cout<<"File written, process completed"<<endl;

}
Exemplo n.º 16
0
void CsIProj()
{
  TFile *file = new TFile("../root/NZ_55_New.root");
  TFile *gates = new TFile("../gates/zlines.root");
  TFile *gates2 = new TFile("../gates/zlines_new.root");

  ofstream ofile("CsI_55A_New.dat");
  
  TCanvas *mycan = (TCanvas*)gROOT->FindObjectAny("mycan");
  if(!mycan)
    {
      mycan = new TCanvas("mycan","mycan");
      mycan->Divide(1,2);
    }
  
  
  ostringstream outstring;
  string name;
  int p1= 30, p2=50; //+- fit limits up to 2 peaks. May be different.
  int const num_par = 5; //number of peaks times 2(pol1)+3(gaus).
  
  for(int ic =0;ic<56;ic++)
    {
      
      outstring.str("");
      outstring << "dEE/dEE_" << ic;
      name = outstring.str();
      
      mycan->cd(1);
      TH2I *hist = (TH2I*)file->Get(name.c_str());
      hist->Draw("col");  
      hist->GetXaxis()->SetRangeUser(200.,1800.); 
      hist->GetYaxis()->SetRangeUser(5.,50.); 
   
      
      if(ic <16 || ic > 31)
	TCutG *mycut = (TCutG*)gates->Get(Form("Zline_%i_2_4",ic));
      else 
	TCutG *mycut = (TCutG*)gates2->Get(Form("Zline_%i_2_4",ic));
      mycut->Draw();

      file->cd();
      outstring.str("");
      outstring << "CsI/CsIGate/ECsI_" << ic << "_Gate";
      name = outstring.str();
      gPad->SetLogz();

      mycan->cd(2);
      TH1I * proj = (TH1I*)file->Get(name.c_str());
      proj->Draw();
      proj->Rebin(4);
      proj->GetXaxis()->SetRangeUser(700.,1800.);

      mycan->Modified();
      mycan->Update();

      TMarker * mark;
      mark=(TMarker*)mycan->WaitPrimitive("TMarker"); //Get the Background limits
      int bkg_lo = mark->GetX();
      delete mark;  
      mark=(TMarker*)mycan->WaitPrimitive("TMarker");
      int bkg_hi = mark->GetX();
      delete mark;
      mark=(TMarker*)mycan->WaitPrimitive("TMarker"); // Get the 1st peak initial guess
      int peak1 = mark->GetX();
      delete mark;
      
      
      double par[num_par] = {0.};
      double out[num_par] = {0.}; 
      int peak1_lo = peak1 - p1, peak1_hi = peak1 + p1; // Peak center and limits
      
      
      TF1 *l1 = new TF1("l1", "pol1", bkg_lo, bkg_hi);
      TF1 *g1 = new TF1("g1", "gaus", peak1_lo,peak1_hi);
      
      TF1 *total = new TF1("total", "pol1(0)+gaus(2)", bkg_lo,bkg_hi);
      
      proj->Fit(l1,"R");
      proj->Fit(g1,"R+");
      
      l1->GetParameters(&par[0]);
      g1->GetParameters(&par[2]);
      
      total->SetParameters(par);
      proj->Fit(total,"R");
      total->GetParameters(out);
      
      
      ofile << ic << " " << out[3] << endl;
      
      outstring.str("");
      outstring << "55A_" << ic;
      name = outstring.str();
      total->SetName(name.c_str());
      total->Draw("same");
      mycan->Modified();
      mycan->Update();
      
      bool IsGood = 0;

      cout << "Good fit?" << endl;
      cin >> IsGood;
  

      if(IsGood)
	{
      ofile << ic << " " << out[3] << endl;
	}      
      else
	ofile << ic << " " << -1 << endl;      

   

    }
  
  
  return;
}
Exemplo n.º 17
0
void makeVNDet(){

  bool testrun          = 0;
  const int norder_     = 2;
  const double vtxCut   = 15.;

  const double ptMin = 0.3;
  const double ptMax = 3.00;
  const double etaMax = 1.0;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0;  //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;

  TFile * fOut;
  TDirectory * SubEvt_0;
  TDirectory * SubEvt_1;
  TDirectory * FullEvt;

  TH1D * hVNDetX_0;
  TH1D * hVNDetY_0;
  TH1D * hVNDetX_1;
  TH1D * hVNDetY_1;
  TH1D * hVNDetX_full;
  TH1D * hVNDetY_full;

  double VNRawX_0[NCENT];
  double VNRawY_0[NCENT];
  double VNRawX_1[NCENT];
  double VNRawY_1[NCENT];
  double VNRawX_full[NCENT];
  double VNRawY_full[NCENT];

  double sumw_0[NCENT];
  double sumw_1[NCENT];
  double sumw_full[NCENT];

  int evtMult_0[NCENT];
  int evtMult_1[NCENT];
  int evtMult_full[NCENT];
 
  double VNDetX_0[NCENT];
  double VNDetY_0[NCENT];
  double VNDetX_1[NCENT];
  double VNDetY_1[NCENT];
  double VNDetX_full[NCENT];
  double VNDetY_full[NCENT];

  int Nevents[NCENT];
  int NFails[NCENT];

  //
  // MAIN
  //


  //-- Set up the analyzer objects
  fAna = new TFile("/rfs/jcastle/PbPb2015/PixelTracking_MB2/EbyETree_EPOS_LHC_RECO_SMEAR5.root");

  tree = (TTree*) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
    
  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);

  //-- Setup the output objects
  fOut     = new TFile( Form("V%iDet.root", norder_), "recreate" );
  SubEvt_0 = fOut->mkdir("SubEvt_0");
  SubEvt_1 = fOut->mkdir("SubEvt_1");
  FullEvt  = fOut->mkdir("FullEvt");
    
  SubEvt_0->cd();
  hVNDetX_0    = new TH1D( "hVNDetX_0",    "hVNDetX_0",    NCENT, centbinsDefault);
  hVNDetX_0->GetXaxis()->SetTitle("Centrality %");
    
  hVNDetY_0    = new TH1D( "hVNDetY_0",    "hVNDetY_0",    NCENT, centbinsDefault);
  hVNDetY_0->GetXaxis()->SetTitle("Centrality %");
    
  SubEvt_1->cd();
  hVNDetX_1    = new TH1D( "hVNDetX_1",    "hVNDetX_1",    NCENT, centbinsDefault);
  hVNDetX_1->GetXaxis()->SetTitle("Centrality %");
    
  hVNDetY_1    = new TH1D( "hVNDetY_1",    "hVNDetY_1",    NCENT, centbinsDefault);
  hVNDetY_1->GetXaxis()->SetTitle("Centrality %");
  
  FullEvt->cd();
  hVNDetX_full = new TH1D( "hVNDetX_full", "hVNDetX_full", NCENT, centbinsDefault);
  hVNDetX_full->GetXaxis()->SetTitle("Centrality %");
    
  hVNDetY_full = new TH1D( "hVNDetY_full", "hVNDetY_full", NCENT, centbinsDefault);
  hVNDetY_full->GetXaxis()->SetTitle("Centrality %");
    
  //-- initialize all variables
  for(int icent = 0; icent<NCENT; icent++){

    VNDetX_0[icent]     = 0.;
    VNDetY_0[icent]     = 0.;
    VNDetX_1[icent]     = 0.;
    VNDetY_1[icent]     = 0.;
    VNDetX_full[icent]  = 0.;
    VNDetY_full[icent]  = 0.;

    evtMult_0[icent]    = 0;
    evtMult_1[icent]    = 0;
    evtMult_full[icent] = 0;

    Nevents[icent]      = 0;
    NFails[icent]       = 0;

  }
    
    
  //
  // Calculate Vn_det
  //
    
  cout<<"Begin DETECTOR loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if(testrun) N = 10000; 
  else        N = tree->GetEntries();

  //-- Begin event loop
  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout << "Processing Event " << ievent+1 << "\t" << (100.*(ievent+1)/N) << "% Completed" << endl;
        
    tree->GetEntry(ievent);
      
    //-- Vertex Cut
    if(TMath::Abs(vtx) > vtxCut) continue;
      
    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- Reset Raw and sumw values
    VNRawX_0[icent]     = 0.;
    VNRawY_0[icent]     = 0.;
    VNRawX_1[icent]     = 0.;
    VNRawY_1[icent]     = 0.;
    VNRawX_full[icent]  = 0.;
    VNRawY_full[icent]  = 0.;            
	
    sumw_0[icent]       = 0.;
    sumw_1[icent]       = 0.;
    sumw_full[icent]    = 0.;
      
    evtMult_0[icent]    = 0;
    evtMult_1[icent]    = 0;
    evtMult_full[icent] = 0;
      
    Nevents[icent]++;

    //-- Begin analyzer histogram loops
    for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
      for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){
	  
	double pt  = sumw->GetXaxis()->GetBinCenter(ipt+1);
        double eta = sumw->GetYaxis()->GetBinCenter(ieta+1);
        if( pt < ptMin || pt > ptMax ) continue;
        if( fabs( eta ) > etaMax )     continue;

	if(sumw->GetBinContent(ipt+1,ieta+1) !=0){
	    
	  //-- Subevent 0 (eta >= 0)
	  if(etabinsDefault[ieta] >= 0){
	    VNRawX_0[icent]   += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VNRawY_0[icent]   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	    sumw_0[icent]     += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_0[icent]  += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Subevent 1 (eta < 0)
	  else{
	    VNRawX_1[icent]   += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VNRawY_1[icent]   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	    sumw_1[icent]     += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_1[icent]  += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Full Event
	  VNRawX_full[icent]  += sumwqx->GetBinContent(ipt+1,ieta+1);
	  VNRawY_full[icent]  += sumwqy->GetBinContent(ipt+1,ieta+1);
	    
	  sumw_full[icent]    += sumw->GetBinContent(ipt+1,ieta+1);
	  evtMult_full[icent] += hMult->GetBinContent(ipt+1,ieta+1);
	}
	  
      } //-- End eta loop
      
    } //-- End pt loop
    
    //-- Only use events that have tracks in all subevents AND subevents that have at least two tracks to determine VN
    if( sumw_0[icent] == 0 || sumw_1[icent] == 0 || evtMult_0[icent] < 2 || evtMult_1[icent] < 2 ){
	NFails[icent]++;
    }
    else{      
      VNDetX_0[icent]    += VNRawX_0[icent]    / sumw_0[icent];
      VNDetY_0[icent]    += VNRawY_0[icent]    / sumw_0[icent];
      VNDetX_1[icent]    += VNRawX_1[icent]    / sumw_1[icent];
      VNDetY_1[icent]    += VNRawY_1[icent]    / sumw_1[icent];
      VNDetX_full[icent] += VNRawX_full[icent] / sumw_full[icent];
      VNDetY_full[icent] += VNRawY_full[icent] / sumw_full[icent];
    }

  } //-- End event loop
    
  std::cout<<"End DETECTOR loop"<<std::endl;

  //-- Average VNDet over all events for each centrality, EP and, qn bin
  for(int icent = 0; icent < NCENT; icent++){
  
    double  Neffective = (double) Nevents[icent] - (double) NFails[icent];
    if( Neffective == 0 ) continue;
    
    VNDetX_0[icent]    /= Neffective;
    VNDetY_0[icent]    /= Neffective;
    VNDetX_1[icent]    /= Neffective;
    VNDetY_1[icent]    /= Neffective;
    VNDetX_full[icent] /= Neffective;
    VNDetY_full[icent] /= Neffective;

    //-- Populate histograms that will be used by ReadTree_normDet.C
    hVNDetX_0    -> SetBinContent(icent+1, VNDetX_0[icent]);
    hVNDetX_1    -> SetBinContent(icent+1, VNDetX_1[icent]);
    hVNDetX_full -> SetBinContent(icent+1, VNDetX_full[icent]);
        
    hVNDetY_0    -> SetBinContent(icent+1, VNDetY_0[icent]);
    hVNDetY_1    -> SetBinContent(icent+1, VNDetY_1[icent]);
    hVNDetY_full -> SetBinContent(icent+1, VNDetY_full[icent]);

  }

  fOut->Write();
  cout<<"File written, process completed"<<endl;

}
Exemplo n.º 18
0
void ITSSDDQAMaker(char *iFile, Int_t MaxEvts=1000000, Int_t FirstEvt=0) {

  //To have Baseline Histos uncomment parts with " // BL!!! " comment

cout << "SDD Quality Assurance Prototype Macro" << endl; 

const Int_t nSDDmodules= 260;
const Int_t imodoffset = 240;
const Int_t modtotSDD  = nSDDmodules*2;
const Int_t anode = 256;

Float_t xi = -0.5;
Float_t xf = xi + nSDDmodules;
TH1F *hModulePattern = new TH1F("hModulePattern","Modules pattern",nSDDmodules,xi,xf);
xf = xi + modtotSDD;
TH1F *hModuleSidePattern = new TH1F("hModuleSidePattern","Modules/Side pattern",modtotSDD,xi,xf);

TH2F *hModuleChargeMap[modtotSDD];  //260 dx e 260 sx  with A, T, Q
TH2F *hModuleCountsMap[modtotSDD];  //260 dx e 260 sx  with A, T, Ncounts
TH2I *hModuleCarlos = new TH2I("hModuleCarlos","hModuleCarlos",modtotSDD,xi,xf,101,-0.5,100.5);
/*
  TH1F *hModuleSideBL[modtotSDD][anode];                                // BL!!!
*/ 


//-------histograms definition 
Char_t *hisnam = new Char_t[50];
Char_t *histit = new Char_t[50];  
Char_t *hisnam2 = new Char_t[50];
Char_t *histit2 = new Char_t[50];    
Char_t *hisnam3 = new Char_t[50];
 for(Int_t imod=0; imod<nSDDmodules;imod++){
   for(Int_t isid=0;isid<2;isid++){
     Int_t index=2*imod+isid;       //260*2 position

     sprintf(hisnam,"chargeMap%d",index);
     sprintf(histit,"Total Charge, module number %d",index);
     hModuleChargeMap[index]=new TH2F(hisnam,histit,256,-0.5,255.5,256,-0.5,255.5);  

     sprintf(hisnam2,"countsMap%d",index);
     sprintf(histit2,"Number of Counts, module number %d",index);
     hModuleCountsMap[index] = new TH2F(hisnam2,histit2,256,-0.5,255.5,256,-0.5,255.5);
     /*
       for(Int_t ianode=0; ianode<anode; ianode++){                         // BL!!!
       sprintf(hisnam3,"BL_module_%d_%d",index,ianode); 
       //cout<<hisnam3 <<endl;
       hModuleSideBL[index][ianode] = new TH1F(hisnam3,hisnam3,256,0.,1024.);
     }
     */
   }
 }

  TString strFile = iFile;
  strFile += "?EventType=7";
  AliRawReader *rd = new AliRawReaderDate(strFile.Data(),FirstEvt);  // open run
  Int_t evCounter = 0;
  do{                       // start loop on events
    if(++evCounter > MaxEvts) { cout << MaxEvts << " events read, stop" << endl; evCounter--; break; }  
    cout << "Read Event: " << evCounter+FirstEvt-1 << endl;

    rd->RequireHeader(kFALSE);             
    rd->Reset();                           // reset the current position to the beginning of the event
 
    Int_t nSkip = 0;                     // number of skipped signals
    AliITSRawStreamSDD s(rd);            //This class provides access to ITS SDD digits in raw data.
    Int_t iddl;
    Int_t isddmod;
    Int_t moduleSDD;
    gStyle->SetPalette(1);
    while(s.Next()){                     //read the next raw digit; returns kFALSE if there is no digit left
      if(s.IsCompletedModule()) continue;
      if(s.IsCompletedDDL()) continue;
      iddl=rd->GetDDLID()-2; // -2 is temporary for test raw data

	isddmod=s.GetModuleNumber(iddl,s.GetCarlosId());        //this is the FEE Carlos
       	//cout<<"DDLID= "<<iddl <<"; Module number= " <<isddmod  <<endl;
	if(isddmod >= imodoffset) { 
	  hModulePattern->Fill(isddmod-imodoffset);             // 0 to 259    so  240 to 499
	  moduleSDD=2*(isddmod-imodoffset)+s.GetChannel();
          hModuleSidePattern->Fill(moduleSDD);                  // 0 to 519
	  hModuleCarlos->Fill(isddmod-imodoffset,s.GetCarlosId());
          //cout << "anode " << s.GetCoord1() << ", time bin: " << s.GetCoord2() << ", charge: " << s.GetSignal() << endl;	  
	  Int_t coord1 = s.GetCoord1();
 	  Int_t coord2 = s.GetCoord2();
 	  Int_t signal = s.GetSignal();
	  hModuleChargeMap[moduleSDD]->Fill(coord2, coord1,signal);
          hModuleCountsMap[moduleSDD]->Fill(coord2, coord1 );   
	  //hModuleSideBL[moduleSDD][coord1]->Fill(signal);             // BL  !!!
	} else {
	  nSkip++;
	}
    }    
    cout << "End of Event " << evCounter+FirstEvt-1 << ", " << nSkip << " wrong module numbers" << endl;
  } while(rd->NextEvent()); // end loop on events
  delete rd;

  cout << "end after " << evCounter << " events" << endl;
  /*
  TNtuple *Baseline = new TNtuple("Baseline","Baseline","HalfModule:Anode:Mean:RMS");      // BL!!!
  Float_t meanBL;
  Float_t rmsBL;  
  */
  for(Int_t i=0; i<modtotSDD; i++){   
    if(hModuleSidePattern->GetBinContent(i+1)){              //check if they're not empty
      hModuleChargeMap[i]->GetXaxis()->SetTitle("Time Bin");
      hModuleChargeMap[i]->GetYaxis()->SetTitle("Anode"); 
      hModuleCountsMap[i]->GetXaxis()->SetTitle("Time Bin");
      hModuleCountsMap[i]->GetYaxis()->SetTitle("Anode");  
      /*
      for(Int_t ianode=0; ianode<anode; ianode++ ){                                      // BL!!!
	hModuleSideBL[i][ianode]->GetXaxis()->SetTitle("ADC counts");
	hModuleSideBL[i][ianode]->GetYaxis()->SetTitle("#"); 
	meanBL = hModuleSideBL[i][ianode]->GetMean();
	rmsBL = hModuleSideBL[i][ianode]->GetRMS();
	gaussfitBL = hModuleSideBL[i][ianode]->Fit("gaus");	
	Baseline->Fill(i,ianode,meanBL,rmsBL);
      }
      */
    }
  }  
  
  hModuleSidePattern->GetXaxis()->SetTitle("2*(Module Number-1)+Side");
  hModuleSidePattern->GetYaxis()->SetTitle("Counts");  
  hModulePattern->GetXaxis()->SetTitle("Module Number");  
  hModulePattern->GetYaxis()->SetTitle("Counts");  


  //-------store Histograms
  cout << "Store Histograms" << endl;
  TString oFileName(iFile);
  oFileName.Append(".root");
  TFile *oFile = TFile::Open(oFileName,"recreate");
  hModulePattern->Write();
  hModuleSidePattern->Write();
  hModuleCarlos->Write();
  for(Int_t i=0; i<modtotSDD; i++){ 
      if(hModuleSidePattern->GetBinContent(i+1)){            //check if they're not empty
	hModuleChargeMap[i]->Write();
	hModuleCountsMap[i]->Write();     
	/* 
	for(Int_t ianode=0; ianode<anode; ianode++ ){                           // BL!!!
 	  hModuleSideBL[i][ianode]->Write();
	  Baseline->Write();
 	}
	*/
      }
  }
  
  oFile->Close();
  cout << "Clear memory" << endl;
  for(Int_t imod=0; imod<nSDDmodules;imod++){
    for(Int_t isid=0;isid<2;isid++){
      Int_t index=2*imod+isid;       //260*2 position
      delete hModuleChargeMap[index];
      delete hModuleCountsMap[index];       
      /*
      for(Int_t ianode=0; ianode<anode; ianode++ ){                              // BL!!!
	delete hModuleSideBL[index][ianode]; 
	delete Baseline;
      }
      */
    }
  }
  delete hModulePattern;
  delete hModuleSidePattern;
  delete hModuleCarlos;

}
Exemplo n.º 19
0
void CCDimage14(int firstrun, int lastrun)
{
  gStyle->SetPalette(1,0); 
  gSystem->Load("libMaxCam");
  gSystem->Load("libWaveformTools.so");

  std::stringstream sstm;

  TH2F * sum = 0; 
  TH2I * count = 0;
  TH2F * p=0;
         sum = new TH2F("alpha_sum","alpha_sum",256,0,1024,256,0,1024); 
        count = new TH2I("alpha_count","alpha_count",256,0,1024,256,0,1024);
  const int c = 0;
 
  gROOT->cd(); 

  int runnum;
  int setnum;
  
    if		(firstrun>=889 && lastrun<=954)		{setnum=0;}
    else if	(firstrun>=955 && lastrun<=3868)	{setnum=1;}
    else if	(firstrun>=3876 && lastrun<=5789)	{setnum=2;}
	else if	(firstrun>=5792)					{setnum=3;}
	else
	{
	gApplication->Terminate();
	exit;}
  
  
for (int x = firstrun; x <= lastrun; x++){
	runnum=x;
	
       string origfile = "/net/nudsk0001/d00/scratch/dctpc_tmp/bigdctpc_data/BigDCTPC_run_";
       string skimfile = "/net/nudsk0001/d00/scratch/dctpc_tmp/bigdctpc_skim/BigDCTPC_run_";  
      
//            string origfile = "/net/hisrv0001/home/spitzj/myOutput_";
//      string skimfile = "/net/hisrv0001/home/spitzj//myOutput_";
      
      string skimend = "skim.root";
      string origend = ".root";
      string origfilename;
      string skimfilename;
      sstm.str("");
      if (x<10000){ origfile+="0"; skimfile+="0"; }
      if (x<1000){ origfile+="0"; skimfile+="0"; }
      if (x<100){ origfile+="0"; skimfile+="0"; }
      if (x<10){ origfile+="0"; skimfile+="0"; }
      sstm << origfile << x << origend;
      origfilename = sstm.str();
      sstm.str("");
      sstm << skimfile << x << skimend;
      skimfilename = sstm.str();
      cout << origfilename << endl;
      ifstream ifile(origfilename.c_str());
      ifstream ifile2(skimfilename.c_str());
      if(!ifile)
	  continue;
      if(!ifile2)
	continue;
  	DmtpcSkimDataset d;
  	d.openRootFile(skimfilename.c_str());    
  	d.loadDmtpcEvent(true,origfilename.c_str());
  	for (int i = 0; i < d.nevents(); i ++){
        if(i%100==0){
			cout<<"Event: "<<i<<endl;
		}

	//cout<<"here"<<endl
    d.getEvent(i);    
    //cout<<"here2"<<endl;
    for (int t =0 ; t < d.event()->ntracks(c); t++)
    {
      if(d.event()->maxpixel(0,t)>150){continue;}
      if(d.event()->spark(0)){continue;} 
      p = (TH2F*)d.event()->cluster(c)->getImage(); 
      vector<int> clust = d.event()->cluster(c)->getCluster(t); 
     
    	for (vector<int>::iterator it = clust.begin(); it!=clust.end(); it++)
		{
	  		sum->SetBinContent(*it, sum->GetArray()[*it] + p->GetArray()[*it]);
	  		count->SetBinContent(*it, count->GetArray()[*it] + 1); 
		}    
    }
  }
 }

  TH2F * normalized = (TH2F*) sum->Clone("normalized"); 
  normalized->SetName("normalized");
  normalized->Divide(count); 
  normalized->SetStats(0);
  normalized->Draw("COLZ");
  c1->Print(Form("CCDimage14_set_%d_runs_%d_%d.pdf",setnum,firstrun,lastrun));

  TFile *f=new TFile(Form("CCDimage14_set_%d_runs_%d_%d.root",setnum,firstrun,lastrun),"RECREATE");
  normalized->Write();
  f->Close();

  gApplication->Terminate();
}
Exemplo n.º 20
0
void frameViewer(char* arg) {
	//Take the arguments and save them into respective strings
	std::string infileName;
	std::string inF;
	std::string inPrefix;
	std::string runs, layers;
	std::string runCount;
	std::istringstream stm(arg);

	inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/rawRoot/";

	while (true) {	
		if (std::getline(stm, layers, ' ')) {

			//load the input root files
			TChain *chain = new TChain("fourChamTree");

			for (int i=0; ; i++) {
				runCount = std::to_string(i);
				inF = "run" + runCount + "_" + layers + "layers.root";
				infileName = inPrefix + inF;
				ifstream fin;
				fin.open(infileName.c_str());
				if (!fin.fail()) {
					fin.close();
					chain->Add(infileName.c_str());
					std::cout << "Got " << inF << std::endl;
				} else break;
			}

			const int width=480;	//width of the raw image
			const int height=640;	//height of the raw image


			int x=-10;	//x from file
			int y=-10;	//y from file
			int intensity=-10;	//pixle intensity from file
			int pNum=0;//a counter of the order in which the frame was processed

			//the 2d array which will store each frame of image data.
			int frame[480][640]={0};

			//variables
			int UNIXtime=0;
			float tdc[2]={-10,-10};


			//TTree *T = new TTree("T","TTree of muplus data");
			//add the 'branches' to the tree we will now read in
			chain->SetBranchAddress("pNum",&pNum);	//branch for the frame number
			chain->SetBranchAddress("frame",&frame);	//branch for frame data

			TH2I *frameHisto = new TH2I("Single 4 Spark Event","",width,0,width,height,0,height);	//histogram for the stacked images

			TH1I *chamber1 = new TH1I("chamber1","Chamber 1",width,0,width);//histogram for chamber 1 (the top one)
			TH1I *chamber2 = new TH1I("chamber2","Chamber 2",width,0,width);//histogram for chamber 2
			TH1I *chamber3 = new TH1I("chamber3","Chamber 3",width,0,width);//histogram for chamber 3
			TH1I *chamber4 = new TH1I("chamber4","Chamber 4",width,0,width);//histogram for chamber 4 (the bottom one)
			
			TH1I *chamber1y = new TH1I("chamber1y","Chamber 1",height,0,height);//histogram for chamber 1 (the top one)
			TH1I *chamber2y = new TH1I("chamber2y","Chamber 2",height,0,height);//histogram for chamber 2
			TH1I *chamber3y = new TH1I("chamber3y","Chamber 3",height,0,height);//histogram for chamber 3
			TH1I *chamber4y = new TH1I("chamber4y","Chamber 4",height,0,height);//histogram for chamber 4 (the bottom one)

			//output the plot of the stacked images
		
			TCanvas *fH2 = new TCanvas("fH2", "Single 4 Spark Event", 0, 0, 800, 800);
			fH2->cd();
			frameHisto->Draw();
			frameHisto->GetXaxis()->SetTitle("X position (px)");
			frameHisto->GetXaxis()->CenterTitle();

			frameHisto->GetYaxis()->SetTitle("Intensity");
			frameHisto->GetYaxis()->SetTitleOffset(1.4);
			frameHisto->GetYaxis()->CenterTitle();

			TCanvas *pc2 = new TCanvas("pc2","Frame",0,0,800,800);
			
			pc2->Divide(2,2);
			
			pc2->cd(1);
			chamber1->Draw();
			chamber1->GetXaxis()->SetTitle("X position (px)");
			chamber1->GetXaxis()->CenterTitle();

			chamber1->GetYaxis()->SetTitle("Intensity");
			chamber1->GetYaxis()->SetTitleOffset(1.4);
			chamber1->GetYaxis()->CenterTitle();

			pc2->cd(2);
			chamber2->Draw();
			chamber2->GetXaxis()->SetTitle("X position (px)");
			chamber2->GetXaxis()->CenterTitle();

			chamber2->GetYaxis()->SetTitle("Intensity");
			chamber2->GetYaxis()->SetTitleOffset(1.4);
			chamber2->GetYaxis()->CenterTitle();

			pc2->cd(3);
			chamber3->Draw();
			chamber3->GetXaxis()->SetTitle("X position (px)");
			chamber3->GetXaxis()->CenterTitle();

			chamber3->GetYaxis()->SetTitle("Intensity");
			chamber3->GetYaxis()->SetTitleOffset(1.4);
			chamber3->GetYaxis()->CenterTitle();

			pc2->cd(4);
			chamber4->Draw();
			chamber4->GetXaxis()->SetTitle("X position (px)");
			chamber4->GetXaxis()->CenterTitle();

			chamber4->GetYaxis()->SetTitle("Intensity");
			chamber4->GetYaxis()->SetTitleOffset(1.4);
			chamber4->GetYaxis()->CenterTitle();

			//TFile myF("trackTree.root","RECREATE");
			

			//loop over all data in chain
			Int_t nevent = chain->GetEntries();	//get the number of entries in the TChain
			for (Int_t i=0;i<nevent;i++) {
				chain->GetEntry(i);

				//put the frame data into the histogram for this event
				for(int x=0;x<width;x++){
					for(int y=0;y<height;y++){
						if(frame[x][y]>0){
							frameHisto->Fill(x,y,frame[x][y]);
							if(y>580 && y<610){
								chamber1->Fill(x,frame[x][y]);
								chamber1y->Fill(y,frame[x][y]);
							}
							else if(y>400 && y<440){
								chamber2->Fill(x,frame[x][y]);
								chamber2y->Fill(y,frame[x][y]);
							}
							else if(y>240 && y<280){
								chamber3->Fill(x,frame[x][y]);
								chamber3y->Fill(y,frame[x][y]);
							}
							else if(y>50 && y<100){
								chamber4->Fill(x,frame[x][y]);
								chamber4y->Fill(y,frame[x][y]);
							}
						}	
					}
				}

				double x12[2];
				double y12[2];
				double x34[2];
				double y34[2];

				x12[0] = chamber1->GetMean();
				y12[0] = chamber1y->GetMean();			//593.3;
				x12[1] = chamber2->GetMean();
				y12[1] = chamber2y->GetMean();			//424.7;
				x34[0] = chamber3->GetMean();
				y34[0] = chamber3y->GetMean();			//262.5;
				x34[1] = chamber4->GetMean();
				y34[1] = chamber4y->GetMean();			//69.33;

				cout << "Chamber1x: " << chamber1->GetMean() << endl;
				cout << "Chamber1y: " << chamber1y->GetMean() << endl;
				cout << "Chamber2x: " << chamber2->GetMean() << endl;
				cout << "Chamber2y: " << chamber2y->GetMean() << endl;
				cout << "Chamber3x: " << chamber3->GetMean() << endl;
				cout << "Chamber3y: " << chamber3y->GetMean() << endl;
				cout << "Chamber4x: " << chamber4->GetMean() << endl;
				cout << "Chamber4y: " << chamber4y->GetMean() << endl;

				pc2->cd(1);
				chamber1->Draw();
				gPad->Update();
				
				pc2->cd(2);
				chamber2->Draw();
				gPad->Update();
				
				pc2->cd(3);
				chamber3->Draw();
				gPad->Update();
				
				pc2->cd(4);
				chamber4->Draw();
				gPad->Update();
				
				fH2->cd();
				frameHisto->Draw();
				gPad->Update();

				//wait for user input to advance to next event
				cout << "Frame Number=" << pNum<<endl;
				cout << "Press enter to advance to the next frame" << endl;
				cin.ignore();
				
				//clear the old frame from the histogram
				frameHisto->Reset();
				chamber1->Reset();
				chamber2->Reset();
				chamber3->Reset();
				chamber4->Reset();
			}
		} else break;
	}
}
Exemplo n.º 21
0
Arquivo: Zlumi.C Projeto: cms-ts/Histo
void Zlumi::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L Zlumi.C
//      Root > Zlumi t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
 
 gROOT->ForceStyle();
        tdrStyle();

  if (fChain == 0) return;

int minRun=0;
int maxRun=0;
int maxLS=0;
bool forminRun=true;


//TH2I * LumiSRun = new TH2I("LumiSRun", "LS vs Run", 3000, 0., 3000., 20000, 160000., 180000.);
//TH1I * test2 = new TH1I("test2","test2", 3000,0, 3000);


Long64_t nentries = fChain->GetEntriesFast();

Long64_t nbytes = 0, nb = 0;
for (Long64_t jentry=0; jentry<nentries;jentry++) {
	Long64_t ientry = LoadTree(jentry);
	if (ientry < 0) break;
	nb = fChain->GetEntry(jentry);   nbytes += nb;


	if(forminRun && (Run!=0)){minRun=Run; forminRun=false;}
	if((Run!=0) && (Run>maxRun)){maxRun=Run;}
	if((LS!=0) && (LS>maxLS)){maxLS=LS;}
	//printf("run %i ls %i \n",Run,LS);
}
cout << nentries << " nentries \n";

TH2I *LumiSRun = new TH2I("LumiSRun", "LS vs Run", maxLS, 0, maxLS, maxRun-minRun+2, minRun-1, maxRun+1);
TH1I *Runs = new TH1I("Runs","Run", maxRun-minRun+2, minRun-1, maxRun+1);
 Runs->Sumw2();
nbytes = 0; nb = 0;
for (Long64_t jentry=0; jentry<nentries;jentry++) {
	Long64_t ientry = LoadTree(jentry);
	if (ientry < 0) break;
	nb = fChain->GetEntry(jentry);   nbytes += nb;

	LumiSRun->Fill(LS,Run);
	//printf("run %i ls %i \n",Run,LS);
	Runs->Fill(Run);
	//test2->Fill(LS);
}
	printf("minRun %i maxRun %i \n",minRun,maxRun);
LumiSRun->Draw();
 for (int h=0;h<Runs->GetNbinsX();h++){
   Runs->SetBinError(h+1,sqrt(Runs->GetBinContent(h+1)) );
 }
Runs->Draw();
//test->Draw();
//test2->Draw();

TH1F *FileRuns = new TH1F("FileRuns","Run from Lumicalc", maxRun-minRun+2, minRun-1, maxRun+1);
TH1D *XsecDistro = new TH1D("XsecDistro","X sec distribution", 60, 0., 0.6);
//-------------
   const Int_t mpt = maxRun-minRun;
   int fileRun[mpt];
   double Lumi[mpt];

   int npt = 0;
   // read data file
   ifstream file;
   //file.open("./2011-run-lumi.txt");
   file.open("./LumiAeB-dav.txt");
   while (1) {

	   file >> fileRun[npt] >> Lumi[npt];
	   if ( ! file.good() ) break;
	   cout << "x = " << fileRun[npt] << " y = " << Lumi[npt] << endl;
	   
	   FileRuns->SetBinContent((fileRun[npt]-minRun+2),0.2);
	   npt++;
   }

   file.close();
   printf("found %d Runs in file \n", npt);

bool flaggg=1;
TH1D *LumiRuns = new TH1D("LumiRuns","Zyield vs Run", maxRun-minRun+2, minRun-1, maxRun+1);
 LumiRuns->Sumw2();
for(int i=0; i<npt;i++){
	for(int j=0;j<maxRun;j++){
		if(fileRun[i]==(minRun+j)){
		  cout << fileRun[i]-minRun+1 <<" "<< ((float)Runs->GetBinContent(j+1))/Lumi[i] <<" "<< Lumi[i] << " matched run \n";
		if(Lumi[i]>0.&&Runs->GetBinContent(j+2)>0.){
			LumiRuns->SetBinContent(fileRun[i]-minRun+2,(((double)Runs->GetBinContent(j+2))/Lumi[i])*1000);
			LumiRuns->SetBinError(fileRun[i]-minRun+2,((TMath::Sqrt((double)Runs->GetBinContent(j+2)))/Lumi[i])*1000);
			XsecDistro->Fill((((double)Runs->GetBinContent(j+2))/Lumi[i])*1000);
		flaggg=false;
		}
		}
		else if(fileRun[i]==(minRun+j) && (Runs->GetBinContent(j+2+1)>0. || Runs->GetBinContent(j+2-1)>0.)) cout << "Son cazzi " << fileRun[i]<<"\n";
	}
	if(flaggg) {
	//cout << " ---------------- \n";
	cout << fileRun[i] << " Run not matched! \n";
	//cout << Runs->GetBinContent(i) <<" " << Runs->GetBinContent(i+1) <<" " << Runs->GetBinContent(i+2) <<" "<< Lumi[i] << " probably not empty \n";
	//if(Lumi[i]>1.e+06) cout << "ALERT THIS ONE IS GOOD \n";
	}
	flaggg=true;
}

TCanvas * Canv = (TCanvas*)gDirectory->GetList()->FindObject("Canv");
if (Canv) delete Canv;
Canv = new TCanvas("Canv","Canv",0,0,800,600);
Canv->cd();
LumiRuns->SetXTitle("Run");
LumiRuns->SetYTitle("#sigma (nb)");
LumiRuns->SetLineColor(kBlack);
LumiRuns->Draw("E1");
Runs->SetLineColor(kRed);
//Runs->Draw("SAMES");
FileRuns->SetLineColor(kBlue);
//FileRuns->Draw("SAMES");
//LumiRuns->Draw("E1 SAMES");
Canv->Print("ratio_zlumi.eps");

TCanvas * Another = (TCanvas*)gDirectory->GetList()->FindObject("Another");
if (Another) delete Another;
Another = new TCanvas("Another","Another",0,0,800,600);
Another->cd();
XsecDistro->SetXTitle("#sigma (nb)");
XsecDistro->SetLineColor(kBlack);
XsecDistro->Draw();
Another->Print("distrib_zsigma.eps");

/*
  //-------------
  // per il momento tengo le due sezioni separate... solo per debuggare meglio...
  //-------------
   const Int_t rpt = 120000;
   int lsRun[rpt];
   float LuSec[rpt];

   npt = 0;
   // read data file
   ifstream in;
   in.open("./2011-LS.txt");
   while (1) {

	   in >> lsRun[npt] >> LuSec[npt];
	   if ( ! in.good() ) break;
	   //cout << "x = " << fileRun[npt] << " y = " << Lumi[npt] << endl;
	   npt++;
   }

   in.close();
   printf("found %d LS\n", npt);
*/
}