Ejemplo n.º 1
0
/*
-- FUNCTION: receiveFile
--
-- DATE: September 23, 2011
--
-- REVISIONS:
--
-- DESIGNER: Karl Castillo
--
-- PROGRAMMER: Karl Castillo
--
-- INTERFACE: void receiveFile(int port, const char* fileName)
--				socket - the current socket the client is connected as
--				fileName - the name of the file to be received/downloaded
--
-- RETURNS: void
--
-- NOTES:
-- This function sends the receive command and waits for the reply of the 
-- transfer server. The transfer server will reply with the contents of the
-- file. If the file is not present, the server will return an error message.
-- This error message will be printed out.
--
-- Once all the contents of the file are received and written to a file, the
-- program will print out a success message.
*/
void receiveFile(int port, const char* fileName)
{
	char* buffer = (char*)malloc(sizeof(char) * BUFFER_LENGTH);
	FILE* file = NULL;
	off_t fileSize = 0;
	int bytesRead = 0;
	int count = 0;
	int transferSocket = 0;
	char* fileNamePath = (char*)malloc(sizeof(char) * FILENAME_MAX);
	
	initalizeServer(&port, &transferSocket);
	
	// Get Size of file
	readData(&transferSocket, buffer, BUFFER_LENGTH);
	memmove((void*)&fileSize, buffer, sizeof(off_t));
	printf("Size of File: %d\n", (int)fileSize);
	
	// Create file path
	sprintf(fileNamePath, "%s%s", DEF_DIR, fileName);
    printf("Save Path: %s\n", fileNamePath);
	
	// Opening file for writing
	if((file = fopen(fileNamePath, "wb")) == NULL) {
		fprintf(stderr, "Error opening file: %s\n", fileName);
		return;
	}
	
	// Hide Cursor
	fprintf(stderr, "\033[?25l");
	
	// Start Reading from socket
	while (count < (fileSize - BUFFER_LENGTH)) {
        bytesRead = readData(&transferSocket, buffer, BUFFER_LENGTH);
        fwrite(buffer, sizeof(char), bytesRead, file);
        count += bytesRead;
        printProgressBar(fileSize, count);
    }
	
	bytesRead = readData(&transferSocket, buffer, fileSize - count);
	printProgressBar(fileSize, count + bytesRead);
    fwrite(buffer, sizeof(char), bytesRead, file);
	// End Reading from socket
	
	// Show Cursor
	fprintf(stderr, "\033[?25h\n");
	
	// Close file
	fclose(file);
	
	chmod(fileName, 00400 | 00200 | 00100);
    
    // Free memory allocated for buffer
    free(buffer);
    
    // Print Success message
    printf("Transfer Complete!\n");
}
Ejemplo n.º 2
0
int readFile(int port)
{
	ControlPacket packet;
	while(!getControlPacket(port, &packet)){}
	//puts("\nGot beginning packet");
	if(packet.end != CONTROL_PACKET_BEGIN){
		printf("Error: didn't receive expected start control package\n");
		return -1;
	}

	int file = open(packet.filename+1, O_CREAT|O_TRUNC|O_WRONLY, 0666);
	free(packet.filename);
	DataPacket dataPacket;
	unsigned char expectedSequenceNumber = 0;
	float percentage;
	int acum = 0;
	char * proBar = updateProgressBar(0, packet.size, &percentage);
	while(getDataPacket(port, &dataPacket) != E_NOTDATA){

		if (expectedSequenceNumber != dataPacket.sequenceNumber){
			printf("Error in packet sequence: expected packet no %u and got packet no %u\n", expectedSequenceNumber, dataPacket.sequenceNumber);
		exit(-1);
		}
		expectedSequenceNumber++;
		expectedSequenceNumber %= 255;
		
		//printf("Received data packet with size %d\n", dataPacket.size);
		write(file, dataPacket.data, dataPacket.size);
		acum += dataPacket.size;
		proBar = updateProgressBar(acum, packet.size, &percentage);
		if(visMode != 0)
			printProgressBar(proBar, percentage);
		free(dataPacket.data);

	}
	printf("\n");
	unsigned char* dump;
	while(llread(port, &dump) != E_CLOSED){}	
	//puts("discei");
	return 0;
}
int main (int argc, char *argv[])
{

  printBoxedMessage("Starting plot generation");

  // ####################
  // ##   Init tools   ##
  // ####################

     // Create a sonic Screwdriver
      SonicScrewdriver screwdriver;

     // ##########################
     // ##   Create Variables   ##
     // ##########################

     screwdriver.AddVariable("MT",             "M_{T}",                   "GeV",    40,0,400,       &(myEvent.MT),                    "logY");

     // #########################################################
     // ##   Create ProcessClasses (and associated datasets)   ##
     // #########################################################

        screwdriver.AddProcessClass("1ltop", "1l top",                             "background",kRed-7);
            #ifdef USING_TTBAR_POWHEG
                screwdriver.AddDataset("ttbar_powheg",                "1ltop",  0, 0);
            #endif
            #ifdef USING_TTBAR_MADGRAPH
                screwdriver.AddDataset("ttbar_madgraph_1l",             "1ltop",  0, 0);
            #endif
            //screwdriver.AddDataset("ttbar_madgraph_scaledown",    "1ltop",  0, 0);
            //screwdriver.AddDataset("ttbar_madgraph_scaleup",      "1ltop",  0, 0);
            //screwdriver.AddDataset("ttbar_madgraph_matchingdown", "1ltop",  0, 0);
            //screwdriver.AddDataset("ttbar_madgraph_matchingup",   "1ltop",  0, 0);
            //screwdriver.AddDataset("ttbar_madgraph_mass166-5",    "1ltop",  0, 0);
            //screwdriver.AddDataset("ttbar_madgraph_mass178-5",    "1ltop",  0, 0);

            screwdriver.AddDataset("singleTop_st",                  "1ltop",  0, 0);


     screwdriver.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);
            #ifdef USING_TTBAR_MADGRAPH
                screwdriver.AddDataset("ttbar_madgraph_2l",   "ttbar_2l",  0, 0);
            #endif


     screwdriver.AddProcessClass("W+jets",   "W+jets",                          "background",kOrange-2);
             screwdriver.AddDataset("W+jets",    "W+jets", 0, 0);

     screwdriver.AddProcessClass("rare",   "rare",                              "background",kMagenta-5);
             screwdriver.AddDataset("rare",   "rare", 0, 0);

     screwdriver.AddProcessClass("data",   "data",                              "data",COLORPLOT_BLACK);
            screwdriver.AddDataset("SingleElec",   "data", 0, 0);
            screwdriver.AddDataset("SingleMuon",   "data", 0, 0);
            screwdriver.AddDataset("DoubleElec",   "data", 0, 0);
            screwdriver.AddDataset("DoubleMuon",   "data", 0, 0);
            screwdriver.AddDataset("MuEl",         "data", 0, 0);

     // ##########################
     // ##    Create Regions    ##
     // ##########################

     screwdriver.AddRegion("0btag_noMTCut",         "Preselection;0 b-tag Control Region, no M_{T} cut",    &goesIn0BtagControlRegion          );

     // ##########################
     // ##   Create Channels    ##
     // ##########################

     screwdriver.AddChannel("singleLepton", "e/#mu-channels",            &goesInSingleLeptonChannel);

  // ########################################
  // ##       Create histograms and        ##
  // ##  schedule type of plots to produce ##
  // ########################################

     // Create histograms
     screwdriver.Create1DHistos();

     // Schedule plots
     screwdriver.SchedulePlots("1DDataMCComparison");

     // Config plots

     screwdriver.SetGlobalStringOption("DataMCComparison",  "includeSignal",                    "stack");
     screwdriver.SetGlobalFloatOption ("DataMCComparison",  "factorSignal",                     1.0    );

     screwdriver.SetGlobalStringOption("Plot", "infoTopRight", "CMS Preliminary");
     screwdriver.SetGlobalStringOption("Plot", "infoTopLeft",  "#sqrt{s} = 8 TeV, L = 19.5 fb^{-1}");

     screwdriver.SetGlobalBoolOption("Plot", "exportPdf", true);
     screwdriver.SetGlobalBoolOption("Plot", "exportEps", false);
     screwdriver.SetGlobalBoolOption("Plot", "exportPng", false);

  // ########################################
  // ##       Run over the datasets        ##
  // ########################################

  vector<string> datasetsList;
  screwdriver.GetDatasetList(&datasetsList);

  cout << "   > Reading datasets... " << endl;
  cout << endl;

    Table scaleFactors = Table("../prediction/scaleFactors/preselection.tab");

    Figure SF_pre           = scaleFactors.Get("value","SF_pre");
    Figure SF_post          = scaleFactors.Get("value","SF_post");
    Figure SF_0btag         = scaleFactors.Get("value","SF_0btag");
    Figure SF_vetopeak      = scaleFactors.Get("value","SF_vetopeak");
    Figure SF_MTtail_1ltop  = scaleFactors.Get("value","SF_MTtail_1ltop");
    Figure SF_MTtail_Wjets  = scaleFactors.Get("value","SF_MTtail_Wjets");

  for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
  {
     string currentDataset = datasetsList[d];
     string currentProcessClass = screwdriver.GetProcessClass(currentDataset);

     sampleName = currentDataset;
     sampleType = screwdriver.GetProcessClassType(currentProcessClass);

     // Open the tree
     TFile f((string(FOLDER_BABYTUPLES)+currentDataset+".root").c_str());
     TTree* theTree = (TTree*) f.Get("babyTuple");

     intermediatePointers pointers;
     InitializeBranchesForReading(theTree,&myEvent,&pointers);

     myEvent.mStop       = -1;
     myEvent.mNeutralino = -1;

  // ########################################
  // ##        Run over the events         ##
  // ########################################

     bool ttbarDatasetToBeSplitted = false;
      if (findSubstring(currentDataset,"ttbar")
      && (currentDataset != "ttbar_madgraph_1l")
      && (currentDataset != "ttbar_madgraph_2l"))
          ttbarDatasetToBeSplitted = true;

      int nEntries = theTree->GetEntries();
      for (int i = 0 ; i < nEntries ; i++)
      {
          if (i % (nEntries / 50) == 0) printProgressBar(i,nEntries,currentDataset);

          // Get the i-th entry
          ReadEvent(theTree,i,&pointers,&myEvent);

          float weight = getWeight();

          // Split 1-lepton ttbar and 2-lepton ttbar
          string currentProcessClass_ = currentProcessClass;
          if (ttbarDatasetToBeSplitted && (myEvent.numberOfGenLepton == 2))
              currentProcessClass_ = "ttbar_2l";

          if (myEvent.MT > 100)
          {
                   if (currentProcessClass_ == "1ltop" ) weight *= SF_MTtail_1ltop.value();
              else if (currentProcessClass_ == "W+jets") weight *= SF_MTtail_Wjets.value();
          }

          screwdriver.AutoFillProcessClass(currentProcessClass_,weight);
      }

      printProgressBar(nEntries,nEntries,currentDataset);
      cout << endl;
      f.Close();

  }

    // #############################
    // ##   Apply scale factors   ##
    // #############################

    screwdriver.ApplyScaleFactor("W+jets",   "0btag_noMTCut",        "singleLepton", SF_0btag);
    screwdriver.ApplyScaleFactor("1ltop",    "0btag_noMTCut",        "singleLepton", SF_0btag);

  // ###################################
  // ##   Make plots and write them   ##
  // ###################################

  cout << endl;
  cout << "   > Making plots..." << endl;
  screwdriver.MakePlots();
  cout << "   > Saving plots..." << endl;
  screwdriver.WritePlots("./plots/fullMTwithSFRinTail/");

  printBoxedMessage("Plot generation completed");

  // #############################
  // ##   Post-plotting tests   ##
  // #############################

  printBoxedMessage("Program done.");
  return (0);
}
int main (int argc, char *argv[])
{
    //loadBDTSignalRegions();

    printBoxedMessage("Starting tables generation");

    // ####################
    // ##   Init tools   ##
    // ####################

        // Create a sonic Screwdriver
        SonicScrewdriver screwdriver;

    // #########################################################
    // ##   Create ProcessClasses (and associated datasets)   ##
    // #########################################################
	/*
        screwdriver.AddProcessClass("1ltop", "1l top",                             "background",kRed-7);
            #ifdef USING_TTBAR_POWHEG
                screwdriver.AddDataset("ttbar_powheg",                "1ltop",  0, 0);
            #endif
            #ifdef USING_TTBAR_MADGRAPH
                screwdriver.AddDataset("ttbar_madgraph_1l",             "1ltop",  0, 0);
            #endif
            screwdriver.AddDataset("singleTop_st",                  "1ltop",  0, 0);


        screwdriver.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);
            #ifdef USING_TTBAR_MADGRAPH
                screwdriver.AddDataset("ttbar_madgraph_2l",   "ttbar_2l",  0, 0);
            #endif

        screwdriver.AddProcessClass("W+jets",   "W+jets",                          "background",kOrange-2);
            screwdriver.AddDataset("W+jets",    "W+jets", 0, 0);

        screwdriver.AddProcessClass("rare",   "rare",                              "background",kMagenta-5);
            screwdriver.AddDataset("rare",   "rare", 0, 0);

        screwdriver.AddProcessClass("data",   "data",                              "data",COLORPLOT_BLACK);
            screwdriver.AddDataset("SingleElec",   "data", 0, 0);
            screwdriver.AddDataset("SingleMuon",   "data", 0, 0);
            screwdriver.AddDataset("DoubleElec",   "data", 0, 0);
            screwdriver.AddDataset("DoubleMuon",   "data", 0, 0);
            screwdriver.AddDataset("MuEl",         "data", 0, 0);
	*/
        //screwdriver.AddProcessClass("signal",            "signal",                "background",kMagenta-5);
           // screwdriver.AddDataset("T2tt_650_325", "signal", 0, 0);
        screwdriver.AddProcessClass("W+jets",   "W+jets",                          "background",kOrange-2);
            screwdriver.AddDataset("T2tt_650_325", "W+jets", 0, 0);


    // ##########################
    // ##    Create Regions    ##
    // ##########################

        screwdriver.AddRegion("presel_MTpeak",          "Preselection (MT peak)",      &goesInMTpeak);
        screwdriver.AddRegion("presel_MTtail",          "Preselection (MT peak)",      &goesInMTtail);


    // ##########################
    // ##   Create Channels    ##
    // ##########################

        //screwdriver.AddChannel("singleLepton", "e/#mu-channels",  &goesInSingleLeptonChannel);
        screwdriver.AddChannel("singleElec",   "e-channel",       &goesInSingleElecChannel  );
        screwdriver.AddChannel("singleMuon",   "#mu-channel",     &goesInSingleMuonChannel  );

        /*
        screwdriver.AddChannel("doubleLepton", "2l-channel",      &goesInDoubleLeptonChannel);
        screwdriver.AddChannel("doubleElec",   "ee-channel",      &goesInDoubleElecChannel  );
        screwdriver.AddChannel("doubleMuon",   "#mu#mu-channel",  &goesInDoubleMuonChannel  );
        screwdriver.AddChannel("emu",          "e#mu-channel",    &goesInMuonElecChannel    );
        */

        screwdriver.AddChannel("allChannels",  "",                &goesInAnyChannel         );

    // ########################################
    // ##       Create histograms and        ##
    // ##  schedule type of plots to produce ##
    // ########################################

        // Create histograms
        screwdriver.Create1DHistos();

    // ########################################
    // ##       Run over the datasets        ##
    // ########################################

        vector<string> datasetsList;
        screwdriver.GetDatasetList(&datasetsList);

        cout << "   > Reading datasets... " << endl;
        cout << endl;

        for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
        {
            string currentDataset = datasetsList[d];
            string currentProcessClass = screwdriver.GetProcessClass(currentDataset);

            sampleName = currentDataset;
            sampleType = screwdriver.GetProcessClassType(currentProcessClass);

            // Open the tree
            string treePath = string(FOLDER_BABYTUPLES)+currentDataset+".root";
            TFile f(treePath.c_str());
            TTree* theTree = (TTree*) f.Get("babyTuple");

            InitializeBranchesForReading(theTree,&myEvent);

        // ########################################
        // ##        Run over the events         ##
        // ########################################

            bool ttbarDatasetToBeSplitted = false;
            if (findSubstring(currentDataset,"ttbar")
            && (currentDataset != "ttbar_madgraph_1l")
            && (currentDataset != "ttbar_madgraph_2l"))
                ttbarDatasetToBeSplitted = true;

            int nEntries = theTree->GetEntries();
            for (int i = 0 ; i < nEntries ; i++)
            {
                if (i % (nEntries / 50) == 0) printProgressBar(i,nEntries,currentDataset);

                // Get the i-th entry
                //ReadEvent(theTree,i,&pointers,&myEvent);
                //cout<<"can I read the event ?"<<endl;
		ReadEvent(theTree,i,&myEvent);
		//cout<<"> Yes I can !"<<endl;

         	if(goesInPreselection() && goesInAnyChannel()){
		cout<<myEvent.MT<<" "<<myEvent.pfmet<<" "<<myEvent.ngoodleps<<" "<<myEvent.ngoodjets<<endl;
		cout<<"preselection: "<<goesInPreselection()<<endl;
		cout<<"all channel"<< goesInAnyChannel() <<  endl;
		}
		//cout<<""<< <<  endl;
		//cout<<""<< <<  endl;
		//cout<<""<< <<  endl;
	 	float weight = getWeight();

                // Split 1-lepton ttbar and 2-lepton ttbar
                string currentProcessClass_ = currentProcessClass;
                if (ttbarDatasetToBeSplitted && (myEvent.genlepsfromtop == 2))
                    currentProcessClass_ = "ttbar_2l";

                screwdriver.AutoFillProcessClass(currentProcessClass_,weight);

            }
            printProgressBar(nEntries,nEntries,currentDataset);
            cout << endl;
            f.Close();

        }

        // ####################################
        // ##        Write the table         ##
        // ####################################

        printBoxedMessage("Writing the table ... ");

        vector<string> regions  = { 
				    "presel_MTpeak", "presel_MTtail",
				    /*
				    "preveto_MTpeak",      "preveto_MTtail",
                                    "signalRegion_MTpeak", "signalRegion_MTtail",
                                    "0btag_MTpeak",        "0btag_MTtail",
                                    "reversedVeto_MTpeak", "reversedVeto_MTtail",
                                    "2leptons", "2leptons_MTpeak", "2leptons_MTtail",
                                  */};

        string exportFile = "rawYieldTables/"+string(SIGNAL_REGION_TAG)+".tab";
        TableDataMC(&screwdriver,regions,"allChannels").Print(exportFile,4);

        vector<string> secondLeptonInAcceptanceRegions  = {
                                                              "preveto_MTtail",
                                                              "secondLeptonInAcceptance",
                                                              "singleTrack",
                                                              "hadronicTau"
                                                          };

        //string exportFile2 = "secondLeptonInAcceptance/"+string(SIGNAL_REGION_TAG)+".tab";
        //TableDataMC(&screwdriver,secondLeptonInAcceptanceRegions,"allChannels").Print(exportFile2,4);

        printBoxedMessage("Table generation completed");

        return (0);
}
int main (int argc, char *argv[])
{

  printBoxedMessage("Starting plot generation");

  // ####################
  // ##   Init tools   ##
  // ####################
 
     string signalCategory = "T2bw-025";

     // Create a sonic Screwdriver
      SonicScrewdriver screwdriver;

  // ##########################
  // ##   Create Variables   ##
  // ##########################

     screwdriver.AddVariable("METoverSqrtHT",  "MET / #sqrt{H_{T}}",      "",       32,0,32,         &(myEvent.METoverSqrtHT),       "");
     screwdriver.AddVariable("MET",            "MET",                     "GeV",    15,50,500,       &(myEvent.MET),                 "logY=true");
     screwdriver.AddVariable("MT",             "MT",                      "GeV",    20,0,400,        &(myEvent.MT),                  "logY=true");
     screwdriver.AddVariable("leadingBPt",     "p_{T}(leading b jet)",    "GeV",    20,0,200,        &(myEvent.leadingBPt),          "logY=true");
     
     screwdriver.AddVariable("mStop",          "m_{#tilde{t}}",           "GeV",    28,112.5,812.5,  &(myEvent.mStop),               "");
     screwdriver.AddVariable("mNeutralino",    "m_{#chi^{0}}",            "GeV",    16,-12.5,387.5,  &(myEvent.mNeutralino),         "noOverflowInLastBin");
     
     // #########################################################
     // ##   Create ProcessClasses (and associated datasets)   ##
     // #########################################################

     screwdriver.AddProcessClass("1ltop",                        "1l top", "background",kRed-7);
         #ifdef USING_TTBAR_POWHEG
             screwdriver.AddDataset("ttbar_powheg",              "1ltop",  0, 0);
         #endif
         #ifdef USING_TTBAR_MADGRAPH
             screwdriver.AddDataset("ttbar_madgraph_1l",         "1ltop",  0, 0);
         #endif
         screwdriver.AddDataset("singleTop_st",                  "1ltop",  0, 0);


     screwdriver.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);
         #ifdef USING_TTBAR_MADGRAPH
             screwdriver.AddDataset("ttbar_madgraph_2l",   "ttbar_2l",  0, 0);
         #endif

     screwdriver.AddProcessClass("W+jets",         "W+jets",                    "background", kOrange-2);
             screwdriver.AddDataset("W+jets",      "W+jets", 0, 0);
                                                   
     screwdriver.AddProcessClass("rare",           "rare",                      "background", kMagenta-5);
             screwdriver.AddDataset("rare",        "rare", 0, 0);
                                                   
     screwdriver.AddProcessClass(signalCategory,    signalCategory,             "signal",     kViolet-1);
             screwdriver.AddDataset(signalCategory, signalCategory,   0, 0);

     screwdriver.AddProcessClass("signal_250_100",  signalCategory+" (250/100)",      "signal",COLORPLOT_BLUE   );
     screwdriver.AddProcessClass("signal_450_100",  signalCategory+" (450/100)",      "signal",COLORPLOT_GREEN2 ); 
     screwdriver.AddProcessClass("signal_400_175",  signalCategory+" (400/175)",      "signal",COLORPLOT_GREEN2 ); 
     screwdriver.AddProcessClass("signal_650_100",  signalCategory+" (650/100)",      "signal",COLORPLOT_GREEN  );

  // ##########################
  // ##    Create Regions    ##
  // ##########################

     screwdriver.AddRegion("presel",             "Preselection",                          &goesInPreselectionMTtail);
/*
     screwdriver.AddRegion("veryOffShell_loose", "Cut-and-count;Very off-shell (loose)",  &Selector_veryOffShell_loose);
     screwdriver.AddRegion("offShell_loose",     "Cut-and-count;Off-shell (loose)",       &Selector_offShell_loose );
     screwdriver.AddRegion("lowDeltaM_tight",    "Cut-and-count;Low #DeltaM (tight)",     &Selector_lowDeltaM_tight );
     screwdriver.AddRegion("highDeltaM",         "Cut-and-count;High #DeltaM",            &Selector_highDeltaM );
*/
     
     screwdriver.AddRegion("offshell",           "Cut-and-count;Off-shell",              &Selector_offShell);
     screwdriver.AddRegion("lowMasses",          "Cut-and-count;Low masses",             &Selector_lowMasses);
     screwdriver.AddRegion("highMasses",         "Cut-and-count;High masses",            &Selector_highMasses);
     

  // ##########################
  // ##   Create Channels    ##
  // ##########################
      
     screwdriver.AddChannel("singleLepton", "e/#mu-channels",  &goesInSingleLeptonChannel);

  // ########################################
  // ##       Create histograms and        ##
  // ##  schedule type of plots to produce ##
  // ########################################

     screwdriver.SetLumi(20000);

     // Create histograms
     screwdriver.Create1DHistos();
     screwdriver.Add2DHisto("mStop","mNeutralino");

     screwdriver.SetGlobalBoolOption  ("1DSuperimposed",   "includeSignal",                   true   );

     screwdriver.SetGlobalStringOption("1DStack",          "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("1DStack",          "factorSignal",                    1.0    );

     screwdriver.SetGlobalStringOption("DataMCComparison", "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("DataMCComparison", "factorSignal",                    1.0    );

     // Schedule plots
     screwdriver.SchedulePlots("1DSuperimposed");
     screwdriver.SchedulePlots("1DStack");
     screwdriver.SchedulePlots("2D");
     screwdriver.SchedulePlots("2DSuperimposed");

     // Config plots

     screwdriver.SetGlobalStringOption("Plot", "infoTopRight", "CMS Internal");
     screwdriver.SetGlobalStringOption("Plot", "infoTopLeft",  "#sqrt{s} = 8 TeV, L = 20 fb^{-1}");

     screwdriver.SetGlobalBoolOption("Plot", "exportPdf", true);
     screwdriver.SetGlobalBoolOption("Plot", "exportEps", false);
     screwdriver.SetGlobalBoolOption("Plot", "exportPng", false);

  // ########################################
  // ##       Run over the datasets        ##
  // ########################################

  vector<string> datasetsList;
  screwdriver.GetDatasetList(&datasetsList);

  cout << "   > Reading datasets... " << endl;
  cout << endl;

  for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
  {
     string currentDataset = datasetsList[d];
     string currentProcessClass = screwdriver.GetProcessClass(currentDataset); 
     // Open the tree
     TFile f((string(FOLDER_BABYTUPLES)+currentDataset+".root").c_str());
     TTree* theTree = (TTree*) f.Get("babyTuple"); 

     intermediatePointers pointers;
     InitializeBranchesForReading(theTree,&myEvent,&pointers);

     sampleName = currentDataset;
     sampleType = screwdriver.GetProcessClassType(currentProcessClass);
    
     if (currentDataset == signalCategory)
     {
         theTree->SetBranchAddress("mStop",       &(myEvent.mStop));
         theTree->SetBranchAddress("mNeutralino", &(myEvent.mNeutralino));
     }
     else
     {
         myEvent.mStop       = -1;
         myEvent.mNeutralino = -1;
     }

  // ########################################
  // ##        Run over the events         ##
  // ########################################

      int nEntries = theTree->GetEntries();
      for (int i = 0 ; i < nEntries ; i++)
      //for (int i = 0 ; i < min(200000, (int) theTree->GetEntries()); i++)
      {
          if (i % (theTree->GetEntries() / 50) == 0) 
              printProgressBar(i,nEntries,currentDataset);

          // Get the i-th entry
          ReadEvent(theTree,i,&pointers,&myEvent);

          // Split 1-lepton ttbar and 2-lepton ttbar
          string currentProcessClass_ = currentProcessClass;
          if ((currentDataset == "ttbar_powheg") && (myEvent.numberOfGenLepton == 2)) 
              currentProcessClass_ = "ttbar_2l";

          screwdriver.AutoFillProcessClass(currentProcessClass_,getWeight());

          if ((myEvent.mStop == 250) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_250_100",getWeight());
          if ((myEvent.mStop == 450) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_450_100",getWeight());
          if ((myEvent.mStop == 400) && (myEvent.mNeutralino == 175))
              screwdriver.AutoFillProcessClass("signal_400_175",getWeight());
          if ((myEvent.mStop == 650) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_650_100",getWeight());
      }

      printProgressBar(nEntries,nEntries,currentDataset);
      cout << endl;
      f.Close();

  }

  // ###################################
  // ##   Make plots and write them   ##
  // ###################################
 
  cout << endl;
  cout << "   > Making plots..." << endl;
  screwdriver.MakePlots();
  cout << "   > Saving plots..." << endl;
  screwdriver.WritePlots("../plots/cutAndCount_performances/"+signalCategory+"/");

  printBoxedMessage("Plot generation completed");

  // #############################
  // ##   Post-plotting tests   ##
  // #############################
  
  printBoxedMessage("Now computing misc tests ... ");
  
  /*
  vector<string> cutAndCountRegions =
  {
      "veryOffShell_loose",
      "offShell_loose",    
      "lowDeltaM_tight",   
      "highDeltaM"     
  };

  float SF_1ltop_and_Wjets = 2;
  float SF_allOthers       = 1.3;

  vector<float> globalBackgroundUncertainty =
  {
      0.2,
      0.2,
      0.2,
      0.4
  };
  */
  
  vector<string> cutAndCountRegions =
  {
    "presel",
    "offshell",
    "lowMasses",
    "highMasses"
  };

  float SF_1ltop_and_Wjets = 2;
  float SF_allOthers       = 1.3;

  vector<float> globalBackgroundUncertainty =
  {
      0.2,
      0.2,
      0.2
  };
  
  TableBackgroundSignal(&screwdriver,cutAndCountRegions,"singleLepton").Print();
  TableBackgroundSignal(&screwdriver,cutAndCountRegions,"singleLepton").PrintLatex();

  // ##########################
  // ##   Compute FOM maps   ##
  // ##########################

  vector<TH2F*> signalMaps;
  vector<TH2F*> FOMdiscoveryMaps;
  vector<TH2F*> FOMexclusionMaps;
  vector<TH2F*> efficiencies;

  int nBinsX = -1;
  int nBinsY = -1;

  TH2F* signalMapPresel  = screwdriver.get2DHistoClone("mStop","mNeutralino",signalCategory,"presel","singleLepton");
  TH2F* backgroundPresel = screwdriver.get2DCompositeHistoClone("mStop","mNeutralino","2DSumBackground","presel","singleLepton","");

  if (nBinsX == -1) nBinsX = signalMapPresel->GetNbinsX();
  if (nBinsY == -1) nBinsY = signalMapPresel->GetNbinsY();

  // Store background eff in (mStop,mLSP) = (200,300)
  int backgroundBin = signalMapPresel->FindBin(200,300);
  float backgroundYieldPresel = backgroundPresel->Integral(0,nBinsX+1,0,nBinsY+1);

  for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
  {
      signalMaps.push_back(screwdriver.get2DHistoClone("mStop","mNeutralino",signalCategory,cutAndCountRegions[i],"singleLepton"));
      signalMaps[i]->SetName((string("signalMap_")+cutAndCountRegions[i]).c_str());

      float B =   screwdriver.GetYieldAndError("1ltop",    cutAndCountRegions[i],"singleLepton").value()  * SF_1ltop_and_Wjets
                + screwdriver.GetYieldAndError("ttbar_2l", cutAndCountRegions[i],"singleLepton").value()  * SF_allOthers
                + screwdriver.GetYieldAndError("W+jets",   cutAndCountRegions[i],"singleLepton").value()  * SF_1ltop_and_Wjets
                + screwdriver.GetYieldAndError("rare",     cutAndCountRegions[i],"singleLepton").value()  * SF_allOthers;

      // Apply scale factor from background prediction
      float f_B = globalBackgroundUncertainty[i];
      //float f_B = 0.15;

      if (B < 1.0) B = 1.0;
 
      efficiencies.push_back((TH2F*) signalMaps[i]->Clone());
      efficiencies[i]->SetName((string("eff_")+cutAndCountRegions[i]).c_str());
      efficiencies[i]->Divide(signalMapPresel);
      efficiencies[i]->SetBinContent(backgroundBin,B/backgroundYieldPresel);
      
      FOMdiscoveryMaps.push_back((TH2F*) signalMaps[i]->Clone());
      FOMdiscoveryMaps[i]->SetName((string("FOMdisco_")+cutAndCountRegions[i]).c_str());

      FOMexclusionMaps.push_back((TH2F*) signalMaps[i]->Clone());
      FOMexclusionMaps[i]->SetName((string("FOMexclu_")+cutAndCountRegions[i]).c_str());

      for (int x = 1 ; x <= nBinsX ; x++)
      for (int y = 1 ; y <= nBinsY ; y++)
      {
          float S = signalMaps[i]->GetBinContent(x,y);

          float FOMdiscovery = figureOfMerit(S,B,"discovery",false,f_B);
          FOMdiscoveryMaps[i]->SetBinContent(x,y,FOMdiscovery);
          
          float FOMexclusion = figureOfMerit(S,B,"exclusion",false,f_B);
          FOMexclusionMaps[i]->SetBinContent(x,y,FOMexclusion);
      }

  }

  // ################################
  // ##   Compute "best" FOM map   ##
  // ################################

  TH2F* bestDiscoFOMMap = (TH2F*) signalMaps[0]->Clone();  bestDiscoFOMMap->SetName("bestDiscoFOM");
  TH2F* bestDiscoSetMap = (TH2F*) signalMaps[0]->Clone();  bestDiscoSetMap->SetName("bestDiscoSet");
  TH2F* bestDiscoSigEff = (TH2F*) signalMaps[0]->Clone();  bestDiscoSigEff->SetName("bestDiscoSigEff");
  TH2F* bestDiscoBkgEff = (TH2F*) signalMaps[0]->Clone();  bestDiscoBkgEff->SetName("bestDiscoBkgEff");
  
  TH2F* bestExcluFOMMap = (TH2F*) signalMaps[0]->Clone();  bestExcluFOMMap->SetName("bestExcluFOM");
  TH2F* bestExcluSetMap = (TH2F*) signalMaps[0]->Clone();  bestExcluSetMap->SetName("bestExcluSet");
  TH2F* bestExcluSigEff = (TH2F*) signalMaps[0]->Clone();  bestExcluSigEff->SetName("bestExcluSigEff");
  TH2F* bestExcluBkgEff = (TH2F*) signalMaps[0]->Clone();  bestExcluBkgEff->SetName("bestExcluBkgEff");
  
  for (int x = 1 ; x <= nBinsX ; x++)
  for (int y = 1 ; y <= nBinsY ; y++)
  {
      float bestDiscoFOM = -1.0;
      int   bestDiscoSet = 0;
      float bestDiscoSigEff_ = -1.0;
      float bestDiscoBkgEff_ = -1.0;
      for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
      {
          float DiscoFOM = FOMdiscoveryMaps[i]->GetBinContent(x,y);
          if (bestDiscoFOM < DiscoFOM)
          {
              bestDiscoFOM = DiscoFOM;
              if (bestDiscoFOM > 0) bestDiscoSet = i+1;
              bestDiscoSigEff_ = efficiencies[i]->GetBinContent(x,y);
              bestDiscoBkgEff_ = efficiencies[i]->GetBinContent(backgroundBin);
          }
      }
      bestDiscoFOMMap->SetBinContent(x,y,bestDiscoFOM);
      bestDiscoSetMap->SetBinContent(x,y,bestDiscoSet);
      bestDiscoSigEff->SetBinContent(x,y,bestDiscoSigEff_);
      bestDiscoBkgEff->SetBinContent(x,y,bestDiscoBkgEff_);

      float bestExcluFOM = -1.0;
      int   bestExcluSet = 0;
      float bestExcluSigEff_ = -1.0;
      float bestExcluBkgEff_ = -1.0;
      for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
      {
          float ExcluFOM = FOMexclusionMaps[i]->GetBinContent(x,y);
          if (bestExcluFOM < ExcluFOM)
          {
              bestExcluFOM = ExcluFOM;
              if (bestExcluFOM > 0) bestExcluSet = i+1;
              bestExcluSigEff_ = efficiencies[i]->GetBinContent(x,y);
              bestExcluBkgEff_ = efficiencies[i]->GetBinContent(backgroundBin);
          }
      }
      bestExcluFOMMap->SetBinContent(x,y,bestExcluFOM);
      bestExcluSetMap->SetBinContent(x,y,bestExcluSet);
      bestExcluSigEff->SetBinContent(x,y,bestExcluSigEff_);
      bestExcluBkgEff->SetBinContent(x,y,bestExcluBkgEff_);

  }

  // #########################
  // ##   Save those maps   ##
  // #########################

  float lineOffset = 0.0;
  string label;
  if (signalCategory == "T2tt"    ) { lineOffset = 172; label = "T2tt;";            }
  if (signalCategory == "T2bw-025") { lineOffset = 320; label = "T2bw (x = 0.25);"; }
  if (signalCategory == "T2bw-050") { lineOffset = 160; label = "T2bw (x = 0.50);"; }
  if (signalCategory == "T2bw-075") { lineOffset = 105; label = "T2bw (x = 0.75);"; }

  TFile fOutput(("../plots/cutAndCount_performances/"+signalCategory+"/custom.root").c_str(),"RECREATE");
  string pathExport = "../plots/cutAndCount_performances/"+signalCategory+"/";
  gStyle->SetPaintTextFormat("4.0f");
  formatAndWriteMapPlot(&screwdriver,bestDiscoSetMap,bestDiscoSetMap->GetName(),label+"Best set of cuts;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluSetMap,bestExcluSetMap->GetName(),label+"Best set of cuts;(for exclusion)",pathExport,lineOffset);
  gStyle->SetPaintTextFormat("4.1f");
  for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
  {
      FOMdiscoveryMaps[i]->SetMaximum(5.0);
      formatAndWriteMapPlot(&screwdriver,FOMdiscoveryMaps[i],FOMdiscoveryMaps[i]->GetName(),string("Discovery FOM for ")+cutAndCountRegions[i], pathExport,lineOffset);
      formatAndWriteMapPlot(&screwdriver,    efficiencies[i],    efficiencies[i]->GetName(),string("Efficiencies for " )+cutAndCountRegions[i], pathExport,lineOffset);
  }
  bestDiscoFOMMap->SetMaximum(5.0);
  bestExcluFOMMap->SetMaximum(5.0);
  formatAndWriteMapPlot(&screwdriver,bestDiscoFOMMap,bestDiscoFOMMap->GetName(),label+"Best FOM;(for discovery)"              ,pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestDiscoSigEff,bestDiscoSigEff->GetName(),label+"Best signal efficiency;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestDiscoBkgEff,bestDiscoBkgEff->GetName(),label+"Best backgr efficiency;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluFOMMap,bestExcluFOMMap->GetName(),label+"Best FOM;(for exclusion)"              ,pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluSigEff,bestExcluSigEff->GetName(),label+"Best signal efficiency;(for exclusion)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluBkgEff,bestExcluBkgEff->GetName(),label+"Best backgr efficiency;(for exclusion)",pathExport,lineOffset);
  fOutput.Close();

  printBoxedMessage("Program done.");
  return (0);
}
int main (int argc, char *argv[])
{
    // Loading standard BDT cuts
    loadBDTSignalRegions();

    // Replacing standard BDT cuts with cut allowing >=25% efficiency on the background
    // (goal is to have enough stat to perform the template fit)
    loadBDTCutsWithCustomRequirement("25percentEfficiency");

    printBoxedMessage("Starting plot generation");

    // ####################
    // ##   Init tools   ##
    // ####################

    // Create a sonic Screwdriver
    SonicScrewdriver screwdriver;

    // ##########################
    // ##   Create Variables   ##
    // ##########################


    screwdriver.AddVariable("Mlb",           "M'(lb)",    "GeV",  40,0,600,             &(myEvent.Mlb),    "");

    float Mlb_customBinning[3] = {0,150,600};
    screwdriver.AddVariable("Mlb_small",     "M'(lb)",    "GeV",  2, Mlb_customBinning, &(myEvent.Mlb),    "");
    screwdriver.AddVariable("M3b",           "M3b",       "GeV",  40,0,1000,            &(myEvent.M3b),    "");


    // To perform systematic study
    // (Note : JESup/down are not in skimmed babyTuples as for now)
    /*
    screwdriver.AddVariable("M3b_JESup",     "M3b_JESup",    "GeV",    40,0,1000,       &(myEvent.M3b_JESup),      "");
    screwdriver.AddVariable("M3b_JESdown",   "M3b_JESdown",  "GeV",    40,0,1000,       &(myEvent.M3b_JESdown),    "");
    screwdriver.AddVariable("Mlb_JESup",     "Mlb_JESup",    "GeV",    40,0,1000,       &(myEvent.Mlb_JESup),      "");
    screwdriver.AddVariable("Mlb_JESdown",   "Mlb_JESdown",  "GeV",    40,0,1000,       &(myEvent.Mlb_JESdown),    "");
    */

    int nJets;
    screwdriver.AddVariable("nJets", "Number of selected jets", "",  4, 4, 7,        &(nJets),                "");

    // #########################################################
    // ##   Create ProcessClasses (and associated datasets)   ##
    // #########################################################

    screwdriver.AddProcessClass("1ltop", "1l top",                             "background",kRed-7);
        #ifdef USING_TTBAR_POWHEG
            screwdriver.AddDataset("ttbar_powheg",                "1ltop",  0, 0);
        #endif
        #ifdef USING_TTBAR_MADGRAPH
            screwdriver.AddDataset("ttbar_madgraph_1l",             "1ltop",  0, 0);
        #endif
    //screwdriver.AddDataset("ttbar_madgraph_scaledown",    "1ltop",  0, 0);
    //screwdriver.AddDataset("ttbar_madgraph_scaleup",      "1ltop",  0, 0);
    //screwdriver.AddDataset("ttbar_madgraph_matchingdown", "1ltop",  0, 0);
    //screwdriver.AddDataset("ttbar_madgraph_matchingup",   "1ltop",  0, 0);
    //screwdriver.AddDataset("ttbar_madgraph_mass166-5",    "1ltop",  0, 0);
    //screwdriver.AddDataset("ttbar_madgraph_mass178-5",    "1ltop",  0, 0);

    screwdriver.AddDataset("singleTop_st",                  "1ltop",  0, 0);


    screwdriver.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);
        #ifdef USING_TTBAR_MADGRAPH
            screwdriver.AddDataset("ttbar_madgraph_2l",   "ttbar_2l",  0, 0);
        #endif

    screwdriver.AddProcessClass("W+jets",          "W+jets",                 "background",kOrange-2);
        screwdriver.AddDataset("W+jets",           "W+jets", 0, 0);

    screwdriver.AddProcessClass("rare",            "rare",                   "background",kMagenta-5);
        screwdriver.AddDataset("rare",             "rare", 0, 0);
        //screwdriver.AddDataset(SIGNAL_CONTAMINATION_INPUT, "rare", 0, 0);

    screwdriver.AddProcessClass("data",   "data",                              "data",COLORPLOT_BLACK);
        screwdriver.AddDataset("SingleElec",   "data", 0, 0);
        screwdriver.AddDataset("SingleMuon",   "data", 0, 0);

    // ##########################
    // ##    Create Regions    ##
    // ##########################

    screwdriver.AddRegion("MTpeak",              "MT peak Control Region;No b-tag requirement",      &goesInPreselNoBRequirementControlRegionMTinverted);
    screwdriver.AddRegion("presel_MTinverted",   "Preselection (MT < 100 GeV)",                      &goesInPreselectionMTinverted);
    screwdriver.AddRegion("presel_MTpeak",       "Preselection (MT peak)",                           &goesInPreselectionMTpeak);
    screwdriver.AddRegion("0btag",               "0 b-tag Control Region",                           &goesIn0BtagControlRegion);
    screwdriver.AddRegion("0btag_MTpeak",        "0 b-tag Control Region;MT peak",                   &goesIn0BtagControlRegionMTpeak);
    screwdriver.AddRegion("0btag_MTinverted",    "0 b-tag Control Region;MT < 100 GeV",              &goesIn0BtagControlRegionMTinverted);
    screwdriver.AddRegion("0btag_MTtail",        "0 b-tag Control Region;MT tail",                   &goesIn0BtagControlRegionMTtail);

    string rebinning;
    rebinning="rebin=2";
    screwdriver.AddRegion("BDT_MTtail_T2tt_1",    "", &BDT_MTtail_T2tt_1,    rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2tt_2",    "", &BDT_MTtail_T2tt_2,    rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2tt_5",    "", &BDT_MTtail_T2tt_5,    rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw075_1", "", &BDT_MTtail_T2bw075_1, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw075_2", "", &BDT_MTtail_T2bw075_2, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw075_3", "", &BDT_MTtail_T2bw075_3, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw075_5", "", &BDT_MTtail_T2bw075_5, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw050_1", "", &BDT_MTtail_T2bw050_1, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw050_3", "", &BDT_MTtail_T2bw050_3, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw050_4", "", &BDT_MTtail_T2bw050_4, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw050_5", "", &BDT_MTtail_T2bw050_5, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw050_6", "", &BDT_MTtail_T2bw050_6, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw025_1", "", &BDT_MTtail_T2bw025_1, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw025_3", "", &BDT_MTtail_T2bw025_3, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw025_4", "", &BDT_MTtail_T2bw025_4, rebinning);
    screwdriver.AddRegion("BDT_MTtail_T2bw025_6", "", &BDT_MTtail_T2bw025_6, rebinning);

    rebinning="rebin=4";
    screwdriver.AddRegion("BDT_MTpeak_T2tt_1",    "",  &BDT_MTpeak_T2tt_1   , rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2tt_2",    "",  &BDT_MTpeak_T2tt_2   , rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2tt_5",    "",  &BDT_MTpeak_T2tt_5   , rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw075_1", "",  &BDT_MTpeak_T2bw075_1, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw075_2", "",  &BDT_MTpeak_T2bw075_2, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw075_3", "",  &BDT_MTpeak_T2bw075_3, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw075_5", "",  &BDT_MTpeak_T2bw075_5, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw050_1", "",  &BDT_MTpeak_T2bw050_1, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw050_3", "",  &BDT_MTpeak_T2bw050_3, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw050_4", "",  &BDT_MTpeak_T2bw050_4, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw050_5", "",  &BDT_MTpeak_T2bw050_5, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw050_6", "",  &BDT_MTpeak_T2bw050_6, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw025_1", "",  &BDT_MTpeak_T2bw025_1, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw025_3", "",  &BDT_MTpeak_T2bw025_3, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw025_4", "",  &BDT_MTpeak_T2bw025_4, rebinning);
    screwdriver.AddRegion("BDT_MTpeak_T2bw025_6", "",  &BDT_MTpeak_T2bw025_6, rebinning);

    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2tt_1",     "",  &BDT_MTPeakNoBtag_T2tt_1   , rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2tt_2",     "",  &BDT_MTPeakNoBtag_T2tt_2   , rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2tt_5",     "",  &BDT_MTPeakNoBtag_T2tt_5   , rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw075_1",  "",  &BDT_MTPeakNoBtag_T2bw075_1, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw075_2",  "",  &BDT_MTPeakNoBtag_T2bw075_2, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw075_3",  "",  &BDT_MTPeakNoBtag_T2bw075_3, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw075_5",  "",  &BDT_MTPeakNoBtag_T2bw075_5, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw050_1",  "",  &BDT_MTPeakNoBtag_T2bw050_1, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw050_3",  "",  &BDT_MTPeakNoBtag_T2bw050_3, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw050_4",  "",  &BDT_MTPeakNoBtag_T2bw050_4, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw050_5",  "",  &BDT_MTPeakNoBtag_T2bw050_5, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw050_6",  "",  &BDT_MTPeakNoBtag_T2bw050_6, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw025_1",  "",  &BDT_MTPeakNoBtag_T2bw025_1, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw025_3",  "",  &BDT_MTPeakNoBtag_T2bw025_3, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw025_4",  "",  &BDT_MTPeakNoBtag_T2bw025_4, rebinning);
    screwdriver.AddRegion("BDT_MTPeakNoBtag_T2bw025_6",  "",  &BDT_MTPeakNoBtag_T2bw025_6, rebinning);

    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2tt_1",    "",  &BDT_MTPeakOneBtag_T2tt_1     , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2tt_2",    "",  &BDT_MTPeakOneBtag_T2tt_2     , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2tt_5",    "",  &BDT_MTPeakOneBtag_T2tt_5     , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw075_1", "",  &BDT_MTPeakOneBtag_T2bw075_1  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw075_2", "",  &BDT_MTPeakOneBtag_T2bw075_2  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw075_3", "",  &BDT_MTPeakOneBtag_T2bw075_3  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw075_5", "",  &BDT_MTPeakOneBtag_T2bw075_5  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw050_1", "",  &BDT_MTPeakOneBtag_T2bw050_1  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw050_3", "",  &BDT_MTPeakOneBtag_T2bw050_3  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw050_4", "",  &BDT_MTPeakOneBtag_T2bw050_4  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw050_5", "",  &BDT_MTPeakOneBtag_T2bw050_5  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw050_6", "",  &BDT_MTPeakOneBtag_T2bw050_6  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw025_1", "",  &BDT_MTPeakOneBtag_T2bw025_1  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw025_3", "",  &BDT_MTPeakOneBtag_T2bw025_3  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw025_4", "",  &BDT_MTPeakOneBtag_T2bw025_4  , rebinning);
    screwdriver.AddRegion("BDT_MTPeakOneBtag_T2bw025_6", "",  &BDT_MTPeakOneBtag_T2bw025_6  , rebinning);

    screwdriver.AddRegion("CR0btag_MTtail_MT_100",           "",  &goesIn0BtagControlRegionMTtail100);
    screwdriver.AddRegion("CR0btag_MTtail_MT_120",           "",  &goesIn0BtagControlRegionMTtail120);
    screwdriver.AddRegion("CR0btag_MTtail_MT_125",           "",  &goesIn0BtagControlRegionMTtail125);
    screwdriver.AddRegion("CR0btag_MTtail_MT_130",           "",  &goesIn0BtagControlRegionMTtail130);
    screwdriver.AddRegion("CR0btag_MTtail_MT_135",           "",  &goesIn0BtagControlRegionMTtail135);
    screwdriver.AddRegion("CR0btag_MTtail_MT_140",           "",  &goesIn0BtagControlRegionMTtail140);

    screwdriver.AddRegion("CR0btag_MTpeak_MET_200",          "",  &CR0btag_MTpeak_MET_200         );
    screwdriver.AddRegion("CR0btag_MTpeak_MET_250",          "",  &CR0btag_MTpeak_MET_250         );
    screwdriver.AddRegion("CR0btag_MTpeak_MET_300",          "",  &CR0btag_MTpeak_MET_300         );
    screwdriver.AddRegion("CR0btag_MTpeak_MET_350",          "",  &CR0btag_MTpeak_MET_350         );
    screwdriver.AddRegion("CR0btag_MTtail_MET_200",          "",  &CR0btag_MTtail_MET_200         );
    screwdriver.AddRegion("CR0btag_MTtail_MET_250",          "",  &CR0btag_MTtail_MET_250         );
    screwdriver.AddRegion("CR0btag_MTtail_MET_300",          "",  &CR0btag_MTtail_MET_300         );
    screwdriver.AddRegion("CR0btag_MTtail_MET_350",          "",  &CR0btag_MTtail_MET_350         );
    screwdriver.AddRegion("CR0btag_MTpeak_METoverSqrtHT_6" , "",  &CR0btag_MTpeak_METoverSqrtHT_6 );
    screwdriver.AddRegion("CR0btag_MTpeak_METoverSqrtHT_7" , "",  &CR0btag_MTpeak_METoverSqrtHT_7 );
    screwdriver.AddRegion("CR0btag_MTpeak_METoverSqrtHT_8" , "",  &CR0btag_MTpeak_METoverSqrtHT_8 );
    screwdriver.AddRegion("CR0btag_MTpeak_METoverSqrtHT_9" , "",  &CR0btag_MTpeak_METoverSqrtHT_9 );
    screwdriver.AddRegion("CR0btag_MTpeak_METoverSqrtHT_10", "",  &CR0btag_MTpeak_METoverSqrtHT_10);
    screwdriver.AddRegion("CR0btag_MTpeak_METoverSqrtHT_12", "",  &CR0btag_MTpeak_METoverSqrtHT_12);
    screwdriver.AddRegion("CR0btag_MTtail_METoverSqrtHT_6" , "",  &CR0btag_MTtail_METoverSqrtHT_6 );
    screwdriver.AddRegion("CR0btag_MTtail_METoverSqrtHT_7" , "",  &CR0btag_MTtail_METoverSqrtHT_7 );
    screwdriver.AddRegion("CR0btag_MTtail_METoverSqrtHT_8" , "",  &CR0btag_MTtail_METoverSqrtHT_8 );
    screwdriver.AddRegion("CR0btag_MTtail_METoverSqrtHT_9" , "",  &CR0btag_MTtail_METoverSqrtHT_9 );
    screwdriver.AddRegion("CR0btag_MTtail_METoverSqrtHT_10", "",  &CR0btag_MTtail_METoverSqrtHT_10);
    screwdriver.AddRegion("CR0btag_MTtail_METoverSqrtHT_12", "",  &CR0btag_MTtail_METoverSqrtHT_12);
    screwdriver.AddRegion("CR0btag_MTpeak_BPt_100" ,         "",  &CR0btag_MTpeak_BPt_100         );
    screwdriver.AddRegion("CR0btag_MTpeak_BPt_150" ,         "",  &CR0btag_MTpeak_BPt_150         );
    screwdriver.AddRegion("CR0btag_MTpeak_BPt_180" ,         "",  &CR0btag_MTpeak_BPt_180         );
    screwdriver.AddRegion("CR0btag_MTtail_BPt_100" ,         "",  &CR0btag_MTtail_BPt_100         );
    screwdriver.AddRegion("CR0btag_MTtail_BPt_180" ,         "",  &CR0btag_MTtail_BPt_180         );
    screwdriver.AddRegion("CR0btag_MTpeak_DPhi_02" ,         "",  &CR0btag_MTpeak_DPhi_02         );
    screwdriver.AddRegion("CR0btag_MTpeak_DPhi_08" ,         "",  &CR0btag_MTpeak_DPhi_08         );
    screwdriver.AddRegion("CR0btag_MTtail_DPhi_02" ,         "",  &CR0btag_MTtail_DPhi_02         );
    screwdriver.AddRegion("CR0btag_MTtail_DPhi_08" ,         "",  &CR0btag_MTtail_DPhi_08         );
    screwdriver.AddRegion("CR0btag_MTpeak_ISRJet"  ,         "",  &CR0btag_MTpeak_ISRJet          );
    screwdriver.AddRegion("CR0btag_MTtail_ISRJet"  ,         "",  &CR0btag_MTtail_ISRJet          );
    screwdriver.AddRegion("CR0btag_MTpeak_MT2W_180",         "",  &CR0btag_MTpeak_MT2W_180        );
    screwdriver.AddRegion("CR0btag_MTpeak_MT2W_190",         "",  &CR0btag_MTpeak_MT2W_190        );
    screwdriver.AddRegion("CR0btag_MTpeak_MT2W_200",         "",  &CR0btag_MTpeak_MT2W_200        );
    screwdriver.AddRegion("CR0btag_MTtail_MT2W_180",         "",  &CR0btag_MTtail_MT2W_180        );
    screwdriver.AddRegion("CR0btag_MTtail_MT2W_190",         "",  &CR0btag_MTtail_MT2W_190        );
    screwdriver.AddRegion("CR0btag_MTtail_MT2W_200",         "",  &CR0btag_MTtail_MT2W_200        );

    // ##########################
    // ##   Create Channels    ##
    // ##########################

    screwdriver.AddChannel("singleLepton", "e/#mu-channels",   &goesInSingleLeptonChannel);

    // ########################################
    // ##       Create histograms and        ##
    // ##  schedule type of plots to produce ##
    // ########################################

    // Create histograms
    screwdriver.Create1DHistos();

    // Schedule plots
    screwdriver.SchedulePlots("1DDataMCComparison");
    screwdriver.SchedulePlots("1DSuperimposed");

    // Config plots

    screwdriver.SetGlobalStringOption("Plot", "infoTopRight", "CMS Internal");
    screwdriver.SetGlobalStringOption("Plot", "infoTopLeft",  "#sqrt{s} = 8 TeV, L = 19.5 fb^{-1}");

    screwdriver.SetGlobalBoolOption("Plot", "exportPdf", true);
    screwdriver.SetGlobalBoolOption("Plot", "exportEps", false);
    screwdriver.SetGlobalBoolOption("Plot", "exportPng", false);

    // ########################################
    // ##       Run over the datasets        ##
    // ########################################

    vector<string> datasetsList;
    screwdriver.GetDatasetList(&datasetsList);

    cout << "   > Reading datasets... " << endl;
    cout << endl;

    for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
    {
        string currentDataset = datasetsList[d];
        string currentProcessClass = screwdriver.GetProcessClass(currentDataset);

        sampleName = currentDataset;
        sampleType = screwdriver.GetProcessClassType(currentProcessClass);

        // Open the tree
        TFile f((string(FOLDER_BABYTUPLES)+currentDataset+".root").c_str());
        TTree* theTree = (TTree*) f.Get("babyTuple");

        intermediatePointers pointers;
        InitializeBranchesForReading(theTree,&myEvent,&pointers);

        // ########################################
        // ##        Run over the events         ##
        // ########################################

        bool ttbarDatasetToBeSplitted = false;
        if (findSubstring(currentDataset,"ttbar")
                && (currentDataset != "ttbar_madgraph_1l")
                && (currentDataset != "ttbar_madgraph_2l"))
            ttbarDatasetToBeSplitted = true;

        int nEntries = theTree->GetEntries();
        for (int i = 0 ; i < nEntries ; i++)
        {
            if (i % (nEntries / 50) == 0) printProgressBar(i,nEntries,currentDataset);

            // Get the i-th entry
            ReadEvent(theTree,i,&pointers,&myEvent);

            float weight = getWeight();

            // Split 1-lepton ttbar and 2-lepton ttbar
            string currentProcessClass_ = currentProcessClass;
            if (ttbarDatasetToBeSplitted && (myEvent.numberOfGenLepton == 2))
                currentProcessClass_ = "ttbar_2l";

            // FIXME Why managing overflow this way ?
            // It's already done on the plot automatically...
            nJets = myEvent.nJets;
            if(myEvent.nJets >6 ) nJets = 6;

            screwdriver.AutoFillProcessClass(currentProcessClass_,weight);

        }
        printProgressBar(nEntries,nEntries,currentDataset);
        cout << endl;
        f.Close();

    }

    // ###################################
    // ##   Make plots and write them   ##
    // ###################################

    cout << endl;
    cout << "   > Making plots..." << endl;
    screwdriver.MakePlots();
    cout << "   > Saving plots..." << endl;
    // TODO : if we need to redo tests for different ttbar sample,
    // move the plots to a separate folder with the name of the alternative sample
    screwdriver.WritePlots(string("./inputPlots/"));

    printBoxedMessage("Plot generation completed");

    // #############################
    // ##   Post-plotting tests   ##
    // #############################

    printBoxedMessage("Program done.");
    return (0);
}
Ejemplo n.º 7
0
int sendFile(int port, int fd, char *filePath)
{
	int size = getSize(fd);
	unsigned char* buffer = (unsigned char*) mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
	if(buffer == MAP_FAILED){
		//printf("did not mmap\n");
		exit(-1);
	}
	unsigned char *bufferBckup = buffer;
	int length;

	unsigned char* packet = makeControlPacket(size , filePath, 1, &length);
	//printf("gonna send following packet of length %d: \n", length);
		/*int j;
		for(j = 0; j < length; j++){
			//printf("%d: 0x%02x - %c\n", j, packet[j], packet[j]);
		}*/
	if(llwrite(port, packet, length) < 0 )
		return -1;
	int i = 0;
	int acum = 0;
	float percentage;
	char *proBar = updateProgressBar(acum, size, &percentage);
	for(i = 0; i < (size/PACKET_SIZE); i++){
		/*//printf("gonna send following packet of length %d: \n", length);
		int j;
		for(j = 0; j < length; j++){
			//printf("%d: 0x%02x - %c\n", j, packet[j], packet[j]);
		}*/
		packet = makeDataPacket(PACKET_SIZE, buffer, &length);

		if(llwrite(port, packet, length) < 0 )
			return -1;
		buffer += PACKET_SIZE;

		acum += PACKET_SIZE;
		proBar = updateProgressBar(acum, size, &percentage);
		if(visMode != 0)
			printProgressBar(proBar, percentage);
		

	}

	if((size % PACKET_SIZE) != 0){
		packet = makeDataPacket((size % PACKET_SIZE), buffer, &length);
		/*//printf("gonna send following packet of length %d: \n", length);
		int j;
		for(j = 0; j < length; j++){
			//printf("%d: 0x%02x - %c\n", j, packet[j], packet[j]);
		}*/
		if(llwrite(port, packet, length) < 0 )
			return -1;
		acum += (size % PACKET_SIZE);
		
		proBar = updateProgressBar(acum, size, &percentage);
		if(visMode != 0)
			printProgressBar(proBar, percentage);
		
		
	}

	printf("\n");
	packet = makeControlPacket(size, filePath, 2, &length);
	llwrite(port, packet, length);


	llclose(port);

	if(munmap(bufferBckup, size) == -1)
		perror("failed to unmap the file");

		return 0;
}
int main (int argc, char *argv[])
{

  printBoxedMessage("Starting plot generation");

  // ####################
  // ##   Init tools   ##
  // ####################
  
     // Create a sonic Screwdriver
      SonicScrewdriver screwdriver;

       // Create a container for the event
     babyEvent myEvent;
     myEventPointer = &myEvent;

  // ##########################
  // ##   Create Variables   ##
  // ##########################

     screwdriver.AddVariable("MET",            "MET",                     "GeV",    15,50,500,      &(myEvent.MET),                  "logY");

     // #########################################################
     // ##   Create ProcessClasses (and associated datasets)   ##
     // #########################################################

     screwdriver.AddProcessClass("ttbar_1l", "t#bar{t} #rightarrow l+jets","background",kRed-7);
     screwdriver.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}",    "background",kCyan-3);
            screwdriver.AddDataset("ttbar",    "ttbar_1l",  0, 0);
     
     screwdriver.AddProcessClass("W+jets",   "W+jets",                     "background",kOrange-2);
             screwdriver.AddDataset("Wjets",    "W+jets", 0, 0);

     screwdriver.AddProcessClass("others",   "others",                     "background",kMagenta-5);
             screwdriver.AddDataset("others",   "others", 0, 0);

     /*
     screwdriver.AddProcessClass("T2tt",     "T2tt",                       "signal",kViolet-1);
             screwdriver.AddDataset("T2tt",     "T2tt",   0, 0);

     screwdriver.AddProcessClass("signal_250_50",  "T2tt (250/50)",      "signal",COLORPLOT_AZURE);
     screwdriver.AddProcessClass("signal_450_50",  "T2tt (450/50)",      "signal",kCyan-3);
     screwdriver.AddProcessClass("signal_650_50",  "T2tt (650/50)",      "signal",COLORPLOT_GREEN);
     */


  // ##########################
  // ##    Create Regions    ##
  // ##########################

     screwdriver.AddRegion("LM150",      "LM 150",            &Selector_LM150);

  // ##########################
  // ##   Create Channels    ##
  // ##########################
   
     screwdriver.AddChannel("singleLepton", "e/#mu-channels",         &singleLeptonChannelSelector);
     screwdriver.AddChannel("singleElec",   "e-channel",              &singleElecChannelSelector  );
     screwdriver.AddChannel("singleMuon",   "#mu-channel",            &singleMuonChannelSelector  );
     
  // ########################################
  // ##       Create histograms and        ##
  // ##  schedule type of plots to produce ##
  // ########################################

     screwdriver.SetLumi(20000);

     // Create histograms
     screwdriver.Create1DHistos();

     screwdriver.SetGlobalBoolOption  ("1DSuperimposed",   "includeSignal",                   true   );

     screwdriver.SetGlobalStringOption("1DStack",          "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("1DStack",          "factorSignal",                    1.0    );

     screwdriver.SetGlobalStringOption("DataMCComparison", "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("DataMCComparison", "factorSignal",                    1.0    );

     screwdriver.SetGlobalFloatOption ("FigureOfMerit",    "backgroundSystematicUncertainty", 0.15   );

     // Schedule plots
     screwdriver.SchedulePlots("1DSuperimposed");
     screwdriver.SchedulePlots("1DStack");

     // Config plots

     screwdriver.SetGlobalStringOption("Plot", "infoTopRight", "CMS Internal");
     screwdriver.SetGlobalStringOption("Plot", "infoTopLeft",  "#sqrt{s} = 8 TeV, L = 19.5 fb^{-1}");

     screwdriver.SetGlobalBoolOption("Plot", "exportPdf", true);
     screwdriver.SetGlobalBoolOption("Plot", "exportEps", false);
     screwdriver.SetGlobalBoolOption("Plot", "exportPng", false);

  // ########################################
  // ##       Run over the datasets        ##
  // ########################################

  vector<string> datasetsList;
  screwdriver.GetDatasetList(&datasetsList);

  cout << "   > Reading datasets... " << endl;
  cout << endl;

  for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
  {
     string currentDataset = datasetsList[d];
     string currentProcessClass = screwdriver.GetProcessClass(currentDataset);

     pCurrentDataset     = &currentDataset;
     pCurrentDatasetType = &currentProcessClass;

     // Open the tree
     TFile f((string(FOLDER_BABYTUPLES)+currentDataset+".root").c_str());
     TTree* theTree = (TTree*) f.Get("babyTuple"); 
     
     intermediatePointers pointers;
     InitializeBranches(theTree,&myEvent,&pointers);

  // ########################################
  // ##        Run over the events         ##
  // ########################################

      int nEntries = theTree->GetEntries();
      for (int i = 0 ; i < nEntries ; i++)
      {
          if (i % (nEntries / 50) == 0) printProgressBar(i,nEntries,currentDataset);

          //if (i > 0.03 * nEntries) break;

          // Get the i-th entry
          ReadEvent(theTree,i,&pointers,&myEvent);

          float weight = 1.0;
          // For MC, apply weights
          /*
          float lumi;

               if (singleElecChannelSelector())  lumi = 19154.0;
          else if (singleMuonChannelSelector())  lumi = 19096.0;
          else                                   lumi = 0.0;
          */
          float lumi = 19500;

          // Normalize to cross section times lumi
          weight *= myEvent.weightCrossSection * lumi;

          // Apply trigger efficiency weights for singleLepton channels
          if (myEvent.numberOfLepton == 1) weight *= myEvent.weightTriggerEfficiency;

          // Apply pile-up weight except for signal
          if (currentDataset != "T2tt") weight *= myEvent.weightPileUp;

          // For signal, apply ISR reweighting
          if (currentDataset == "T2tt")  weight *= myEvent.weightISRmodeling;

          // For ttbar, apply topPt reweighting
          //if (currentDataset == "ttbar") weight *= myEvent.weightTopPt;

          // Split 1-lepton ttbar and 2-lepton ttbar
          string currentProcessClass_ = currentProcessClass;
          if ((currentDataset == "ttbar") && (myEvent.numberOfGenLepton == 2)) 
              currentProcessClass_ = "ttbar_2l";

          screwdriver.AutoFillProcessClass(currentProcessClass_,weight);

          if ((myEvent.mStop == 250) && (myEvent.mNeutralino == 50))
              screwdriver.AutoFillProcessClass("signal_250_50",weight);
          if ((myEvent.mStop == 450) && (myEvent.mNeutralino == 50))
              screwdriver.AutoFillProcessClass("signal_450_50",weight);
          if ((myEvent.mStop == 650) && (myEvent.mNeutralino == 50))
              screwdriver.AutoFillProcessClass("signal_650_50",weight);

      } 
      printProgressBar(nEntries,nEntries,currentDataset);
      cout << endl;
      cout << "Reading " << f.GetBytesRead() << " bytes in " << f.GetReadCalls() << " transactions" << endl;
      f.Close();

  }

  // ###################################
  // ##   Make plots and write them   ##
  // ###################################
 
  cout << endl;
  cout << "   > Making plots..." << endl;
  screwdriver.MakePlots();
  cout << "   > Saving plots..." << endl;
  screwdriver.WritePlots("../plots/dataMCChecks/");

  printBoxedMessage("Plot generation completed");

  // #############################
  // ##   Post-plotting tests   ##
  // #############################
  
  printBoxedMessage("Now computing misc tests ... ");


  // Print yield tables for the signal region LM150
  vector<string> tableRegions = { "LM150" };
  TableBackgroundSignal(&screwdriver,tableRegions,"singleLepton").PrintTable();

  printBoxedMessage("Program done.");
  return (0);
}
int main (int argc, char *argv[])
{
    //loadBDTSignalRegions();

    if(argc == 2){
    	cout<<"load"<<endl;
	default_param2(topness2_param_);
	LoadParam2(string(argv[1]));
    }
    else{
    	cout<<"You shoul provide the name of the config file !"<<endl;
    	return -1;
    }
    printBoxedMessage("Starting tables generation");

    // ####################
    // ##   Init tools   ##
    // ####################

        // Create a sonic Screwdriver
        SonicScrewdriver screwdriver;
     
     
     // ##########################
     // ##   Create Variables   ##
     // ##########################
  
   
     vector<string> colTags = {"default","resMass", "aCM", "allTerms","allTermsBias"};
     vector<string> colLabels = {"default","reso mass", "aCM terms", "all terms", "id + bias"};
     vector<string> rowTags = {"purity"};
     vector<string> rowLabels = {"purity"};
     Table table_topness_purity(colTags,rowTags,colLabels,rowLabels);
     int n_tt2l_sel = 0;
     int n_tt2l_sel_matchable = 0;

     int n_topness_var = 5;
     vector< vector< int > > topness_purity;
     topness_purity.resize(n_topness_var);
     for(int i=0;i<n_topness_var;i++) topness_purity[i].resize(2);

     //tt2l_mc_info mcinfo;
     //tt2l_reso res;
    

     float d_met;
     float topness_def;
     float topness_m1; // change the resolution term for Invis.
     float topness_m2; // change the resolution term for aCM
     float topness_m3; // change the resolution term for all
     float topness_m4; // change the resolution term for all
     float topness_m5; // m3 + correct for MET bias
     float topness_m6; // m3 + correct for MET bias
     float topness_m7; // m3 + correct for MET bias
     float topness_m8; // m3 + correct for MET bias
     float topness_m9; // m3 + correct for MET bias
     float topness_m10; // m3 + correct for MET bias
     float topness_m11; // m3 + correct for MET bias
     float topness_m12; // m3 + correct for MET bias
     float topness_m13; // m3 + correct for MET bias

     screwdriver.AddVariable("MT2W",             "MT2W",                   "GeV",    40,0,400,       &(myEvent.MT2W),                   "");

     //screwdriver.AddVariable("lostLeptonEta",             "Eta of lost lepton",            "",    40, -6, 6,     &(res.lost_eta),                   "");

     // topness
     screwdriver.AddVariable("topness",             "topness - reference",            "",    80, -5, 15,     &(topness_def),                   "");
     /*
     screwdriver.AddVariable("topness_m12",          "topness - resolution modified",  "",    40, -20, 20,     &(topness_m12),                   "");
     screwdriver.AddVariable("topness_m13",          "topness - resolution modified",  "",    40, -20, 20,     &(topness_m13),                   "");
*/
//int index_b;	//
	//int index_bbar; //
//	vector<int> index_isr;



    // #########################################################
    // ##   Create ProcessClasses (and associated datasets)   ##
    // #########################################################
	
	screwdriver.AddProcessClass("ttbar_1l", "t#bar{t} #rightarrow l+jets",                             "background",kRed-7);
                screwdriver.AddDataset("ttbar-madgraph",                "ttbar_1l",  0, 0);


        screwdriver.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);
///*	
	screwdriver.AddProcessClass("single_top", "single top",                             "background",kRed-5);
                screwdriver.AddDataset("singleTopbar_s",                "single_top",  0, 0);
                screwdriver.AddDataset("singleTopbar_t",                "single_top",  0, 0);
                screwdriver.AddDataset("singleTop_s",                "single_top",  0, 0);
                screwdriver.AddDataset("singleTop_t",                "single_top",  0, 0);
	 
        screwdriver.AddProcessClass("W+jets",   "W+jets",                          "background",kOrange-2);
            screwdriver.AddDataset("Wjets", "W+jets", 0, 0);
        screwdriver.AddProcessClass("VV",   "di-boson",                          "background",kOrange-3);
            //screwdriver.AddDataset("ZZ", "ZZ", 0, 0);
            screwdriver.AddDataset("WZ", "WZ", 0, 0);
       
       screwdriver.AddProcessClass("ttV",   "ttV",                          "background",kOrange-4);
            screwdriver.AddDataset("ttW", "ttV", 0, 0);
            screwdriver.AddDataset("ttZ", "ttV", 0, 0);
//	*/
	screwdriver.AddProcessClass("T2tt_850_100",   "T2tt_850_100",                          "signal",kGreen+2);
            screwdriver.AddDataset("T2tt_850_100", "T2tt_850_100", 0, 0);
	screwdriver.AddProcessClass("T2tt_650_100",   "T2tt_650_100",                          "signal",kGreen+3);
           screwdriver.AddDataset("T2tt_650_100", "T2tt_650_100", 0, 0);
       // screwdriver.AddProcessClass("T2tt_500_325",   "T2tt_500_325",                          "signal",kGreen+4);
         //   screwdriver.AddDataset("T2tt_500_325", "T2tt_500_325", 0, 0);


    // ##########################
    // ##    Create Regions    ##
    // ##########################

        //screwdriver.AddRegion("presel_MTpeak",          "Preselection (MT peak)",      &goesInMTpeak);
        //screwdriver.AddRegion("presel_MTtail",          "Preselection (MT peak)",      &goesInMTtail);
        screwdriver.AddRegion("baseline",          "Baseline selection",      &goesInBaselineSearchSR);
        screwdriver.AddRegion("baslineLargeDM",          "Baseline S.R.  - Large #DeltaM",      &goesInLargeDMSR);
        screwdriver.AddRegion("baselineSmallDM",          "Baseline S.R. - Small #DeltaM",      &goesInSmallDMSR);
        screwdriver.AddRegion("baseline2b",          "Baseline selection",      &goesInBaselineSearchSR2b);
        screwdriver.AddRegion("baselineSmallDM2b",          "Baseline S.R. - Small #DeltaM",      &goesInSmallDMSR2b);


    // ##########################
    // ##   Create Channels    ##
    // ##########################

        //screwdriver.AddChannel("singleLepton", "e/#mu-channels",  &goesInSingleLeptonChannel);
        //screwdriver.AddChannel("singleElec",   "e-channel",       &goesInSingleElecChannel  );
        //screwdriver.AddChannel("singleMuon",   "#mu-channel",     &goesInSingleMuonChannel  );
        screwdriver.AddChannel("allChannels",  "",                &goesInAnyChannel         );

  // ########################################
  // ##       Create histograms and        ##
  // ##  schedule type of plots to produce ##
  // ########################################

     // Create histograms
     screwdriver.Create1DHistos();
     
     // Create 2D histos
    
    
    // #########################################################

     // Schedule plots
     screwdriver.SchedulePlots("1DDataMCComparison");
     screwdriver.SchedulePlots("1DStack");
     screwdriver.SchedulePlots("1DSuperimposed");
     //screwdriver.SchedulePlots("2D");


     // Config plots

     screwdriver.SetGlobalStringOption("DataMCComparison",  "includeSignal",                    "stack");
     screwdriver.SetGlobalFloatOption ("DataMCComparison",  "factorSignal",                     1.0    );
     
     screwdriver.SetGlobalStringOption("1DStack",           "includeSignal",    "superimposed");
     screwdriver.SetGlobalFloatOption ("1DStack",           "factorSignal",     1.0    );

     screwdriver.SetGlobalStringOption("Plot", "infoTopRight", "CMS Preliminary");
     screwdriver.SetGlobalStringOption("Plot", "infoTopLeft",  "#sqrt{s} = 8 TeV, L = 10 fb^{-1}");

     screwdriver.SetGlobalBoolOption("Plot", "exportPdf", true);
     screwdriver.SetGlobalBoolOption("Plot", "exportEps", false);
     screwdriver.SetGlobalBoolOption("Plot", "exportPng", false);

    // ########################################
    // ##       Run over the datasets        ##
    // ########################################

        vector<string> datasetsList;
        screwdriver.GetDatasetList(&datasetsList);

        cout << "   > Reading datasets... " << endl;
        cout << endl;

        for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
        {
            string currentDataset = datasetsList[d];
            string currentProcessClass = screwdriver.GetProcessClass(currentDataset);

            sampleName = currentDataset;
            sampleType = screwdriver.GetProcessClassType(currentProcessClass);

            // Open the tree
            string treePath = string(FOLDER_BABYTUPLES_SKIM)+currentDataset+".root";
            TFile f(treePath.c_str());
            TTree* theTree = (TTree*) f.Get("babyTuple");

	    //cout<<"v1"<<endl;
            InitializeBranchesForReading(theTree,&myEvent);
	    //cout<<"v2"<<endl;

        // ########################################
        // ##        Run over the events         ##
        // ########################################

            bool ttbarDatasetToBeSplitted = false;
            if (findSubstring(currentDataset,"ttbar")
            && (currentDataset != "ttbar_madgraph_1l")
            && (currentDataset != "ttbar_madgraph_2l"))
                ttbarDatasetToBeSplitted = true;

            int nEntries = theTree->GetEntries();
            //if(nEntries>10000000) nEntries = 10000000;
            //if(nEntries>5000000) nEntries = 5000000;
            //if(nEntries>500000) nEntries = 500000;
	    double tWL, tTL, tTM;
	    float sf_fracEvent = (float)nEntries/theTree->GetEntries();
	    for (int i = 0 ; i < nEntries ; i++)
            {
                if (i % (nEntries / 50) == 0) printProgressBar(i,nEntries,currentDataset);

		// Get the i-th entry
		ReadEvent(theTree,i,&myEvent);

                string currentProcessClass_ = currentProcessClass;
		float weight = getWeight(currentDataset,theTree->GetEntries(), sf_fracEvent);

		
		//Compute Delta MET
		d_met = myEvent.pfmet-myEvent.genMET;

		//Topness study
		bool is_tt2l = false;
		if(myEvent.ttbar_decay == 2){
			is_tt2l = true; 
			n_tt2l_sel++;
			if(myEvent.matched == true) n_tt2l_sel_matchable++;
		}
			
			#ifdef topness_computation

		        int index_b1 = -1;
			int index_b2 = -1;
			//cout<<topness_param_.use_cox_box<<endl;
			//cout<<topness_param_.aW<<endl;	
			//default_param(topness_param_);
			//DumpParam();

			topness_def = ComputeTopness(index_b1,index_b2, tWL, tTL, tTM);
			//cout<<"topness = "<<topness_def<<endl;
			if(TopnessMatched(index_b1, index_b2)) topness_purity[0][0]++;
			// changing the resolution terms
			/*
			// default computation
			// -- load default parameter s
			default_param(topness_param_);
			topness_def = ComputeTopness(index_b1,index_b2);
			if(TopnessMatched(index_b1, index_b2)) topness_purity[0][0]++;
			// changing the resolution terms
			default_param(topness_param_);
			topness_param_.aW = 40;
			topness_param_.aT = 50;
			
			topness_m1 = ComputeTopness(index_b1,index_b2);
			if(TopnessMatched(index_b1, index_b2)) topness_purity[0][1]++;			
			//
			default_param(topness_param_);
			topness_param_.aCM = 70;
			topness_param_.aCM_mean = 500;
			
			topness_m2 = ComputeTopness(index_b1,index_b2);
			if(TopnessMatched(index_b1, index_b2)) topness_purity[0][2]++;			
			
			//
			default_param(topness_param_);
			topness_param_.aW = 40;
			topness_param_.aT = 50;
			topness_param_.aCM = 200;
			topness_param_.aCM_mean = 650;
			
			topness_m3 = ComputeTopness(index_b1,index_b2);
			if(TopnessMatched(index_b1, index_b2)) topness_purity[0][3]++;			
			
			//
			default_param(topness_param_);
			topness_param_.aCM = 250;
			topness_param_.aCM_mean = 670;
			
			topness_m4 = ComputeTopness(index_b1,index_b2);
			if(TopnessMatched(index_b1, index_b2)) topness_purity[0][4]++;			
			
			
			//correct for MET bias
			topness_param_.aW = 40;
			topness_param_.aT = 50;
			topness_param_.aCM = 200;
			topness_param_.aCM_mean =670;
			topness_m7 = ComputeTopness(index_b1,index_b2);
			//if(TopnessMatched(index_b1, index_b2)) topness_purity[0][5]++;			
		
			//correct for MET bias
			//if(myEvent.pfmet>80) myEvent.pfmet = myEvent.pfmet - 50;
			default_param(topness_param_);
			topness_param_.aW = 80;
			topness_param_.aT = 100;
			topness_param_.aCM = 200;
			topness_param_.aCM_mean = 670;
			topness_m8 = ComputeTopness(index_b1,index_b2);
			//if(TopnessMatched(index_b1, index_b2)) topness_purity[0][5]++;			
			
			//correct for MET bias
			//if(myEvent.pfmet>80) myEvent.pfmet = myEvent.pfmet - 50;
			default_param(topness_param_);
			//topness_param_.aW = 80;
			//topness_param_.aT = 100;
			topness_param_.aCM = 65;
			topness_param_.aCM_mean = 650;
			topness_param_.use_cox_box = true;
			topness_m9 = ComputeTopness(index_b1,index_b2);
			//if(TopnessMatched(index_b1, index_b2)) topness_purity[0][5]++;		
			
			
			//correct for MET bias
			//if(myEvent.pfmet>80) myEvent.pfmet = myEvent.pfmet - 50;
			default_param(topness_param_);
			topness_param_.aW = 40;
			topness_param_.aT = 50;
			topness_param_.aCM = 65;
			topness_param_.aCM_mean = 650;
			topness_param_.use_cox_box = true;
			topness_m10 = ComputeTopness(index_b1,index_b2);
			
			
			//correct for MET bias
			//if(myEvent.pfmet>80) myEvent.pfmet = myEvent.pfmet - 50;
			default_param(topness_param_);
			topness_param_.aW = 40;
			topness_param_.aT = 50;
			topness_param_.aCM = 80;
			topness_param_.aCM_mean = 800;
			topness_param_.use_cox_box = true;
			topness_m11 = ComputeTopness(index_b1,index_b2);

			//correct for MET bias
			//if(myEvent.pfmet>80) myEvent.pfmet = myEvent.pfmet - 50;
			default_param(topness_param_);
			//topness_param_.aW = 40;
			//topness_param_.aT = 50;
			//topness_param_.aCM = 80;
			//topness_param_.aCM_mean = 800;
			//topness_param_.use_cox_box = true;
			topness_param_.usePtPz = true;
			topness_m12 = ComputeTopness(index_b1,index_b2);
*/
			//correct for MET bias
			//if(myEvent.pfmet>80) myEvent.pfmet = myEvent.pfmet - 50;
			/*
			default_param(topness_param_);
			topness_param_.aW = 40;
			topness_param_.aT = 50;
			//topness_param_.aCM = 80;
			//topness_param_.aCM_mean = 800;
			//topness_param_.use_cox_box = true;
			topness_param_.usePtPz = true;
			topness_m13 = ComputeTopness(index_b1,index_b2);
*/
/*

			//correct for MET bias
			//if(myEvent.pfmet>80) myEvent.pfmet = myEvent.pfmet - 50;
			default_param(topness_param_);
			topness_param_.aW = 40;
			topness_param_.aT = 50;
			topness_param_.aCM = 350;
			topness_param_.aCM_mean = 850;
			topness_m6 = ComputeTopness(index_b1,index_b2);
			//if(TopnessMatched(index_b1, index_b2, res)) topness_purity[0][5]++;			
			
			//correct for MET bias
			//cout<<myEvent.pfmet<<endl;
			//if(myEvent.pfmet>80) myEvent.pfmet = myEvent.pfmet - 50;
			if(myEvent.pfmet>80) myEvent.pfmet = myEvent.pfmet*0.70;// - 50;
			//cout<<myEvent.pfmet<<endl;
			default_param(topness_param_);
			topness_param_.aW = 40;
			topness_param_.aT = 50;
			topness_param_.aCM = 300;
			topness_param_.aCM_mean = 650;
			topness_m5 = ComputeTopness(index_b1,index_b2);
			//if(TopnessMatched(index_b1, index_b2, res)) topness_purity[0][5]++;			
			*/
			#endif
                
		// Split 1-lepton ttbar and 2-lepton ttbar
                //if (ttbarDatasetToBeSplitted && (myEvent.genlepsfromtop == 2))
                if (ttbarDatasetToBeSplitted && is_tt2l)
                    currentProcessClass_ = "ttbar_2l";
                
		screwdriver.AutoFillProcessClass(currentProcessClass_,weight);

            }
            printProgressBar(nEntries,nEntries,currentDataset);
            cout << endl;
            f.Close();

        }
  
  // ###################################
  // ##   Make plots and write them   ##
  // ###################################

  cout << endl;
  cout << "   > Making plots..." << endl;
  screwdriver.MakePlots();
  cout << "   > Saving plots..." << endl;

  //string output_dir = %./plots/"+string(argv[1])+"/pow2/";
  string output_dir = "./plots/"+string(argv[1])+"/comb3_4/";
  //string output_dir = "./plots/"+string(argv[1])+"/pow2/loopnonb_all/";
  //string output_dir = "./plots/topness2/"+string(argv[1])+"/";
  //screwdriver.WritePlots(string("./plots/plotsProducer/"));
  screwdriver.WritePlots(output_dir);

  printBoxedMessage("Plot generation completed");
        
  printBoxedMessage("Writing the table ... ");
 
 vector<string> regions  = { 
 	"presel_MTtail", "baseline", "baslineLargeDM", "baselineSmallDM"
				    //"presel_MTpeak", "presel_MTtail",
				    /*
				    "preveto_MTpeak",      "preveto_MTtail",
                                    "signalRegion_MTpeak", "signalRegion_MTtail",
                                    "0btag_MTpeak",        "0btag_MTtail",
                                    "reversedVeto_MTpeak", "reversedVeto_MTtail",
                                    "2leptons", "2leptons_MTpeak", "2leptons_MTtail",
                                  */};

  //string exportFile = "rawYieldTables/prediction.tab";
  //TableDataMC(&screwdriver,regions,"allChannels").Print(exportFile,4);

  // #############################
  // ##   Post-plotting tests   ##
  // #############################
  

  //Table topness - purity
  for(int i=0;i<n_topness_var;i++){
  	table_topness_purity.Set(0,i, Figure(topness_purity[i][0],sqrt(topness_purity[i][0]))/Figure(n_tt2l_sel,sqrt(n_tt2l_sel)));
  	table_topness_purity.Set(1,i, Figure(topness_purity[i][0],sqrt(topness_purity[i][0]))/Figure(n_tt2l_sel_matchable,sqrt(n_tt2l_sel_matchable)));
  }
  table_topness_purity.Print(output_dir+"purity.dat");

  printBoxedMessage("Program done.");
/*
 string region = "baseline";
 string channel = "allChannels";
 string var;
 var = "topness_m5";
 //loop over the backgroumd
 vector<string> processClassList;
 //GetProcessClassTagList()
 screwdriver.GetProcessClassTagList(&processClassList);
 TH1F* h_Eff_Bkg = 0;
 TH1F* h_Eff_Sig = 0;
 bool first = true;
 for(unsigned int i=0;i<processClassList.size();i++){
 	string proc = processClassList[i];
 	if(scredrive.GetProcessClassType(proc) == "background"){
 		TH1F* h = screewdriver.Get1DHistoClone(var , processClass, region, channel);
 		if(first){
			h_Eff_Bkg = (TH1F*) h->Clone("");
			first = false;
		}
		for(int i=1;i<h->GetNBinsX();i++){
			h_Eff_Bkgh->Integral(i,h->GetNBinsX()+1);
		}
	}
 }
 */
	return (0);
}
Ejemplo n.º 10
0
int main(int argc, char** argv) {
   if(argc < 4) {
      printUsageAndDie();
   }

   FileHashGrouper fileHashGrouper;
   bool enableHtmlOutput = false;
   char* targetFolder;
   char* algoArg;
   char* thresholdArg;
   float threshold = -1.0f;
   HashAlgorithm selectedAlgorithm = DCT; 

   #ifdef DEBUG
   std::cout << "Running in debug mode" << std::endl;
   #endif

   if(*argv[1] == '-') {
      if(argc < 5)
         printUsageAndDie();
      targetFolder = argv[4];
      algoArg = argv[2];
      thresholdArg = argv[3];
      if(argv[1][1] == 'a') {
         #ifndef DEBUG
         fileHashGrouper.thresholdRequiredForAll = false;
         std::cout << "Threshold will be required to be satisfied for only ONE hash." << std::endl;
         #else
         std::cout << "Threshold behaviour argument ignored because of debug mode." << std::endl;
         #endif
      }
   } else {
      targetFolder = argv[3];
      algoArg = argv[1];
      thresholdArg = argv[2];
   }

   enableHtmlOutput = true;
   std::cout << "HTML Output enabled." << std::endl;

   std::string tmpSelectedAlgorithm(algoArg);
   boost::algorithm::to_lower(tmpSelectedAlgorithm);
   if(boost::iequals(tmpSelectedAlgorithm, "dct"))
      selectedAlgorithm = DCT; 
   if(boost::iequals(tmpSelectedAlgorithm, "mh"))
      selectedAlgorithm = MH;
   if(boost::iequals(tmpSelectedAlgorithm, "radish"))
      selectedAlgorithm = RADISH;
   if(boost::iequals(tmpSelectedAlgorithm, "all"))
      selectedAlgorithm = ALL;
   fileHashGrouper.algorithm = selectedAlgorithm;

   try {
      threshold = boost::lexical_cast<int>(thresholdArg);
      if(threshold > 100.0f || threshold < 1.0f)
         throw 33; //No specific reason for 33, just felt like it
   } catch (std::exception& e) { 
      std::cout << "error : threshold must be between 1 and 100\n\n";
      printUsageAndDie();
   }

   std::cout << "Algorithm : " << tmpSelectedAlgorithm;
   std::cout << ", Threshold : " << threshold << " %" << std::endl;

   fileHashGrouper.threshold = 1-threshold/100;

   std::cout << "Scanning target folder : " << targetFolder << std::endl;
   std::vector<FileHash> fileList;
   listImages(bf::path(targetFolder), fileList);
   std::cout << "Done. " << fileList.size() << " file(s) to scan.\nScanning ...\n";
   int scanned = 0;
   for(int i = 0; i < fileList.size(); i++) {
      fileList[i].compute(selectedAlgorithm);
      printProgressBar(std::floor(((i+1)/static_cast<float>(fileList.size()))*100));
   }
   std::cout << std::endl;
    
   ofstream outputHtml;
   if(enableHtmlOutput) {
      outputHtml.open("results.html");
      if(!outputHtml.is_open()) {
         std::cout << "Error : Could not open 'result.html' for writing, disabling HTML output.";
         std::cout << std::endl;
         enableHtmlOutput = false;
      }
      outputHtml << "<!DOCTYPE html>\n";
      outputHtml << "<html>\n\t<head>\n\t\t<title>Image comparaison result</title>\n";
      outputHtml << "\t\t<link href='style.css' rel='stylesheet' type='text/css'>\n\t</head>\n";
      outputHtml << "\t<body>\n";
      outputHtml << "\t\t<h1>Image comparaison result for " << targetFolder << "</h1>\n";
      outputHtml << "\t\t<h2>" << fileList.size() << " image(s)</h2>\n";
      outputHtml << "\t\t<table>\n";
   }
   
   std::vector<FileHashGroup> groups = fileHashGrouper.computeGroups(fileList);
 
   for(int i = 0; i < groups.size(); i++) {
      if(enableHtmlOutput) {
         outputHtml << "\t\t\t<tr>\n";
         outputHtml << "\t\t\t\t<td>\n";
         groups[i][0].file.printHtml(outputHtml, 4);
         outputHtml << "\t\t\t\t</td>\n";
      }
      #ifdef DEBUG
      std::cout << groups[i][0].file.path() << " ";
      #endif
      for(int j = 1; j < groups[i].elements().size(); j++) {
         if(enableHtmlOutput) {
            outputHtml << "\t\t\t\t<td>\n";
            groups[i][j].file.printHtml(outputHtml, 5);
            outputHtml << "\t\t\t\t<br/><span class='similarity'>";
            outputHtml << groups[i][j].similarity.percentage();
            outputHtml << " %</span>\n";
            outputHtml << "\t\t\t\t</td>\n";
         }
         #ifdef DEBUG
         std::cout << groups[i][j].file.path() << " ";  
         std::cout << "dct : " << groups[i][j].similarity.dct << " | ";
         std::cout << "mh : " << groups[i][j].similarity.mh << " | ";
         std::cout << "radish : " << groups[i][j].similarity.radish << " | "; 
         std::cout << std::endl;
         #endif
      }
      if(enableHtmlOutput)
         outputHtml << "\t\t\t</tr>\n";
   }
   if(enableHtmlOutput) {
      outputHtml << "\t\t</table>\n\t</body>\n</html>";
      outputHtml.close();
      std::cout << "Results saved to 'results.html'" << std::endl;
   }
   std::cout << "Done." << std::endl;
   return 0;
}
Ejemplo n.º 11
0
/**
 * print the provided string and draw the bar with provided percent
 *
 * @param string:	the string to write to
 * @param y:		the y postion of the screen
 * @param color:	the color for the string
 */
void PrettyBoot::updateStatus(const char *string, int percent, uint8_t color)
{
	printCentered(KERNEL_NAME, 0, 32);
	printProgressBar(percent, color);
	printCentered(string, 20, 0x07);
}
Ejemplo n.º 12
0
/**
 * called in case of fail, print a red bar
 *
 * @param string:	the error string to print
 */
void PrettyBoot::fail(const char *string)
{
	printCentered(KERNEL_NAME, 0, 32);
	printProgressBar(100, 0xC0);
	printCentered(string, 20, RED);
}
int main (int argc, char *argv[])
{

  printBoxedMessage("Starting plot generation");

  // ####################
  // ##   Init tools   ##
  // ####################

     // Create a sonic Screwdriver
      SonicScrewdriver s;

     // ##########################
     // ##   Create Variables   ##
     // ##########################

     s.AddVariable("MET",            "MET",                     "GeV",    16,50,530,      &(myEvent.MET),                  "logY");
     s.AddVariable("METPhi",         "METPhi",                  "GeV",    16,50,530,      &(myEvent.METPhi),               "");

     s.AddVariable("MT",             "M_{T}",                   "GeV",    40,0,400,       &(myEvent.MT),                   "");
    /*
     s.AddVariable("MTpeak",         "M_{T}",                   "GeV",    20,0,100,       &(myEvent.MT),                   "noOverflowInLastBin");
     s.AddVariable("MTtail",         "M_{T}",                   "GeV",    30,100,400,     &(myEvent.MT),                   "logY,noUnderflowInFirstBin");
     s.AddVariable("deltaPhiMETJets","#Delta#Phi(MET,j_{1,2})", "rad",    16,0,3.2,       &(myEvent.deltaPhiMETJets),      "");
     s.AddVariable("MT2W",           "M_{T2}^{W}",              "GeV",    20,0,500,       &(myEvent.MT2W),                 "");
     s.AddVariable("HTratio",        "H_{T}^{ratio}",           "",       20,0,1.2,       &(myEvent.HTRatio),              "");
     s.AddVariable("HadronicChi2",   "Hadronic #chi^{2}",       "",       20,0,20,        &(myEvent.hadronicChi2),         "logY");
     s.AddVariable("leadingBPt",     "p_{T}(leading b-jet)",    "GeV",    20,0,400,       &(myEvent.leadingBPt),           "");
     s.AddVariable("leadingJetPt",   "p_{T}(leading jet)",      "GeV",    20,0,600,       &(myEvent.leadingJetPt),         "");
     s.AddVariable("leptonPt",       "p_{T}(lepton)",           "GeV",    28,20,300,      &(myEvent.leadingLeptonPt),      "");
     s.AddVariable("Mlb",            "M'(lb)",                  "GeV",    20,0,500,       &(myEvent.Mlb),                  "");
     s.AddVariable("Mlb_hemi",       "M(lb)",             "GeV",          20,0,500,       &(myEvent.Mlb_hemi),             "");
     s.AddVariable("M3b",            "M3b",                     "GeV",    20,0,1000,      &(myEvent.M3b),                  "");
     s.AddVariable("deltaRLeptonB",  "#DeltaR(l,leading b)",    "",       20,0,5,         &(myEvent.deltaRLeptonLeadingB), "");
     s.AddVariable("HTLeptonPtMET",  "HT + MET + p_{T}(lepton)","GeV",    20,100,2100,    &(myEvent.HTPlusLeptonPtPlusMET),"");
     */
     s.AddVariable("HT",             "H_{T}",                   "",       46,120,1500,    &(myEvent.HT),                   "");
     s.AddVariable("METoverSqrtHT",  "MET / #sqrt{H_{T}}",      "",       32,0,32,        &(myEvent.METoverSqrtHT),        "");

     float leadingNonBPtN4;
     s.AddVariable("leadingNonBPt",     "p_{T}(leading nonb-jet)",    "GeV",    20,0,500,       &(leadingNonBPtN4),           "");
     float leadingNonBPtN5;
     s.AddVariable("leadingNonBPtN5",     "p_{T}(leading nonb-jet) (Njet>4)",    "GeV",    20,0,500,       &(leadingNonBPtN5),           "noUnderflowInFirstBin");

     int nJets, nBtag;

     s.AddVariable("nJets",          "Number of selected jets",               "",       11,0,10,        &(nJets),              "");
     s.AddVariable("nBtag",          "Number of selected b-tagged jets",      "",       5, 0,4,         &(nBtag),              "");
     s.AddVariable("numberOfPrimaryVertices",   "Number of primary vertices", "",       41, 0,40,       &(myEvent.numberOfPrimaryVertices),              "");

     float METPtReso;
     float METdPhiReso;
     s.AddVariable("METPtReso",      "MET p_{T} rel. resolution",         "GeV",    50, 0,5,      &(METPtReso),       "");
     s.AddVariable("METdPhiReso",     "MET #Delta #Phi rel. resolution",          "rad",    50, 0,2,      &(METdPhiReso),      "");

     // #########################################################
     // ##   Create ProcessClasses (and associated datasets)   ##
     // #########################################################

        s.AddProcessClass("1ltop", "1l top",                             "background",kRed-7);
            s.AddDataset("ttbar_powheg",                "1ltop",  0, 0);

            s.AddDataset("singleTop_st",                  "1ltop",  0, 0);

     s.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);

     s.AddProcessClass("W+jets",   "W+jets",                          "background",kOrange-2);
             s.AddDataset("W+jets",    "W+jets", 0, 0);

     s.AddProcessClass("rare",   "rare",                              "background",kMagenta-5);
             s.AddDataset("rare",   "rare", 0, 0);
     /*
     s.AddProcessClass("T2tt", "T2tt (450, 50)",  "signal", COLORPLOT_GREEN );
            s.AddDataset("T2tt", "T2tt",   0, 0);

     s.AddProcessClass("T2bw", "T2bw, x = 0.50 (450, 50)",  "signal", COLORPLOT_MAGENTA );
            s.AddDataset("T2bw-050", "T2bw",   0, 0);
     */
     /*
     s.AddProcessClass("data",   "data",                              "data",COLORPLOT_BLACK);
            s.AddDataset("SingleElec",   "data", 0, 0);
            s.AddDataset("SingleMuon",   "data", 0, 0);
            s.AddDataset("DoubleElec",   "data", 0, 0);
            s.AddDataset("DoubleMuon",   "data", 0, 0);
            s.AddDataset("MuEl",         "data", 0, 0);
     */

     // ##########################
     // ##    Create Regions    ##
     // ##########################

     s.AddRegion("preselection",                  "Preselection",               &goesInPreselection          );
     s.AddRegion("preselection_MTtail",           "Preselection;M_{T} tail",    &goesInPreselectionMTtail    );

     // ##########################
     // ##   Create Channels    ##
     // ##########################

     s.AddChannel("singleLepton", "e/#mu-channels",            &goesInSingleLeptonChannel);

  // ########################################
  // ##       Create histograms and        ##
  // ##  schedule type of plots to produce ##
  // ########################################

     // Create histograms
     s.Create1DHistos();
     s.Add2DHisto("MET","HT");
     s.Add2DHisto("MT","METPtReso");
     s.Add2DHisto("MT","METdPhiReso");
     s.Add2DHisto("MT","numberOfPrimaryVertices");
     s.Add2DHisto("numberOfPrimaryVertices","METdPhiReso");
     s.Add2DHisto("numberOfPrimaryVertices","METPtReso");

     // Schedule plots
     //s.SchedulePlots("1DDataMCComparison");
     s.SchedulePlots("1DStack");
     s.SchedulePlots("1DSuperimposed");
     s.SchedulePlots("2D");
     s.SchedulePlots("1DFrom2DProjection","varX=MT,varY=METPtReso,projectionType=mean,labelY=MET Pt rel. resolution");
     s.SchedulePlots("1DFrom2DProjection","varX=MT,varY=METdPhiReso,projectionType=mean,labelY=MET #Delta #Phi rel. resolution");
     s.SchedulePlots("1DFrom2DProjection","varX=MT,varY=numberOfPrimaryVertices,projectionType=mean,labelY=Number of vertices");
     s.SchedulePlots("1DFrom2DProjection","varX=numberOfPrimaryVertices,varY=METdPhiReso,projectionType=mean,labelY=MET #Delta #Phi rel. resolution");
     s.SchedulePlots("1DFrom2DProjection","varX=numberOfPrimaryVertices,varY=METPtReso,projectionType=mean,labelY=MET Pt rel. resolution");

     // Config plots
     s.SetGlobalBoolOption  ("1DSuperimposed",    "includeSignal",    true   );

     s.SetGlobalStringOption("DataMCComparison",  "includeSignal",    "superimposed");
     s.SetGlobalFloatOption ("DataMCComparison",  "factorSignal",     100.0    );

     s.SetGlobalStringOption("1DStack",           "includeSignal",    "superimposed");
     s.SetGlobalFloatOption ("1DStack",           "factorSignal",     100.0    );

     s.SetGlobalFloatOption ("DataMCRatio",       "min",              0.0    );
     s.SetGlobalFloatOption ("DataMCRatio",       "max",              2.0    );

     s.SetGlobalStringOption("Plot",              "infoTopRight",     "CMS Preliminary");
     s.SetGlobalStringOption("Plot",              "infoTopLeft",      "#sqrt{s} = 8 TeV, L = 19.5 fb^{-1}");

     s.SetGlobalBoolOption  ("Plot",              "exportPdf",        true);
     s.SetGlobalBoolOption  ("Plot",              "exportEps",        false);
     s.SetGlobalBoolOption  ("Plot",              "exportPng",        false);

  // ########################################
  // ##       Run over the datasets        ##
  // ########################################

  vector<string> datasetsList;
  s.GetDatasetList(&datasetsList);

  cout << "   > Reading datasets... " << endl;
  cout << endl;

  for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
  {
     string currentDataset = datasetsList[d];
     string currentProcessClass = s.GetProcessClass(currentDataset);

     sampleName = currentDataset;
     sampleType = s.GetProcessClassType(currentProcessClass);

     // Open the tree
     TFile f((string(FOLDER_BABYTUPLES)+currentDataset+".root").c_str());
     TTree* theTree = (TTree*) f.Get("babyTuple");

     intermediatePointers pointers;
     InitializeBranchesForReading(theTree,&myEvent,&pointers);

     if (sampleType == "signal")
     {
        theTree->SetBranchAddress("mStop",       &(myEvent.mStop));
        theTree->SetBranchAddress("mNeutralino", &(myEvent.mNeutralino));
     }
     else
     {
         myEvent.mStop       = -1;
         myEvent.mNeutralino = -1;
     }

  // ########################################
  // ##        Run over the events         ##
  // ########################################

     bool ttbarDatasetToBeSplitted = false;
      if (findSubstring(currentDataset,"ttbar"))
          ttbarDatasetToBeSplitted = true;

      int nEntries = theTree->GetEntries();
      for (int i = 0 ; i < nEntries ; i++)
      {
          //if (i > float(nEntries) * 0.1) break;

          if (i % (nEntries / 50) == 0) printProgressBar(i,nEntries,currentDataset);

          // Get the i-th entry
          ReadEvent(theTree,i,&pointers,&myEvent);

          nJets = myEvent.nJets;
          nBtag = myEvent.nBTag;

          float weight = getWeight();

          // Split 1-lepton ttbar and 2-lepton ttbar
          string currentProcessClass_ = currentProcessClass;
          if (ttbarDatasetToBeSplitted && (myEvent.numberOfGenLepton == 2))
              currentProcessClass_ = "ttbar_2l";

          #ifdef LEADING_NON_B_PT_ALREADY_COMPUTED
          leadingNonBPtN4= myEvent.leadingNonBPt;
          #else
          leadingNonBPtN4= leadingNonBPt();
          #endif
          leadingNonBPtN5=-1;
          if (nJets>4) leadingNonBPtN5= leadingNonBPtN4;

          if ((currentProcessClass_ == "T2tt") && ((myEvent.mStop != 450) || (myEvent.mNeutralino != 50))) continue;
          if ((currentProcessClass_ == "T2bw") && ((myEvent.mStop != 450) || (myEvent.mNeutralino != 50))) continue;

          computeGenInfo();
          METPtReso   = myEvent.MET    / myEvent.genMET;
          METdPhiReso = abs(Phi_mpi_pi(myEvent.METPhi - myEvent.leadingLepton.Phi())) / myEvent.genMETdPhi;

          s.AutoFillProcessClass(currentProcessClass_,weight);
      }

      printProgressBar(nEntries,nEntries,currentDataset);
      cout << endl;
      f.Close();

  }
/*
  // #############################
  // ##   Apply scale factors   ##
  // #############################

    Table scaleFactors = Table("../prediction/scaleFactors/preselection.tab");

    Figure SF_pre           = scaleFactors.Get("value","SF_pre");
    Figure SF_post          = scaleFactors.Get("value","SF_post");
    Figure SF_0btag         = scaleFactors.Get("value","SF_0btag");
    Figure SF_vetopeak      = scaleFactors.Get("value","SF_vetopeak");
    Figure SF_MTtail_1ltop  = scaleFactors.Get("value","SF_MTtail_1ltop");
    Figure SF_MTtail_Wjets  = scaleFactors.Get("value","SF_MTtail_Wjets");

    s.ApplyScaleFactor("ttbar_2l", "preselection_MTtail_withCorr",  "singleLepton", SF_pre);
    s.ApplyScaleFactor("1ltop",    "preselection_MTtail_withCorr",  "singleLepton", SF_post * SF_MTtail_1ltop);
    s.ApplyScaleFactor("W+jets",   "preselection_MTtail_withCorr",  "singleLepton", SF_post * SF_MTtail_Wjets);
*/
  // ###################################
  // ##   Make plots and write them   ##
  // ###################################

  cout << endl;
  cout << "   > Making plots..." << endl;
  s.MakePlots();
  cout << "   > Saving plots..." << endl;
  s.WritePlots("./plots/METresolution/");

  printBoxedMessage("Plot generation completed");

  // #############################
  // ##   Post-plotting tests   ##
  // #############################

  printBoxedMessage("Program done.");
  return (0);
}
Ejemplo n.º 14
0
/**
 * Main method (Duh ;) ) Runs the whole simulation. Main loop runs in this method
 *
 * @param argc number of command line arguments
 * @param argsv[] command line parameters. Several Config file parameters can be overriden by setting them here. "--visualize" is especially cool, as it shows an OpenGL live view
 *
 * @return 0 if successful
 */
int main(int argc, char* argsv[]) {
	if (argc > 1 && (!strcmp(argsv[1], "-?") || !strcmp(argsv[1], "help") || !strcmp(argsv[1], "--help"))) {
		std::cout << "This is the NUKULAR Simulator" << std::endl;
		std::cout << "Authors: " << std::endl;
		std::cout << "\tLeonhard Rannabauer" << std::endl;
		std::cout << "\tJakob Weiss" << std::endl;
		std::cout << "\tAlexander Winkler" << std::endl;
		std::cout << std::endl;
		std::cout << "By default, configuration will be loaded from a configuration file." << std::endl;
		std::cout << "The CWD will be searched for \"config.cfg\". Override this by specifying the" << std::endl;
		std::cout << "\t-configFile command line parameter with the path to your own configuration" << std::endl;
		std::cout << "\t(either .xml or .cfg format)" << std::endl;
		std::cout << std::endl;
		std::cout << "EXAMPLE: ./MolSim -configFile simulationConfig.xml -outputFilePrefix MD_sim -endTime 10" << std::endl;
		std::cout << std::endl;
		std::cout << "\t will load Settings from simulationConfig.xml, simulate the world for 10 seconds" << std::endl;
		std::cout << "\t and output the files with a prefix of \"MD_sim\", which will lead to files like" << std::endl;
		std::cout << "\t\"MD_sim_0010.vtu\"" << std::endl;
		return 0;
	}

	std::cout << "Initializing the logger..." << std::endl << std::flush;
	//Initialize the logging stuff
	initializeLogger();


	Settings::initSettings(argc, argsv);

	LOG4CXX_TRACE(rootLogger, "Settings initialized!");

#ifdef _OPENMP
	if(Settings::numThreads > 0) {
		LOG4CXX_INFO(rootLogger, "Setting OpenMP Threads to " << Settings::numThreads);
		omp_set_num_threads(Settings::numThreads);
	}
	else {
		LOG4CXX_INFO(rootLogger, "Running on " << omp_get_max_threads() << " threads");
		Settings::numThreads = omp_get_max_threads();
	}
#else
	Settings::numThreads = 1;
	LOG4CXX_INFO(rootLogger, "Running serial version!");
#endif

#ifdef PAPI_BENCH
	for(int i=0; i < Settings::numThreads; i++) {
		char fileName[200];
		sprintf(fileName, "CalcF #%i.txt", i);
		papiCalcFCounters[i] = new PapiEnv(fileName);
		sprintf(fileName, "CalcX #%i.txt", i);
		papiCalcXCounters[i] = new PapiEnv(fileName);
	}	
#endif
	//Check if we should be executing some unit tests
	if(!Settings::testCase.empty()) {
		return executeTests();
	}

	LOG4CXX_TRACE(rootLogger, "Creating Simulator instance...");
	Simulator *sim = new Simulator();
#ifndef NOGLVISUALIZER
	outputWriter::theSimulator = sim;
#endif
	//Check if we should initialize with old state file
	if(Settings::inputFile.size() !=0){
		std::cout << "state found"<<std::endl;
	}



	double current_time = Settings::startTime;

	int iteration = 0;

	int benchmarkStartTime = getMilliCount();
	double timeForOneIteration = 0;

	 // for this loop, we assume: current x, current f and current v are known
	int maxIterations = (Settings::endTime - Settings::startTime) / Settings::deltaT;
	int nextProgressBarDraw = 1;
	int iterationsPerPercent = (maxIterations/100) + 1;

	LOG4CXX_INFO(rootLogger, "Will calculate " <<  maxIterations << " iterations and output " << maxIterations/Settings::outputFrequency << " frames ");


	while (current_time < Settings::endTime) {
		if (iteration % Settings::outputFrequency == 0) {
			sim->plotParticles(iteration + Settings::outputFileIterationOffset);
		}
		sim->nextTimeStep();
		iteration++;
		if(iteration == nextProgressBarDraw) {
			nextProgressBarDraw+=iterationsPerPercent;
			printProgressBar(100*iteration/maxIterations, -(benchmarkStartTime - getMilliCount()));
		}
		LOG4CXX_TRACE(rootLogger, "Iteration " << iteration << " finished.");
		current_time += Settings::deltaT;
		timeForOneIteration = ((double)(benchmarkStartTime - getMilliCount()))/iteration;

#ifndef NOGLVISUALIZER
		while(outputWriter::renderingPaused)		usleep(2000);
#endif

#ifdef PAPI_BENCH
		for(int i=0; i < Settings::numThreads; i++) {
			papiCalcFCounters[i]->printResults();
			papiCalcXCounters[i]->printResults();
			papiCalcFCounters[i]->reset();
			papiCalcXCounters[i]->reset();
		}
#endif
	}


	int benchmarkEndTime = getMilliCount();

	if(Settings::saveLastState)
		sim->exportPhaseSpace();
	if(Settings::printStatistics)
		sim->exportStatistics();

	LOG4CXX_INFO(rootLogger, "Simulation finished. Took " << (benchmarkEndTime - benchmarkStartTime)/1000.0 << " seconds");

	delete sim;


	LOG4CXX_DEBUG(rootLogger, "Created " << Particle::createdInstances << " Particle instances (" << Particle::createdByCopy << " by copy)");
	LOG4CXX_DEBUG(rootLogger, "Destroyed " << Particle::destroyedInstances << " Particle instances");

#ifdef PAPI_BENCH
	
	for(int i=0; i < Settings::numThreads; i++) {
		std::cout << "Writing PAPI output for thread " << i << std::endl;
		papiCalcFCounters[i]->createResultFile();
		papiCalcXCounters[i]->createResultFile();
		delete 	papiCalcFCounters[i];
		delete papiCalcXCounters[i];
	}	
#endif
	//10 is arbitrarily chosen. there will always be some stray particles because of
	//static instances that will be destroyed at program exit
#ifndef NOGLVISUALIZER
	if(Particle::createdInstances - Particle::destroyedInstances - outputWriter::render3dParticles.size() > 10) {
#else
	if(Particle::createdInstances - Particle::destroyedInstances > 10) {
#endif
		LOG4CXX_WARN(rootLogger, "Significant mismatch between created and destroyed particle instances. This can be a memory leak! " << (Particle::createdInstances - Particle::destroyedInstances));
	}

	LOG4CXX_DEBUG(rootLogger, "output written. Terminating...");
	return 0;
}


int executeTests() {
	std::cout << "Running tests..." << std::endl;

	CppUnit::TextUi::TestRunner runner;

	bool all = !Settings::testCase.compare("all");

	if(all || !Settings::testCase.compare("ParticleContainer"))
	  runner.addTest(ParticleContainerTests::suite());

	if(all || !Settings::testCase.compare("ParticleGenerator"))
		 runner.addTest(ParticleGeneratorTests::suite());

//	if(all || !Settings::testCase.compare("Settings"))
//		 runner.addTest(SettingsXsdTest::suite());


	if(all || !Settings::testCase.compare("Matrix"))
		 runner.addTest(MatrixTests::suite());

	runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
													   std::cerr ) );
	// Run the tests.
	bool wasSuccessful = runner.run();

	// Return error code 1 if the one of test failed.
	if(wasSuccessful) {
	  std::cout << "Tests ok!" << std::endl;
	}
	else {
		std::cout << "Some tests failed!" << std::endl;
	}

	return wasSuccessful ? 0 : 1;
}