Example #1
0
//_____________________________________________________________________________
void ProofSimple::Begin(TTree * /*tree*/)
{
   // The Begin() function is called at the start of the query.
   // When running with PROOF Begin() is only called on the client.
   // The tree argument is deprecated (on PROOF 0 is passed).

   TString option = GetOption();
   Ssiz_t iopt = kNPOS;

   // Histos array
   if (fInput->FindObject("ProofSimple_NHist")) {
      TParameter<Long_t> *p =
         dynamic_cast<TParameter<Long_t>*>(fInput->FindObject("ProofSimple_NHist"));
      fNhist = (p) ? (Int_t) p->GetVal() : fNhist;
   } else if ((iopt = option.Index("nhist=")) != kNPOS) {
      TString s;
      Ssiz_t from = iopt + strlen("nhist=");
      if (option.Tokenize(s, from, ";") && s.IsDigit()) fNhist = s.Atoi();
   }
   if (fNhist < 1) {
      Abort("fNhist must be > 0! Hint: proof->SetParameter(\"ProofSimple_NHist\","
            " (Long_t) <nhist>)", kAbortProcess);
      return;
   }

   if (fInput->FindObject("ProofSimple_NHist3")) {
      TParameter<Long_t> *p =
         dynamic_cast<TParameter<Long_t>*>(fInput->FindObject("ProofSimple_NHist3"));
      fNhist3 = (p) ? (Int_t) p->GetVal() : fNhist3;
   } else if ((iopt = option.Index("nhist3=")) != kNPOS) {
      TString s;
      Ssiz_t from = iopt + strlen("nhist3=");
      if (option.Tokenize(s, from, ";") && s.IsDigit()) fNhist3 = s.Atoi();
   }

   // Ntuple
   TNamed *nm = dynamic_cast<TNamed *>(fInput->FindObject("ProofSimple_Ntuple"));
   if (nm) {

      // Title is in the form
      //         merge                  merge via file
      //           |<fout>                      location of the output file if merge
      //           |retrieve                    retrieve to client machine
      //         dataset                create a dataset
      //           |<dsname>                    dataset name (default: dataset_ntuple)
      //         |plot                  for a final plot
      //         <empty> or other       keep in memory

      fHasNtuple = 1;
      
      TString ontp(nm->GetTitle());
      if (ontp.Contains("|plot") || ontp == "plot") {
         fPlotNtuple = kTRUE;
         ontp.ReplaceAll("|plot", "");
         if (ontp == "plot") ontp = "";
      }
      if (ontp.BeginsWith("dataset")) fHasNtuple = 2;
   }
}
Example #2
0
void TExpenser::calculate_balance() {

    fBalanceXMLParser -> selectMainNode();
    fBalanceXMLParser -> selectNode("entry");
    TString balance = fBalanceXMLParser -> getNodeContent("amount");
    fBalanceXMLParser -> selectNode("date");
    TString balance_year = fBalanceXMLParser -> getNodeContent("year");
    TString balance_month = fBalanceXMLParser -> getNodeContent("month");

    fLastStatusLabel -> SetText(balance_month+"/"+balance_year+": " + balance + " eur");

    // now calculate the current balance (last - expenses since the last)
    TDatime time;

    fXMLParser->selectMainNode();
    fXMLParser->selectNode("expense");
    Double_t expenses_since_last_status = 0;
    while (fXMLParser->getCurrentNode() != 0) {
        XMLNodePointer_t current_node = fXMLParser->getCurrentNode();

        fXMLParser -> selectNode("date");
        TString year = fXMLParser -> getNodeContent("year");
        TString month = fXMLParser -> getNodeContent("month");
        fXMLParser -> setCurrentNode(current_node);

        bool year_more_recent = (year.Atoi() > balance_year.Atoi());
        bool year_same = (year.Atoi() == balance_year.Atoi());
        bool month_more_recent = (month.Atoi()>=balance_month.Atoi());
        bool expense_more_recent_than_balance = (year_more_recent || (year_same && month_more_recent));
        if (  expense_more_recent_than_balance && fXMLParser -> getNodeContent("withdrawn") == "Yes" ) {
            expenses_since_last_status += fXMLParser -> getNodeContent("amount").Atof();
        }

        fXMLParser->selectNextNode("expense");
    }

    // calculate total income since last balance
    fIncomeXMLParser->selectMainNode();
    fIncomeXMLParser->selectNode("entry");
    Double_t income_since_last_status = 0;
    while (fIncomeXMLParser->getCurrentNode() != 0) {
        XMLNodePointer_t current_node = fIncomeXMLParser->getCurrentNode();

        fIncomeXMLParser -> selectNode("date");
        TString year = fIncomeXMLParser -> getNodeContent("year");
        TString month = fIncomeXMLParser -> getNodeContent("month");
        fIncomeXMLParser -> setCurrentNode(current_node);

        if ( ( (month.Atoi()>=balance_month.Atoi()) && (year.Atoi()==balance_year.Atoi()) ) || (year.Atoi()>balance_year.Atoi()) ) {
            income_since_last_status += fIncomeXMLParser -> getNodeContent("amount").Atof();
        }

        fIncomeXMLParser->selectNextNode("entry");
    }

    Double_t new_balance = balance.Atof() - expenses_since_last_status + income_since_last_status;
    fCurrentStatusLabel -> SetText(toStr(time.GetDay())+"/"+toStr(time.GetMonth())+"/"+toStr(time.GetYear())+": " + toStr(new_balance,2) + " eur");
}
Example #3
0
void TExpenser::createExpensesTableInterface() {

    // create table interface
    const unsigned ncolumns =  6;
    fTableInterface = new TGExpenserTableInterface(ncolumns);
    TString columns[ncolumns]={"amount", "category", "description", "withdrawn","date", "id"};
    fTableInterface -> setColumnNames(columns);

    fXMLParser->selectMainNode();
    fXMLParser->selectNode("expense");
    vector<expense> expenses;
    while (fXMLParser->getCurrentNode() != 0) {
        XMLNodePointer_t current_node = fXMLParser->getCurrentNode();

        fXMLParser -> selectNode("date");
        TString year = fXMLParser -> getNodeContent("year");
        TString month = fXMLParser -> getNodeContent("month");
        TString day = fXMLParser -> getNodeContent("day");
        fXMLParser -> setCurrentNode(current_node);

        if (month.Atoi()<10) month="0"+month;
        if (day.Atoi()<10) day="0"+day;

        expense ex;
        ex.amount = fXMLParser -> getNodeContent("amount");
        ex.category = fXMLParser -> getNodeContent("category");
        ex.description = fXMLParser -> getNodeContent("description");
        ex.withdrawn = fXMLParser -> getNodeContent("withdrawn");
        ex.date = year+month+day;
        ex.dateForCell  = day+"/"+month+"/"+year;
        ex.id  = fXMLParser -> getNodeContent("id");

        fXMLParser->selectNextNode("expense");

        if (fFilterActive) {
            if ( fFilterCategory != "any" && ex.category != fFilterCategory) continue;
            if ( fFilterMonth != "any" && MONTHS[month.Atoi()-1] != fFilterMonth) continue;
            if ( fFilterYear != "any" && year != fFilterYear) continue;
            if ( fFilterWithdrawn != "any" && fFilterWithdrawn != ex.withdrawn ) continue;
            if ( ! ex.description.Contains(fFilterDescription, TString::kIgnoreCase) ) continue;
        }

        expenses.push_back(ex);
    }

    sort(expenses.begin(), expenses.end(), compare);

    for (unsigned i=0; i<expenses.size(); i++) {
        fTableInterface -> addCell (i, expenses[i].amount);
        fTableInterface -> addCell (i, expenses[i].category);
        fTableInterface -> addCell (i, expenses[i].description);
        fTableInterface -> addCell (i, expenses[i].withdrawn);
        fTableInterface -> addCell (i, expenses[i].dateForCell);
        fTableInterface -> addCell (i, expenses[i].id);
    }
    fTableEntries = expenses.size();

}
Example #4
0
void GausBF::Print(Option_t *option) const
{
  TString sopt = option; sopt.ToLower();
  if (sopt == "dump") {
    for (Int_t i = 0; i < Ns1*Ns9*Np; i++) {
      cout << Form(" %10.3e,", _par[i]);
      if (i%6 == 5) cout << endl;
    }
    cout << endl;
  }
  if (sopt.BeginsWith("p")) {
    TString ss = sopt(1, 2);
    if (ss.IsDigit()) {
      Int_t ip = ss.Atoi();
      if (0 <= ip && ip < Np)
	for (Int_t i = 0; i < Ns1; i++) {
	  for (Int_t j = 0; j < Ns9; j++) {
	    AMSPoint p1 = GetP1(i);
	    AMSPoint p9 = GetP9(j);
	    cout << Form("%3d %3d %6.2f %6.2f %7.2f %7.2f %10.3e",
			 i, j, p1.x(), p1.y(),
			       p9.x(), p9.y(), _par[(i*Ns9+j)*Np+ip]) << endl;
	  }
	}
    }
  }
}
Example #5
0
int filechk(string fname)
{
  //TFile f("DQM_V0001_SiStrip_R000062940.root");
  TFile f(fname.c_str());

  if (f.IsZombie()){
    //cout << "File corrupted" << endl;
  return -1;
  }
  else
  {
    if ( fname.find("_SiStrip_") != string::npos ){
      TString rnStr = fname.substr(fname.find("_R") + 2, 9);
      TString runDirStr("Run ");
      runDirStr += rnStr.Atoi();
      TDirectoryFile* runDir = (TDirectoryFile*)f.FindObjectAny(runDirStr);
      if ( runDir == 0 )
        return 0; 
      
      TDirectoryFile* tracking = (TDirectoryFile*)runDir->FindObjectAny("Tracking");
      if ( tracking == 0 )
        return 0;
      
      TDirectoryFile* sistrip = (TDirectoryFile*)runDir->FindObjectAny("SiStrip");
      if ( sistrip == 0 )
        return 0;  
       
      TDirectoryFile* hist = (TDirectoryFile*)tracking->FindObjectAny("reportSummaryMap");
      if ( hist == 0 )
        return 0;
       
      hist = (TDirectoryFile*)sistrip->FindObjectAny("reportSummaryMap");
      if ( hist == 0 )
        return 0; 
      
      return 1;
    }
    
    //TH2F* hist;
    //hist = (TH2F*)f.FindObjectAny("reportSummaryMap");
    TDirectoryFile* hist;	
    //hist = (TDirectoryFile*)f.FindObjectAny("reportSummaryContents");
    hist = (TDirectoryFile*)f.FindObjectAny("reportSummaryMap");
    if (0 == hist) 
    {
      TDirectoryFile* hist2;
      hist2 = (TDirectoryFile*)f.FindObjectAny("EventInfo");
      if (0 != hist2)
        return 1;

      //cout << "File is incomplete" << endl;
      return 0;
    }
    else
    {
      //cout << "File is OK" << endl;
      return 1;
    }
  }
}
Example #6
0
inline void parseAndSet_b(const TString& input, TString arg, bool& value) {
  TString newval = parseArg(input, arg);
  if (!newval.IsNull()) {
    if (newval.IsBin()) value = newval.Atoi();
    else if (newval == "true") value = true;
    else if (newval == "false") value = false;
  }
}
void transferxSecFromTextToROOT(std::string inputStr="xSec_T3G.txt"){

   ifstream fin(inputStr.c_str());
   char line[200];
   TFile *xSecProspinoFile =0;
   TH1D *xSecProspino =0; 
   int minMom = 1000000, maxMom = 0;
   int nBins = 0;

   std::vector<int> momVec; std::vector<double> xSecVec, xSecErrVec;
   while( fin.getline(line, 200) ){
      TString lineT(line);
      if( lineT.Contains("Interactions") ) continue;
      TObjArray *vlist = lineT.Tokenize(" ");
      int nEntries = vlist->GetEntries();
      int mMom;
      double xSec =0, xSecRelErr =0;
      for(int ie=0; ie<nEntries; ie++){
         TObjString* perObj = dynamic_cast<TObjString*>(vlist->At(ie));
         TString perStr = perObj->GetString();
         if( ie==0 ){
            mMom = perStr.Atoi();
            if( minMom > mMom ) minMom = mMom;
            if( maxMom < mMom ) maxMom = mMom;
         }
         if( ie==1 ) xSec = perStr.Atof();
         if( ie==2 ) xSecRelErr = perStr.Atof();
      }
      nBins ++;
      momVec.push_back(mMom); xSecVec.push_back(xSec); xSecErrVec.push_back(xSec*xSecRelErr/100.);
//      std::cout<<"mMom : "<<mMom<<"  xSec : "<<xSec<<"  xSecRelErr : "<<xSecRelErr<<std::endl;
   }
   double divBin = 1.0*(maxMom - minMom)/(nBins-1);
   double lowMom = minMom-divBin/2.0, highMom = maxMom+divBin/2.0;
   std::cout<<"nBins : "<<nBins<<"  minMom : "<<minMom<<"  maxMom : "<<maxMom<<"  divBin : "<<divBin<<"  lowMom : "<<lowMom<<"  highMom : "<<highMom<<std::endl;

   TString rootStrT(inputStr);
   rootStrT.ReplaceAll("txt", "root");

   std::cout<<"root file : "<<rootStrT<<std::endl;
   xSecProspinoFile = new TFile(rootStrT, "RECREATE");

   if( rootStrT.Contains("T1") ) xSecProspino = new TH1D("gluino_xsection", "gluino_xsection", nBins, lowMom, highMom);
   if( rootStrT.Contains("T2") ) xSecProspino = new TH1D("squark_xsection", "squark_xsection", nBins, lowMom, highMom);
   if( rootStrT.Contains("T3G") ) xSecProspino = new TH1D("stop_xsection", "stop_xsection", nBins, lowMom, highMom);

   for(int iv=0; iv<(int)momVec.size(); iv++){
      double mMom = (double)momVec[iv];
      int ib = xSecProspino->FindFixBin(mMom);
      xSecProspino->SetBinContent(ib, xSecVec[iv]);
      xSecProspino->SetBinError(ib, xSecErrVec[iv]);
   }

//   xSecProspino->Write();
   xSecProspinoFile->Write(); xSecProspinoFile->Close();

}
Example #8
0
void TTSelector::Begin(TTree *){
  TString option = GetOption();
  TObjArray *strobj = option.Tokenize(" ");
  gTrigger = ((TObjString*)strobj->At(0))->GetString().Atoi();
  
  gMode = ((TObjString*)strobj->At(1))->GetString().Atoi();
  CreateMap();
  TString filedir=ginFile;
  filedir.Remove(filedir.Last('.')-4);
  fFile = new TFile(goutFile,"RECREATE");
  fTree = new TTree("M","Tree for GSI Prt Analysis");  
  fEvent = new TPrtEvent();
  fTree->Branch("TPrtEvent", "TPrtEvent", &fEvent, 64000, 2);

  TFile f(gcFile);
  TIter nextkey(f.GetListOfKeys());
  TKey *key;

  while ((key = (TKey*)nextkey())) {
    TGraph *gr = (TGraph*)key->ReadObj();
    TString name = gr->GetName();
    Int_t channel = name.Atoi();

    gGr[channel]= new TGraph(*gr);
  }
  f.Close();

  if(gMode == 1){
    TFile f2(gtFile);
    TIter nextkey2(f2.GetListOfKeys());
    TKey *key2;

    while ((key2 = (TKey*)nextkey2())) {
      TGraph *gr = (TGraph*)key2->ReadObj();
      TString name = gr->GetName();
      Int_t channel = name.Atoi();

      gGrDiff[channel]= new TGraph(*gr);
    }
    f2.Close();
  }
  std::cout<<"Initialization successful"<<std::endl;
  
}
Example #9
0
void RunCreateMap() {

  cout << "RunCreateMap" << endl; 

  TString DataRangeString = gSystem->Getenv("DATARANGE");
  int DataRange = DataRangeString.Atoi() - 1; 

  CreateMap(false, DataRange);

}
TString get_sample_name(TString name)
{
  TObjArray* arr = name.Tokenize(".");
  
  TString out = ((TObjString*)arr->At(arr->GetEntries()-2))->GetString();
  out.ReplaceAll("_JER_up", "");
  out.ReplaceAll("_JER_down", "");
  out.ReplaceAll("_JEC_up", "");
  out.ReplaceAll("_JEC_down", "");

  out.ReplaceAll("_PU_down", "");
  out.ReplaceAll("_PU_up", "");
  out.ReplaceAll("_LJets_up", "");
  out.ReplaceAll("_LJets_down", "");
  out.ReplaceAll("_BJets_up", "");
  out.ReplaceAll("_BJets_down", "");
  out.ReplaceAll("_MuonSF_down", "");
  out.ReplaceAll("_MuonSF_up", "");
  out.ReplaceAll("_BJets_down", "");
  out.ReplaceAll("_BJets_down", "");
  out.ReplaceAll("_matching_down", "");
  out.ReplaceAll("_matching_up", "");
  out.ReplaceAll("_scale_down", "");
  out.ReplaceAll("_scale_up", "");

  out.ToLower();

  out.ReplaceAll("dyjets_50toinf", "zlight");
  out.ReplaceAll("dyjets", "zlight");
  out.ReplaceAll("dy", "zlight");
  out.ReplaceAll("wjets_bflavor", "wb");
  out.ReplaceAll("wjets_cflavor", "wc");
  out.ReplaceAll("wjets_lflavor", "wlight");
  //out.ReplaceAll("tt", "ttbar");

  
  if (out.Contains("zp")){
    TString temp = out;
    temp.ReplaceAll("zp","");
    temp.ReplaceAll("p", ".");
    TObjArray* arr2 = temp.Tokenize("w");
    TString nom = ((TObjString*)arr2->At(1))->GetString();
    TString denom = ((TObjString*)arr2->At(0))->GetString();
    cout << "nom = " << nom << " denom = " << denom << endl;
    Int_t p = (100*nom.Atof())/denom.Atof();
    cout << "p = " << p << endl;
    out = TString::Format("zp %d w %d p",denom.Atoi(), p);
    out.ReplaceAll(" ", "");
  }
  
  return out;
}
Example #11
0
void DecodeRunlist(const TString &val){
        //
        // Tokenize run list
        //
        TObjArray *runstrings = val.Tokenize(",");
        TObjString *os;
        TString runstr;
        TIter runIter(runstrings);
        g_runlist.Set(runstrings->GetEntries());
        int nruns(0);
        while((os = dynamic_cast<TObjString *>(runIter()))){
                runstr = os->String();
                g_runlist[nruns++] = runstr.Atoi();
        }
        delete runstrings;
}
//_____________________________________________________________________________
void ProofSimpleFile::Begin(TTree * /*tree*/)
{
   // The Begin() function is called at the start of the query.
   // When running with PROOF Begin() is only called on the client.
   // The tree argument is deprecated (on PROOF 0 is passed).

   TString option = GetOption();

   // Number of histograms (needed in terminate)
   if (fInput->FindObject("ProofSimpleFile_NHist")) {
      TParameter<Long_t> *p =
         dynamic_cast<TParameter<Long_t>*>(fInput->FindObject("ProofSimpleFile_NHist"));
      fNhist = (p) ? (Int_t) p->GetVal() : fNhist;
   } else if ((iopt = option.Index("nhist=")) != kNPOS) {
      TString s;
      Ssiz_t from = iopt + strlen("nhist=");
      if (option.Tokenize(s, from, ";") && s.IsDigit()) fNhist = s.Atoi();
   }
}
Example #13
0
void runCalibSummary(TString runNumberString ="0")
{

  Int_t irun = runNumberString.Atoi();

  // Load libraries
  gSystem->Load("libANALYSIS");
  gSystem->Load("libTPCcalib");

  // Configure OCDB
  gROOT->LoadMacro("ConfigOCDB.C");
  ConfigOCDB(irun);

  // run extraction of the calibration summary ...
  AliTPCcalibSummary *calibSummary = new AliTPCcalibSummary;
  calibSummary->ProcessRun(irun);
  delete calibSummary;

  return;
}
Example #14
0
// ======= FIXME: Hall A lib ================================================
//_____________________________________________________________________________
Int_t TrigBitLoc::Configure( const TObjArray* params, Int_t start )
{
  // Initialize CrateLoc from given parmeters

  // Load name, crate, slot, channel
  Int_t ret = CrateLocMulti::Configure( params, start );
  if( ret )
    return ret;

  // Additional parameters: lower and upper TDC cuts
  cutlo = GetString( params, start+4 ).Atoi();
  cuthi = GetString( params, start+5 ).Atoi();
  
  // The bit number is determined from any trailing digits of the name,
  // which must be in the range 0-31
  assert( fName.Length() > 0 ); // else bug in base class Configure()
  Int_t pos = fName.Length()-1, end = pos;
  TString e;
  do {
    e = fName(pos); 
  } while( e.IsDigit() && pos-- > 0 );
  if( pos == end ) { // No digits at the end of the name
    Error( "TrigBitLoc", "Name of trigger bit variable %s must end with bit "
	   "number (0-31). Example: \"bit12\". Fix database.", GetName() );
    return 50;
  }
  e = fName(pos+1,end-pos);
  Int_t val = e.Atoi();
  if( val < 0 || val > 31 ) {
    Error( "TrigBitLoc", "Illegal bit number %d in trigger bit name %s. "
	   "Must be 0-31. Fix database.", val, GetName() );
    return 50;
  }
  bitnum = val;
  
  return 0;
}
Example #15
0
void FillVZEROEPOADBFull(const char* filename = "AOD083.txt", Bool_t mbOnly = kFALSE)
{
  gSystem->Load("libCore");
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  gSystem->Load("libMinuit");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libESD");
  gSystem->Load("libAOD");
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");   
  gSystem->Load("libOADB");

  AliOADBContainer * oadbCont = new AliOADBContainer("vzeroEP");

  {
    TList *defaultList = new TList;
    defaultList->SetName("Default");
    TProfile *profHisto = NULL;
    TFile fInputDefault("minbias/VZERO.EPFlatenning.PS.LHC11h_AOD083_000170162.root");
    TList *inputList = (TList*)fInputDefault.Get("coutput");
    for(Int_t i = 0; i < 11; ++i) {
      profHisto = (TProfile*)inputList->FindObject(Form("fX2_%d",i))->Clone(Form("fX2_%d",i));
      profHisto->SetDirectory(0);
      defaultList->Add(profHisto);
      profHisto = (TProfile*)inputList->FindObject(Form("fY2_%d",i))->Clone(Form("fY2_%d",i));
      profHisto->SetDirectory(0);
      defaultList->Add(profHisto);
      profHisto = (TProfile*)inputList->FindObject(Form("fX2Y2_%d",i))->Clone(Form("fX2Y2_%d",i));
      profHisto->SetDirectory(0);
      defaultList->Add(profHisto);
      profHisto = (TProfile*)inputList->FindObject(Form("fCos8Psi_%d",i))->Clone(Form("fCos8Psi_%d",i));
      profHisto->SetDirectory(0);
      defaultList->Add(profHisto);
    }
    fInputDefault.Close();
    oadbCont->AddDefaultObject(defaultList);
    printf("Run 170162 filled\n");
  }

  {
    TList *list1 = new TList;
    TProfile *profHisto = NULL;
    TFile fInput1("minbias/VZERO.EPFlatenning.PS.LHC11h_AOD083_000169683.root");
    TList *inputList = (TList*)fInput1.Get("coutput");
    for(Int_t i = 0; i < 11; ++i) {
      profHisto = (TProfile*)inputList->FindObject(Form("fX2_%d",i))->Clone(Form("fX2_%d",i));
      profHisto->SetDirectory(0);
      list1->Add(profHisto);
      profHisto = (TProfile*)inputList->FindObject(Form("fY2_%d",i))->Clone(Form("fY2_%d",i));
      profHisto->SetDirectory(0);
      list1->Add(profHisto);
      profHisto = (TProfile*)inputList->FindObject(Form("fX2Y2_%d",i))->Clone(Form("fX2Y2_%d",i));
      profHisto->SetDirectory(0);
      list1->Add(profHisto);
      profHisto = (TProfile*)inputList->FindObject(Form("fCos8Psi_%d",i))->Clone(Form("fCos8Psi_%d",i));
      profHisto->SetDirectory(0);
      list1->Add(profHisto);
    }
    oadbCont->AppendObject(list1, 169683, 169683);
    printf("Run 169683 filled\n");
  }

  // loop of over all other runs
  Int_t runList[500];
  ifstream *fruns = new ifstream (filename);
  if (!*fruns) return;
  TString strLine;
  Int_t count = 0;
  while (strLine.ReadLine(*fruns)) {
    runList[count++] = strLine.Atoi();
  }
  delete fruns;

  for(Int_t irun = 0; irun < count; ++irun) {
    TList *list2 = new TList;
    TProfile *profHisto = NULL;
    TFile fInput2(Form("csemi/VZERO.EPFlatenning.PS.LHC11h_AOD083_000%d.root",runList[irun]));
    TList *inputList = (TList*)fInput2.Get("coutput");
    TFile fInput3(Form("cpbi2/VZERO.EPFlatenning.PS.LHC11h_AOD083_000%d.root",runList[irun]));
    TList *inputListBis = (TList*)fInput3.Get("coutput");
    for(Int_t i = 0; i < 11; ++i) {
      profHisto = (TProfile*)inputList->FindObject(Form("fX2_%d",i))->Clone(Form("fX2_%d",i));
      profHisto->SetDirectory(0);
      Int_t ibin = profHisto->FindBin(62.5);
      profHisto->SetBinContent(ibin,0);
      profHisto->SetBinError(ibin,0);
      profHisto->SetBinEntries(ibin,0);
      if (mbOnly) {
	profHisto = (TProfile*)inputListBis->FindObject(Form("fX2_%d",i))->Clone(Form("fX2_%d",i));
	profHisto->SetDirectory(0);
      }
      else
	profHisto->Add((TProfile*)inputListBis->FindObject(Form("fX2_%d",i)));
      list2->Add(profHisto);

      profHisto = (TProfile*)inputList->FindObject(Form("fY2_%d",i))->Clone(Form("fY2_%d",i));
      profHisto->SetDirectory(0);
      profHisto->SetBinContent(ibin,0);
      profHisto->SetBinError(ibin,0);
      profHisto->SetBinEntries(ibin,0);
      if (mbOnly) {
	profHisto = (TProfile*)inputListBis->FindObject(Form("fY2_%d",i))->Clone(Form("fY2_%d",i));
	profHisto->SetDirectory(0);
      }
      else
	profHisto->Add((TProfile*)inputListBis->FindObject(Form("fY2_%d",i)));
      list2->Add(profHisto);

      profHisto = (TProfile*)inputList->FindObject(Form("fX2Y2_%d",i))->Clone(Form("fX2Y2_%d",i));
      profHisto->SetDirectory(0);
      profHisto->SetBinContent(ibin,0);
      profHisto->SetBinError(ibin,0);
      profHisto->SetBinEntries(ibin,0);
      if (mbOnly) {
	profHisto = (TProfile*)inputListBis->FindObject(Form("fX2Y2_%d",i))->Clone(Form("fX2Y2_%d",i));
	profHisto->SetDirectory(0);
      }
      else
	profHisto->Add((TProfile*)inputListBis->FindObject(Form("fX2Y2_%d",i)));
      list2->Add(profHisto);

      profHisto = (TProfile*)inputList->FindObject(Form("fCos8Psi_%d",i))->Clone(Form("fCos8Psi_%d",i));
      profHisto->SetDirectory(0);
      profHisto->SetBinContent(ibin,0);
      profHisto->SetBinError(ibin,0);
      profHisto->SetBinEntries(ibin,0);
      if (mbOnly) {
	profHisto = (TProfile*)inputListBis->FindObject(Form("fCos8Psi_%d",i))->Clone(Form("fCos8Psi_%d",i));
	profHisto->SetDirectory(0);
      }
      else
	profHisto->Add((TProfile*)inputListBis->FindObject(Form("fCos8Psi_%d",i)));
      list2->Add(profHisto);
    }
    oadbCont->AppendObject(list2, runList[irun], runList[irun]);
    printf("Run %d filled\n",runList[irun]);
  }

  TString oadbFileName = Form("%s/COMMON/EVENTPLANE/data/vzero.root", AliAnalysisManager::GetOADBPath());
  oadbCont->WriteToFile(oadbFileName.Data());
}
Example #16
0
//___________________________________________________________
Int_t GetYear(TString &sample){
  TString yearstring = sample(3,4); 
  Int_t year = yearstring.Atoi();
  return 2000 + year;
}
void selectData(TString sample, TString maxindex="") {

  TString path="rfio:/castor/cern.ch/user/p/puigh/CUSusy/CUJEM/Summer09/7TeV/Output/";
  sampleid_ = sample;
  
  if (sample.Contains("QCD")) path+="QCD-madgraph/";

  if (sample.Contains("LM")) {
    path+="LM/";
    path+=sampleid_;
    path += "_Summer09_7TeV_CUJEM_V09.root";
    cout<<"Adding to list of input files: "<<path<<endl;
    fileNames.push_back(string(path.Data()));
  }
  else  {
    if (maxindex!="") {
      if(sample.Contains("TTBar")) {
	for (int ind=1; ind<=maxindex.Atoi(); ind++) {
	  TString mypath = "rfio:/castor/cern.ch/user/k/kreis/CUSusy/CUJEM/Summer09/7TeV/Output/";
	  mypath+=sampleid_;
	  mypath += "_Summer09_7TeV_CUJEM_V09_";
	  mypath +=ind;
	  mypath +=".root";
	  cout<<"Adding to list of input files: "<<mypath<<endl;
	  fileNames.push_back(string(mypath.Data()));
	}
      }
      else if(sample.Contains("QCD_Pt170")) {
	for (int ind=1; ind<=maxindex.Atoi(); ind++) {
	  TString mypath = "rfio:/castor/cern.ch/user/k/kreis/CUSusy/CUJEM/Summer09/7TeV/Output/";
	  mypath+=sampleid_;
	  mypath += "_Summer09_7TeV_CUJEM_V09_";
	  mypath +=ind;
	  mypath +=".root";
	  cout<<"Adding to list of input files: "<<mypath<<endl;
	  fileNames.push_back(string(mypath.Data()));
	}
      }
      else if(sample.Contains("QCD_Pt80")) {
	for (int ind=1; ind<=maxindex.Atoi(); ind++) {
	  TString mypath = "rfio:/castor/cern.ch/user/j/joshmt/CUSusy/CUJEM/Summer09/7TeV/Output/";
	  mypath+=sampleid_;
	  mypath += "_Summer09_7TeV_CUJEM_V09_";
	  mypath +=ind;
	  mypath +=".root";
	  cout<<"Adding to list of input files: "<<mypath<<endl;
	  fileNames.push_back(string(mypath.Data()));
	}
      }
      else{
	for (int ind=1; ind<=maxindex.Atoi(); ind++) {
	  TString mypath=path;
	  mypath+=sampleid_;
	  mypath += "_Summer09_7TeV_CUJEM_V09_";
	  mypath +=ind;
	  mypath +=".root";
	  cout<<"Adding to list of input files: "<<mypath<<endl;
	  fileNames.push_back(string(mypath.Data()));
	}
      }
    }
    else {
      path+=sampleid_;
      path += "_Summer09_7TeV_CUJEM_V09.root";
      cout<<"Adding to list of input files: "<<path<<endl;
      fileNames.push_back(string(path.Data()));
    }
  }

}
Example #18
0
int MPTreeDrawer (TString detName, int structId, int layerRing, int stripReadoutMode=0)
{
    setTDRStyle();

    DetName.push_back("BPIX");
    DetName.push_back("FPIX");
    DetName.push_back("TIB");
    DetName.push_back("TOB");

    for(unsigned int i=0; i<DetName.size(); i++) {
        if(DetName.at(i)!=detName) continue;
        DetIndex=i;
        break;
    }
    if(DetIndex<0) {
        printf("Wrong detector name. Possible names are:");
        for(unsigned int i=0; i<DetName.size(); i++) printf("%s ",DetName.at(i).Data());
            printf("\nStopping...");
        return 1;
    }
    VLayer = structId;
    LayerRing = layerRing;
    StripReadMode = stripReadoutMode;

    if(nLayers[DetIndex]==1) { LayerRing=0; VLayer=0; }


    logFile = fopen ( "log.txt","w" );

    runsFile = fopen ( "runs.txt","w" );

    TFile *file = new TFile ( inputFileName );

    TString moduleType="";
    TString readoutMode="";
    if ( DetIndex<2 ) {
        moduleType="Pixel";

    } else {
        moduleType="Strip";
        readoutMode = (StripReadMode==0?"_peak":"_deconvolution");

    }
    TString TreeBaseDir("Si"+moduleType+calibrationType+"Calibration"+readoutMode+"_result_");

    std::vector<int> iovs;
    std::vector<int> iovs_;
    double totLumi=0.0;
    int nIOVs;

// Finding the IOV borders from the directory names in each ROOT file
    TList *list = file->GetListOfKeys();
    int nKeys = list->GetSize();
    for ( int keyNum=0; keyNum<nKeys; keyNum++ ) {
        TKey* key = ( TKey* ) list->At ( keyNum );
        TString str ( key->GetName() );
        if ( !str.BeginsWith ( TreeBaseDir ) ) {
            continue;
        }
        str.ReplaceAll ( TreeBaseDir,"" );
        int run = str.Atoi();
// Putting run number to the list of IOVs of the file
        iovs.push_back ( run );
        iovs_.push_back ( run );
    }
    nIOVs=iovs.size();
    if(nIOVs<1) {
        printf("No trees found with name: %s...\nExiting...\n",TreeBaseDir.Data());
        return -1;
    }
// Changing the run number if it is 1
    if ( iovs_[0]==1 && nIOVs>2 ) {
        iovs_[0]=2*iovs[1]-iovs[2];
    }
    iovs_[0]=190000;	// Setting the first run of the first IOV to a custom value
    iovs_.push_back(209091);	// Setting the last run of the last IOV to a custom value


    // Direct values from the tree
    UInt_t detId;
    Float_t value;
    // Struct of additional values from the tree
    struct treeStr{
        Float_t delta;
        Float_t error;
        UInt_t paramIndex;
    };
    Float_t error=0.f;
    treeStr treeStruct;
    std::vector<TGraphErrors*> graphLA;
    std::vector<TGraphErrors*> graphLAinput;
    int nDetParts=-1;
    bool isOldFormat = false;

    // Looping over entries in each iov tree
    for ( int iov=0; iov<nIOVs+1; iov++ ) {
        char treeName[300];
        sprintf ( treeName,"%s%d",TreeBaseDir.Data(),iovs[iov] );
    // Reading tree for input tree
        if(iov==nIOVs) {
            TString TreeBaseDirIn = TreeBaseDir;
            TreeBaseDirIn.ReplaceAll("_result_","_input");
            sprintf ( treeName,"%s",TreeBaseDirIn.Data());
        }
        TTree *tree = 0;
        tree = ( TTree* ) ( TDirectoryFile* ) file->Get ( treeName );
        Long64_t nEntries = tree->GetEntries();

        int runNr = (iov<nIOVs)?iovs.at(iov):555;
        if(tree) printf ( "Got Tree %d\twith name: %s for IOV: %d - %lld entries\n",iov,treeName,runNr,nEntries );

        fprintf(runsFile,"%d\n",iovs_.at(iov));
        if(iov>=nIOVs-nPointsToSkip && iov<nIOVs) continue;

        tree->SetBranchAddress ( "detId",&detId );
        tree->SetBranchAddress ( "value",&value );
        if(tree->GetBranch("error")) isOldFormat = true;
        if(isOldFormat) tree->SetBranchAddress ( "error",&error ); else
        tree->SetBranchAddress ( "treeStruct",&treeStruct );


        double iovWidth=-1.f;
        if(iovWidthIsFixed || runNr==555) iovWidth = fixedIOVwidth[DetIndex]; 
        else {
    // Getting more precise value of luminosity (calculation started from the first IOV run)
            iovWidth = lumisInIOV(iovs_.at(0),iovs_.at(iov+1)) - lumisInIOV(iovs_.at(0),iovs_.at(iov));
            if(iovWidth<0.0) {
    // Getting less precise value of luminosity (calculation started from this IOV run)
                iovWidth = lumisInIOV(iovs_.at(iov),iovs_.at(iov+1));
                printf("Less precise estimation of luminosity for IOV: %d (%d-%d)\n",iov+1,iovs_.at(iov),iovs_.at(iov+1));
            }
        }
        if(iovWidth<0 && iov<nIOVs) {
            printf("   ERROR!!! Luminosity for IOV %d with runs: %d - %d not found. Skipping.\n",iov,iovs_.at(iov),iovs_.at(iov+1));
            continue;
        }
        iovWidth*=lumiScale;                           // Correcting luminosity to the real (lumiCalc provides slightly larger value)
        if(!iovWidthIsFixed) iovWidth/=1000.0;         // Converting from /pb to /fb
        totLumi+=iovWidth;                             // Updating total luminosity of all IOVs


        for ( Long64_t entry=0; entry<nEntries; entry++ ) {
        //             printf("  Entry %lld\n",entry);
            tree->GetEntry ( entry );
            if(!isOldFormat) error = treeStruct.error;
            int histoId=histoIdx ( detId );
            // fprintf ( logFile,"  entry: %lld\thistoId: %d\tvalue: %.3f\terror: %.3f\n",entry,histoId,value,error );
            if ( histoId<0 ) {
                continue;
            }
            while(histoId>=(int)graphLA.size() && iov<nIOVs) {
                TGraphErrors* graph = new TGraphErrors ( nIOVs-nPointsToSkip );
                graphLA.push_back(graph);
            }
            while(histoId>=(int)graphLAinput.size() && iov>=nIOVs) {
        //printf("0. histoId: %d size: %d\n",histoId,(int)graphLAinput.size());
                TGraphErrors* graph = new TGraphErrors ( 1 );
                graphLAinput.push_back(graph);
            }
            if ( DetIndex==0 || DetIndex==2 || DetIndex==3 ) {
                if(iov<nIOVs) {
                    graphLA.at(histoId)->SetPoint ( iov, totLumi - 0.5*iovWidth, value*3.81 );	// BPIX, TIB, TOB
                    graphLA.at(histoId)->SetPointError ( iov,0.f,error*3.81 );
                } else {    // For line of input LA value
                //printf("1. histoId: %d size: %d\n",histoId,(int)graphLAinput.size());
                    Double_t centerY;
                    Double_t centerX;
                    graphLA.at(histoId)->GetPoint(graphLA.at(histoId)->GetN()/2,centerX,centerY);
                    graphLAinput.at(histoId)->SetPoint ( 0, centerX, value*3.81 );	// BPIX, TIB, TOB
                    graphLAinput.at(histoId)->SetPointError ( 0,centerX*2.5,error*3.81 );
                }
            } else if ( DetIndex==1 ) {
                if(iov<nIOVs) {
                    graphLA.at(histoId)->SetPoint ( iov, totLumi + 0.5*iovWidth, value* ( -1.3 ) );	// FPIX
                    graphLA.at(histoId)->SetPointError ( iov,0.f,error*1.3 );
                } else {    // For line of input LA value
                    Double_t centerY;
                    Double_t centerX;
                    graphLA.at(histoId)->GetPoint(graphLA.at(histoId)->GetN()/2,centerX,centerY);
                    graphLAinput.at(histoId)->SetPoint ( 0, centerX + 0.5*iovWidth, value* ( -1.3 ) );	// FPIX
                    graphLAinput.at(histoId)->SetPointError ( 0,centerX*2.5,error*1.3 );
                }
            }
        }	  // End of loop over entries
    }	// End of loop over IOVs
    nDetParts=graphLA.size();
    printf("Found %d different substructures\n",nDetParts);
    // if(LayerRing==0) nRings[DetIndex]=nDetParts;        // Updating the number of rings to draw
    if(nDetParts<1) {
        fclose(logFile);
        fclose(runsFile);
        return 1;
    }

    float minY_ = minY_det[DetIndex];
    float maxY_ = maxY_det[DetIndex];

    if(minY!=0.f || maxY!=0.f) {
        minY_ = minY;
        maxY_ = maxY;
    }

    if(autoScaleY) {
        minY_=999.9;
        maxY_=-999.9;
    }
    fprintf ( logFile,"File: %s\n",inputFileName.Data() );
    for ( int i=0; i<nDetParts; i++ ) {
    // fprintf ( logFile,"ID: %d Values: ",i );
        for ( int j=0; j<graphLA.at(i)->GetN(); j++ ) {
    // Updating min and max values of LA for axis of the plot
            Double_t val;
            Double_t null;
            graphLA.at(i)->GetPoint ( j,null,val );
            fprintf(logFile,"detPart: %d\tiov %d\tRun: %d\tValue: %.3f\n",i+1,j+1,iovs.at(j),val);
            if ( val<minY_ && autoScaleY && val!=0.0) {
                minY_=val;
            }
            if ( val>maxY_ && autoScaleY && val!=0.0) {
                maxY_=val;
            }
    // fprintf ( logFile," %.3f",val );
        }
    // fprintf ( logFile,"\n" );
    }	// End of loop over Detector parts

    if(autoScaleY) {
        minY_= ( minY_>0 ) ?minY_*0.98:minY_*1.02;
        maxY_= ( maxY_>0 ) ?maxY_*1.05:maxY_*0.95;
    }

    //Drawing canvas
    //    TCanvas *c1 = new TCanvas ( "c1","Canvas1",1000,600 );
    TCanvas *c1 = new TCanvas ( "c1","Canvas1");
    // Drawing empty histogram
    TString Y_title;
    if(calibrationType=="LorentzAngle") Y_title = "tan(#theta_{LA}^{shift}) "; else
    if(calibrationType=="Backplane") Y_title = "#DeltaW_{BP}^{shift} "; else
    Y_title = "??? ";
    drawEmptyHisto ( 0.0,totLumi,"2012 Integrated Luminosity [fb^{-1}]",minY_,maxY_,Y_title,"empty1" );
    // Drawing each graph for input values
    if(drawInput) {
        for ( int i=0; i<nDetParts; i++ ) {
            setGraphStyle ( graphLAinput.at(i),i,1 );
            graphLAinput.at(i)->SetMarkerStyle(0);
            graphLAinput.at(i)->Draw( "Lsame" );
        }
    }
    // Drawing each graph for output values
    for ( int i=0; i<nDetParts; i++ ) {
        setGraphStyle ( graphLA.at(i),i,0 );
        graphLA.at(i)->Draw ( "Psame" );
    }

    TString structName = ( LayerRing==0 ) ?"L":"R";
    TString structNameFull = ( LayerRing==0 ) ?"Layer":"Ring";

    //Drawing legend pane
    TLegend *leg;
    leg = new TLegend ( 0.7,0.77,0.98,0.95,NULL,"brNDC" );
        
    int nCols = (nDetParts>3)?2:1;

    for(int i=0; i<=nDetParts/2; i++) {
        int i2=0;
        TString legName_("");
        if(LayerRing==1) {
            i2 = i+nDetParts/2;
            legName_+="Layer";
        }
        if(LayerRing==0) {
            i2 = nDetParts-1-i;
            legName_+="Ring";
        }
        if(nDetParts<4) {
            i2 = i*2+1;
            i = i2-1;
        }
        char legName[100];
        if(i<nDetParts/2) {
            sprintf(legName,"%s %d",legName_.Data(),i+1);
            leg->AddEntry( graphLA.at(i),legName,"p" );
            sprintf(legName,"%s %d",legName_.Data(),i2+1);
            leg->AddEntry( graphLA.at(i2),legName,"p" );
            if(i==nDetParts/2-1 && nDetParts%2==0) break;
        } else {
            sprintf(legName,"%s %d",legName_.Data(),i+1);
            leg->AddEntry( graphLA.at(i),legName,"p" );
        }
    }
    setLegendStyle ( leg,nCols,nDetParts);


    if ( drawLegend ) {
        leg->Draw();
    }

    //    // Drawing CMS Preliminary label
    //    TLatex *TextCMS = new TLatex(0.2,0.89,"CMS Preliminary 2012");
    //    TextCMS->SetTextColor(1);
    //    TextCMS->SetNDC();
    //    TextCMS->SetTextFont(62);
    //    TextCMS->Draw();

    char Data_[150];
    sprintf(Data_,"%s %s %d",DetName.at(DetIndex).Data(),structNameFull.Data(),VLayer);
    TLatex *TextData = new TLatex(0.2,0.89,Data_);
    TextData->SetTextColor(1);
    TextData->SetNDC();
    TextData->SetTextFont(62);
    TextData->Draw();

    char savePath[150];

    gROOT->ProcessLine(".mkdir -p "+outputPath);
    sprintf ( savePath,"%s/%s_%s_%s%d%s",outputPath.Data(),calibrationType.Data(),DetName.at(DetIndex).Data(),structName.Data(),VLayer, readoutMode.Data() );
    c1->Print( TString ( savePath ) +=".eps" );
    //    c1->SaveAs ( TString ( savePath ) +=".pdf" );
    //    c1->SaveAs ( TString ( savePath ) +=".C" );
    //    c1->SaveAs ( TString ( savePath ) +=".root" );

    fclose ( logFile );

    fclose ( runsFile );

    return 0;
}
Example #19
0
void RsnGridPlugin(TString analysisMode) {

   Bool_t valid = kTRUE;
   TString dsConfig = AliAnalysisManager::GetGlobalStr("rsnTrainDSConfig",valid);
   Int_t globalTrainID = AliAnalysisManager::GetGlobalInt("rsnGlobalTrainID",valid);

   Int_t numRuns = AliAnalysisManager::GetGlobalInt("rsnGridNumRuns",valid);
   Int_t numRunsSkip = AliAnalysisManager::GetGlobalInt("rsnGridNumRunsSkip",valid);

   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      Printf("Error[RsnGridPlugin] mgr is null !!!");
      return;
   }

   AliAnalysisAlien *plugin = (AliAnalysisAlien *) mgr->GetGridHandler();
   if (!plugin) {
      Printf("Error[RsnGridPlugin] : plugin is null !!!");
      return;
   }

   // getting latest train id
   TString rsnTrainName = gSystem->BaseName(dsConfig.Data());
   rsnTrainName.ReplaceAll(".txt","");
   rsnTrainName.Append(TString::Format("/%03d/%d_%d",globalTrainID,numRunsSkip,numRuns).Data());

   if (!gGrid) TGrid::Connect("alien://");
   if (!gGrid) return;
   TGridResult *r = gGrid->Query(TString::Format("%s/RsnTrain/%s",gGrid->GetHomeDirectory(),rsnTrainName.Data()).Data(),"*/analysis.root");
   Int_t idRsnTrain = 0;
   if (r) {
      TString s = r->GetKey(r->GetSize()-1,"lfn");
      s.ReplaceAll("/analysis.root","");
      s = gSystem->BaseName(s);
      if (!s.IsNull()) idRsnTrain = s.Atoi();
      if (!analysisMode.CompareTo("full")) idRsnTrain++;
   }
   rsnTrainName.Append(Form("/%03d",idRsnTrain));

   TString rsnTrainWkDir = TString::Format("RsnTrain/%s",rsnTrainName.Data()).Data();
   Info("RsnGridPlugin()",TString::Format("RSN Train directory : %s%s",gGrid->GetHomeDirectory(),rsnTrainWkDir.Data()).Data());

   plugin->SetGridWorkingDir(rsnTrainWkDir.Data());
   plugin->SetGridOutputDir("output"); // In this case will be $HOME/work/output

   plugin->SetAPIVersion("V1.1x");

   TString rootver = AliAnalysisManager::GetGlobalStr("rsnLegoTrainROOTversion",valid);
   plugin->SetROOTVersion(rootver.Data());

   TString alirootVersion = AliAnalysisManager::GetGlobalStr("rsnLegoTrainAliROOTversion",valid);
   if (alirootVersion.IsNull()) {
      if (gSystem->Getenv("ALICE_ROOT")) alirootVersion = gSystem->GetFromPipe("aliroot --version | awk '{print $3}'");
   }
   plugin->SetAliROOTVersion(alirootVersion.Data());

   plugin->SetExecutableCommand("aliroot -b -q");

   plugin->SetAnalysisMacro("RsnTrain.C");
   plugin->SetMasterResubmitThreshold(90);
   plugin->SetTTL(84600);
   plugin->SetInputFormat("xml-single");
   plugin->SetJDLName("RsnTrain.jdl");
   plugin->SetPrice(1);
   plugin->SetSplitMode("se");
   plugin->SetNtestFiles(2);
   plugin->SetMergeViaJDL();
   plugin->SetOverwriteMode(kFALSE);
   //    plugin->SetKeepLogs(kTRUE);

   RsnSetData(plugin,dsConfig,numRuns,numRunsSkip,1000);

   plugin->SetSplitMaxInputFileNumber(25);

   //   Fatal("RsnDataSet","No dataset found !!!");
}
Example #20
0
void TMVAClassification( TString myMethodList = "" ) 
{
  // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
  // if you use your private .rootrc, or run from a different directory, please copy the 
  // corresponding lines from .rootrc

  // methods to be processed can be given as an argument; use format:
  //
  // mylinux~> root -l TMVAClassification.C\(\"myMethod1,myMethod2,myMethod3\"\)
  //
  // if you like to use a method via the plugin mechanism, we recommend using
  // 
  // mylinux~> root -l TMVAClassification.C\(\"P_myMethod\"\)
  // (an example is given for using the BDT as plugin (see below),
  // but of course the real application is when you write your own
  // method based)

  // this loads the library
  TMVA::Tools::Instance();

  //---------------------------------------------------------------
  // default MVA methods to be trained + tested
  std::map<std::string,int> Use;

  Use["Cuts"]            = 1;
  Use["CutsD"]           = 1;
  Use["CutsPCA"]         = 1;
  Use["CutsGA"]          = 1;
  Use["CutsSA"]          = 1;
  // ---
  Use["Likelihood"]      = 1;
  Use["LikelihoodD"]     = 1; // the "D" extension indicates decorrelated input variables (see option strings)
  Use["LikelihoodPCA"]   = 1; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
  Use["LikelihoodKDE"]   = 1;
  Use["LikelihoodMIX"]   = 1;
  // ---
  Use["PDERS"]           = 1;
  Use["PDERSD"]          = 1;
  Use["PDERSPCA"]        = 1;
  Use["PDERSkNN"]        = 1; // depreciated until further notice
  Use["PDEFoam"]         = 1;
  // --
  Use["KNN"]             = 1;
  // ---
  Use["HMatrix"]         = 1;
  Use["Fisher"]          = 1;
  Use["FisherG"]         = 1;
  Use["BoostedFisher"]   = 1;
  Use["LD"]              = 1;
  // ---
  Use["FDA_GA"]          = 1;
  Use["FDA_SA"]          = 1;
  Use["FDA_MC"]          = 1;
  Use["FDA_MT"]          = 1;
  Use["FDA_GAMT"]        = 1;
  Use["FDA_MCMT"]        = 1;
  // ---
  Use["MLP"]             = 1; // this is the recommended ANN
  Use["MLPBFGS"]         = 1; // recommended ANN with optional training method
  Use["CFMlpANN"]        = 1; // *** missing
  Use["TMlpANN"]         = 1; 
  // ---
  Use["SVM"]             = 1;
  // ---
  Use["BDT"]             = 1;
  Use["BDTD"]            = 0;
  Use["BDTG"]            = 1;
  Use["BDTB"]            = 0;
  // ---
  Use["RuleFit"]         = 1;
  // ---
  Use["Plugin"]          = 0;
  // ---------------------------------------------------------------

  std::cout << std::endl;
  std::cout << "==> Start TMVAClassification" << std::endl;

  if (myMethodList != "") {
    for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

    std::vector<TString> mlist = TMVA::gTools().SplitString( myMethodList, ',' );
    for (UInt_t i=0; i<mlist.size(); i++) {
      std::string regMethod(mlist[i]);

      if (Use.find(regMethod) == Use.end()) {
        std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
        for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
        std::cout << std::endl;
        return;
      }
      Use[regMethod] = 1;
    }
  }

  // Create a new root output file.
  TString outfileName = "TMVA";
  int toAppNum = 1;
  char name[1024];

  TSystemDirectory dir("",".");
  TList *files = dir.GetListOfFiles();
  vector<string> vfname;
  if (files) {
     TIter next(files);
     TSystemFile *file;
     TString fname;
     
     while ((file=(TSystemFile*)next())) {
        fname = file->GetName();
        if (!file->IsDirectory() && fname.EndsWith(".root") && fname.BeginsWith("TMVA")) {
           vfname.push_back(string(fname));
        }
      }
     delete files;
     if (vfname.size()>0) {
        std::sort(vfname.begin(),vfname.end());
        TString num = TString(vfname[vfname.size()-1]);
        num.ReplaceAll(".root","");
        num.ReplaceAll("TMVA","");
        toAppNum = num.Atoi()+1;
     }
  }
  sprintf(name,"%d",toAppNum);
  outfileName = outfileName + name + ".root";
  //TString outfileName( "TMVA.root" );
  TFile* outputFile = TFile::Open( outfileName, "RECREATE" );

  // Create the factory object. Later you can choose the methods
  // whose performance you'd like to investigate. The factory will
  // then run the performance analysis for you.
  //
  // The first argument is the base of the name of all the
  // weightfiles in the directory weight/ 
  //
  // The second argument is the output file for the training results
  // All TMVA output can be suppressed by removing the "!" (not) in 
  // front of the "Silent" argument in the option string
  TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile, 
                                              "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D" );

  // If you wish to modify default settings 
  // (please check "src/Config.h" to see all available global options)
  //    (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
  //    (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";


  // Define the input variables that shall be used for the MVA training
  factory->AddVariable("tEventProbSig := tEventProb[0]+tEventProb[1]+tEventProb[2]","F",0,0);
  factory->AddVariable("tEventProbBkg := tEventProb","F",0,0);
  
  // You can add so-called "Spectator variables", which are not used in the MVA training, 
  // but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the 
  // input variables, the response values of all trained MVAs, and the spectator variables
  factory->AddSpectator("run := m_run", "I");
  factory->AddSpectator("event := m_event", "I");


  // read training and test data
  TFile *input1 = TFile::Open( "/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microWW_EPDv01.root" );
  TFile *input2 = TFile::Open( "/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microWZ_EPDv01.root" );
  TFile *input3 = TFile::Open( "/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microWJets_EPDv01.root" );
  TFile *input4 = TFile::Open( "/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microZJets_EPDv01.root" );
  TFile *input5 = TFile::Open( "/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microTTbar_EPDv01.root" );
  TFile *input6 = TFile::Open( "/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microHWWMH150_EPDv01.root" );

 
  std::cout << "--- TMVAClassification : Using input file: " << input1->GetName() << std::endl;
  std::cout << "--- TMVAClassification : Using input file: " << input2->GetName() << std::endl;
  std::cout << "--- TMVAClassification : Using input file: " << input3->GetName() << std::endl;
  std::cout << "--- TMVAClassification : Using input file: " << input4->GetName() << std::endl;
  std::cout << "--- TMVAClassification : Using input file: " << input5->GetName() << std::endl;
  std::cout << "--- TMVAClassification : Using input file: " << input6->GetName() << std::endl;
   
  //TTree *signal     = (TTree*)input1->Get("WJet");
  //TTree *background = (TTree*)input3->Get("WJet");
  TChain *signal = new TChain("METree");
  signal->Add("/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microHWWMH150_EPDv01.root");
  TChain *background = new TChain("METree"); 
  background->Add("/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microWW_EPDv01.root");
  background->Add("/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microWZ_EPDv01.root");
  background->Add("/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microWJets_EPDv01.root");
  background->Add("/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microZJets_EPDv01.root");
  background->Add("/uscms/home/ilyao/nobackup/Spring12ME7TeV/MEResults/microNtuples/microTTbar_EPDv01.root");

  // global event weights per tree (see below for setting event-wise weights)
  Double_t signalWeight     = 1.0;
  Double_t backgroundWeight = 1.0;

  // ====== register trees ====================================================
  //
  // the following method is the prefered one:
  // you can add an arbitrary number of signal or background trees
  factory->AddSignalTree    ( signal,     signalWeight     );
  factory->AddBackgroundTree( background, backgroundWeight );

  // To give different trees for training and testing, do as follows:
  //    factory->AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" );
  //    factory->AddSignalTree( signalTestTree,     signalTestWeight,  "Test" );

  // Use the following code instead of the above two or four lines to add signal and background 
  // training and test events "by hand"
  // NOTE that in this case one should not give expressions (such as "var1+var2") in the input 
  //      variable definition, but simply compute the expression before adding the event
  // 
  //    // --- begin ----------------------------------------------------------
  //    std::vector<Double_t> vars( 4 ); // vector has size of number of input variables
  //    Float_t  treevars[4];
  //    for (Int_t ivar=0; ivar<4; ivar++) signal->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
  //    for (Int_t i=0; i<signal->GetEntries(); i++) {
  //       signal->GetEntry(i);
  //       for (Int_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
  //       // add training and test events; here: first half is training, second is testing
  //       // note that the weight can also be event-wise	
  //       if (i < signal->GetEntries()/2) factory->AddSignalTrainingEvent( vars, signalWeight ); 
  //       else                            factory->AddSignalTestEvent    ( vars, signalWeight ); 
  //    }
  //
  //    for (Int_t ivar=0; ivar<4; ivar++) background->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
  //    for (Int_t i=0; i<background->GetEntries(); i++) {
  //       background->GetEntry(i); 
  //       for (Int_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
  //       // add training and test events; here: first half is training, second is testing
  //       // note that the weight can also be event-wise	
  //       if (i < background->GetEntries()/2) factory->AddBackgroundTrainingEvent( vars, backgroundWeight ); 
  //       else                                factory->AddBackgroundTestEvent    ( vars, backgroundWeight ); 
  //    }
  //    // --- end ------------------------------------------------------------
  //
  // ====== end of register trees ==============================================

   
  // This would set individual event weights (the variables defined in the 
  // expression need to exist in the original TTree)
  //    for signal    : factory->SetSignalWeightExpression("weight1*weight2");
  //    for background: factory->SetBackgroundWeightExpression("weight1*weight2");
  // factory->SetBackgroundWeightExpression("weight");

  // Apply additional cuts on the signal and background samples (can be different)
  //   TCut mycuts = "abs(eta)>1.5"; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
  //   TCut mycutb = "abs(eta)>1.5"; // for example: TCut mycutb = "abs(var1)<0.5";

  //Acceptance/Base cuts
  //TCut goodW("W_electron_et>30. && TMath::Abs(W_electron_eta)<2.5 && event_met_pfmet>25.");
  TCut goodW("W_muon_pt>25. && TMath::Abs(W_muon_eta)<2.5 && event_met_pfmet>25.");
  TCut twojets("numPFCorJets==2");
  TCut jetPt("JetPFCor_Pt[0]>30. && JetPFCor_Pt[1]>30.");
  TCut jetEta("TMath::Abs(JetPFCor_Eta[0])<2.5 && TMath::Abs(JetPFCor_Eta[1])<2.5");
  TCut deltaR1("TMath::Sqrt(TMath::Power(TMath::Abs(TMath::Abs(TMath::Abs(JetPFCor_Phi[0]-W_muon_phi)-TMath::Pi())-TMath::Pi()),2)+TMath::Power(JetPFCor_Eta[0]-W_muon_eta,2))>0.5");
  TCut deltaR2("TMath::Sqrt(TMath::Power(TMath::Abs(TMath::Abs(TMath::Abs(JetPFCor_Phi[1]-W_muon_phi)-TMath::Pi())-TMath::Pi()),2)+TMath::Power(JetPFCor_Eta[1]-W_muon_eta,2))>0.5");
  TCut noBJets("numPFCorJetBTags==0");
  TCut null("");

  //TCut mycuts (goodW && twojets && jetPt && jetEta && deltaR1 && deltaR2 && noBJets);
  TCut mycuts (null);

  // tell the factory to use all remaining events in the trees after training for testing:
  factory->PrepareTrainingAndTestTree( mycuts, mycuts,
                                       "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );

  // If no numbers of events are given, half of the events in the tree are used for training, and 
  // the other half for testing:
  //    factory->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );  
  // To also specify the number of testing events, use:
  //    factory->PrepareTrainingAndTestTree( mycut, 
  //                                         "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );  

  // ---- Book MVA methods
  //
  // please lookup the various method configuration options in the corresponding cxx files, eg:
  // src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
  // it is possible to preset ranges in the option string in which the cut optimisation should be done:
  // "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable

  // Cut optimisation
  if (Use["Cuts"])
    factory->BookMethod( TMVA::Types::kCuts, "Cuts", 
                         "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );

  if (Use["CutsD"])
    factory->BookMethod( TMVA::Types::kCuts, "CutsD", 
                         "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" );

  if (Use["CutsPCA"])
    factory->BookMethod( TMVA::Types::kCuts, "CutsPCA", 
                         "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=PCA" );

  if (Use["CutsGA"])
    factory->BookMethod( TMVA::Types::kCuts, "CutsGA",
                         "H:!V:FitMethod=GA:CutRangeMin[0]=-10:CutRangeMax[0]=10:VarProp[1]=FMax:EffSel:Steps=30:Cycles=3:PopSize=400:SC_steps=10:SC_rate=5:SC_factor=0.95" );
   
  if (Use["CutsSA"])
    factory->BookMethod( TMVA::Types::kCuts, "CutsSA",
                         "!H:!V:FitMethod=SA:EffSel:MaxCalls=150000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );
   
  // Likelihood
  if (Use["Likelihood"])
     factory->BookMethod( TMVA::Types::kLikelihood, "Likelihood", 
                          "H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" ); 

  // test the decorrelated likelihood
  if (Use["LikelihoodD"])
    factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodD", 
                         "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=Decorrelate" ); 

  if (Use["LikelihoodPCA"])
    factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodPCA", 
                         "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=PCA" ); 
 
  // test the new kernel density estimator
  if (Use["LikelihoodKDE"])
    factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodKDE", 
                         "!H:!V:!TransformOutput:PDFInterpol=KDE:KDEtype=Gauss:KDEiter=Adaptive:KDEFineFactor=0.3:KDEborder=None:NAvEvtPerBin=50" ); 

  // test the mixed splines and kernel density estimator (depending on which variable)
  if (Use["LikelihoodMIX"])
    factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodMIX", 
                         "!H:!V:!TransformOutput:PDFInterpolSig[0]=KDE:PDFInterpolBkg[0]=KDE:PDFInterpolSig[1]=KDE:PDFInterpolBkg[1]=KDE:PDFInterpolSig[2]=Spline2:PDFInterpolBkg[2]=Spline2:PDFInterpolSig[3]=Spline2:PDFInterpolBkg[3]=Spline2:KDEtype=Gauss:KDEiter=Nonadaptive:KDEborder=None:NAvEvtPerBin=50" ); 

  // test the multi-dimensional probability density estimator
  // here are the options strings for the MinMax and RMS methods, respectively:
  //      "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" );   
  //      "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" );   
  if (Use["PDERS"])
    factory->BookMethod( TMVA::Types::kPDERS, "PDERS", 
                         "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" );

  if (Use["PDERSkNN"])
    factory->BookMethod( TMVA::Types::kPDERS, "PDERSkNN", 
                         "!H:!V:VolumeRangeMode=kNN:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" );

  if (Use["PDERSD"])
    factory->BookMethod( TMVA::Types::kPDERS, "PDERSD", 
                         "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=Decorrelate" );

  if (Use["PDERSPCA"])
    factory->BookMethod( TMVA::Types::kPDERS, "PDERSPCA", 
                         "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=PCA" );
  /*
  // Multi-dimensional likelihood estimator using self-adapting phase-space binning
  if (Use["PDEFoam"])
    factory->BookMethod( TMVA::Types::kPDEFoam, "PDEFoam", 
                         "H:!V:SigBgSeparate=F:TailCut=0.001:VolFrac=0.0333:nActiveCells=500:nSampl=2000:nBin=5:CutNmin=T:Nmin=100:Kernel=None:Compress=T" );
  */
  // K-Nearest Neighbour classifier (KNN)
  if (Use["KNN"])
    factory->BookMethod( TMVA::Types::kKNN, "KNN", 
                         "H:nkNN=20:ScaleFrac=0.8:SigmaFact=1.0:Kernel=Gaus:UseKernel=F:UseWeight=T:!Trim" );
  // H-Matrix (chi2-squared) method
  if (Use["HMatrix"])
    factory->BookMethod( TMVA::Types::kHMatrix, "HMatrix", "!H:!V" ); 

  // Fisher discriminant   
  if (Use["Fisher"])
    factory->BookMethod( TMVA::Types::kFisher, "Fisher", "H:!V:Fisher:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=60:NsmoothMVAPdf=10" );

  // Fisher with Gauss-transformed input variables
  if (Use["FisherG"])
    factory->BookMethod( TMVA::Types::kFisher, "FisherG", "H:!V:VarTransform=Gauss" );

  // Composite classifier: ensemble (tree) of boosted Fisher classifiers
  if (Use["BoostedFisher"])
    factory->BookMethod( TMVA::Types::kFisher, "BoostedFisher", "H:!V:Boost_Num=20:Boost_Transform=log:Boost_Type=AdaBoost:Boost_AdaBoostBeta=0.2");
  /*
  // Linear discriminant (same as Fisher)
  if (Use["LD"])
    factory->BookMethod( TMVA::Types::kLD, "LD", "H:!V:VarTransform=None" );
  */
  // Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
  if (Use["FDA_MC"])
    factory->BookMethod( TMVA::Types::kFDA, "FDA_MC",
                         "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:SampleSize=100000:Sigma=0.1" );
   
  if (Use["FDA_GA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
    factory->BookMethod( TMVA::Types::kFDA, "FDA_GA",
                         "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=300:Cycles=3:Steps=20:Trim=True:SaveBestGen=1" );

  if (Use["FDA_SA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
    factory->BookMethod( TMVA::Types::kFDA, "FDA_SA",
                         "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=SA:MaxCalls=15000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );

  if (Use["FDA_MT"])
    factory->BookMethod( TMVA::Types::kFDA, "FDA_MT",
                         "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=2:UseImprove:UseMinos:SetBatch" );

  if (Use["FDA_GAMT"])
    factory->BookMethod( TMVA::Types::kFDA, "FDA_GAMT",
                         "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" );

  if (Use["FDA_MCMT"])
    factory->BookMethod( TMVA::Types::kFDA, "FDA_MCMT",
                         "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:SampleSize=20" );

  // TMVA ANN: MLP (recommended ANN) -- all ANNs in TMVA are Multilayer Perceptrons
  if (Use["MLP"])
    factory->BookMethod( TMVA::Types::kMLP, "MLP", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=500:HiddenLayers=N+5:TestRate=10:EpochMonitoring" );

  if (Use["MLPBFGS"])
    factory->BookMethod( TMVA::Types::kMLP, "MLPBFGS", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=500:HiddenLayers=N+5:TestRate=10:TrainingMethod=BFGS:!EpochMonitoring" );


  // CF(Clermont-Ferrand)ANN
  if (Use["CFMlpANN"])
    factory->BookMethod( TMVA::Types::kCFMlpANN, "CFMlpANN", "!H:!V:NCycles=2000:HiddenLayers=N+1,N"  ); // n_cycles:#nodes:#nodes:...  
  
  // Tmlp(Root)ANN
  if (Use["TMlpANN"])
    factory->BookMethod( TMVA::Types::kTMlpANN, "TMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N:LearningMethod=BFGS:ValidationFraction=0.3"  ); // n_cycles:#nodes:#nodes:...
  
  // Support Vector Machine
  if (Use["SVM"])
    factory->BookMethod( TMVA::Types::kSVM, "SVM", "Gamma=0.25:Tol=0.001:VarTransform=Norm" );
   
  // Boosted Decision Trees
  if (Use["BDTG"]) // Gradient Boost
    factory->BookMethod( TMVA::Types::kBDT, "BDTG", 
                         "!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:GradBaggingFraction=0.6:SeparationType=GiniIndex:nCuts=20:NNodesMax=5" );

  if (Use["BDT"])  // Adaptive Boost
    factory->BookMethod( TMVA::Types::kBDT, "BDT", 
                         "!H:!V:NTrees=400:nEventsMin=400:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );
   
  if (Use["BDTB"]) // Bagging
    factory->BookMethod( TMVA::Types::kBDT, "BDTB", 
                         "!H:!V:NTrees=400:BoostType=Bagging:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );

  if (Use["BDTD"]) // Decorrelation + Adaptive Boost
    factory->BookMethod( TMVA::Types::kBDT, "BDTD", 
                         "!H:!V:NTrees=400:nEventsMin=400:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning:VarTransform=Decorrelate" );
   
  // RuleFit -- TMVA implementation of Friedman's method
  if (Use["RuleFit"])
    factory->BookMethod( TMVA::Types::kRuleFit, "RuleFit",
                         "H:!V:RuleFitModule=RFTMVA:Model=ModRuleLinear:MinImp=0.001:RuleMinDist=0.001:NTrees=20:fEventsMin=0.01:fEventsMax=0.5:GDTau=-1.0:GDTauPrec=0.01:GDStep=0.01:GDNSteps=10000:GDErrScale=1.02" );
   
  // For an example of the category classifier, see: TMVAClassificationCategory

  // --------------------------------------------------------------------------------------------------

  // As an example how to use the ROOT plugin mechanism, book BDT via
  // plugin mechanism
  if (Use["Plugin"]) {
    //
    // first the plugin has to be defined, which can happen either through the following line in the local or global .rootrc:
    //
    // # plugin handler          plugin name(regexp) class to be instanciated library        constructor format
    // [email protected]@MethodBase:  ^BDT                TMVA::MethodBDT          TMVA.1         "MethodBDT(TString,TString,DataSet&,TString)"
    // 
    // or by telling the global plugin manager directly
    gPluginMgr->AddHandler("[email protected]@MethodBase", "BDT", "TMVA::MethodBDT", "TMVA.1", "MethodBDT(TString,TString,DataSet&,TString)");
    factory->BookMethod( TMVA::Types::kPlugins, "BDT",
                         "!H:!V:NTrees=400:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=CostComplexity:PruneStrength=50" );
  }

  // --------------------------------------------------------------------------------------------------

  // ---- Now you can tell the factory to train, test, and evaluate the MVAs

  // Train MVAs using the set of training events
  factory->TrainAllMethods();

  // ---- Evaluate all MVAs using the set of test events
  factory->TestAllMethods();

  // ----- Evaluate and compare performance of all configured MVAs
  factory->EvaluateAllMethods();    

  // --------------------------------------------------------------
   
  // Save the output
  outputFile->Close();

  std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
  std::cout << "==> TMVAClassification is done!" << std::endl;      

  delete factory;

  // Launch the GUI for the root macros
  if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
Example #21
0
void uncutRate(char * month){
    
  gROOT->SetStyle("Plain");
  Int_t nEntries;
    
  //char * month="marchTest";
    
  double sum1,sum2,sum3,sum4,sum5 = 0;
  double channel_energy=0;
  double startTime,endTime=0;
  //double charge[1000];
  double summed_charge,veto_summed_charge;
  double runtime=0;
  unsigned long long time;
  Int_t numTarget=16;
  Int_t numVeto=36;
  Int_t targetEvents_1=0,targetEvents_2=0;
  Int_t vetoEvents_1=0,vetoEvents_2=0;
  Int_t eventsBoth_1=0,eventsBoth_2=0;
  Int_t eventsEither_1=0,eventsEither_2=0;
  double target_thresh=500;
  double veto_thresh=500;
  //double charge[16]={0};
  // double vetoCharge[16]={0};
    
  //Nathaniel Parameters
  Int_t singleTargetFlag, singleVetoFlag;
  double targetPMTQ[16];
  double vetoPMTQ[36];
  double targetPMTPed[16];
  double vetoPMTPed[36];
  double signalGateSigma[52];
  double pedestalGateMean[52];
  double pedestalGateSigma[52];
  double chiSquare[52];
    
  const int maxNumPMTs =36;
  const int numPMTGroups =2;
  Char_t groupNames[numPMTGroups][50]={"Target","Veto"};
  Char_t physicsNames[numPMTGroups+1][50]={"Neutron","MuonInV","MuonInVT"};
    
    
  Int_t numPMTs[numPMTGroups] ={16,36} ; //# of channels in each group
    
  Int_t qRangeAll[numPMTGroups] ={5000,3000} ; // Max SPE Charge in each region; for histogram ranges
  Int_t qRangePhysics[numPMTGroups] ={250,250} ; // Max SPE Charge in each region, physics events; for histogram ranges
    
  double signalThresholds[numPMTGroups][maxNumPMTs]; //contains pmt-by-pmt threshold; readin from file; based on fit to pedestal of (pedestal subtracted) signal gate
  double pmtQperSPE[numPMTGroups][maxNumPMTs]; //contains pmt-by-pmt spe calibration; readin from file; based on LED data
    
  double pedestalThresholdsLower[numPMTGroups][maxNumPMTs]; //contains pmt-by-pmt lower threshold for pedestal gate; readin from file; based on fit to pedestal of gate
  double pedestalThresholdsUpper[numPMTGroups][maxNumPMTs]; //contains pmt-by-pmt upper threshold for pedestal gate; readin from file; based on fit to pedestal of gate
  double qPMT[numPMTGroups][maxNumPMTs];
  double qTotal[numPMTGroups];
    
  //set up isotropy parameters
  double sumQSquare_T,sumQSquare_V;
  double sumQ_T, sumQ_V;
  double iso_T,iso_V;
    
    
    
    
  //1D Histograms that diplay the rates given a specific type of cut

  TH1F *h7= new TH1F("h7","Total Event Rate vs. Run (uncut)",12*750,0,12*31);
    
    
  Int_t numfiles =0;
  TString files[20000];
  ifstream runList;
  TString mName=month;
  TString listName=mName+".txt";
  TString canvas=mName+"Canvas.C";
  TString outFile1=mName+"EventRateTable.C";
  TString outFile2=mName+"PMTRateTable.C";

    
  //read in the runlist
  cerr<<"Looking at Data from "<<listName<<endl;
  runList.open(listName);
  // runList.open("marchTest");
  while(!runList.eof()){
    runList>>files[numfiles];
    numfiles++;
  }
  runList.close();
  //set parameters to extract the day and hour information from the file name
  TString str;
  TString day;
  TString hour;
  Int_t dayNum, hourNum;
  Int_t currentDay,previousDay;
    
  //
  Int_t numTPerEvent,numVPerEvent;
  Double_t liveTime=0;


  TString histName[52];
  Int_t Index;
  TString InName;
  TH1F *ConverisonHist[56];
  cerr<<files[0]<<endl;
  
  ofstream rateVrun;
  rateVrun.open("rateVrun.txt");

  for (Int_t l=1; l<(numfiles-1);++l){
    Int_t numEvents=0;
    targetEvents_1=0;
    vetoEvents_1=0;
    targetEvents_2=0;
    vetoEvents_2=0;
    eventsBoth_1=0;
    eventsEither_1=0;
    double numTargetCut=0;
    double numVetoCut=0;
    TFile *f1 = new TFile( files[l]);
    TTree *wb = (TTree*)f1->Get("procData");
    TChain *slowChain = new TChain("slowTree");
    nEntries= wb->GetEntries();
    cerr<<nEntries<<" events in the file "<<l<<endl;
    double charge[numTarget];
    double vetoCharge[numVeto];
    slowChain->Add(files[l]);
    str = files[l];
    day= str(61,2);
    hour=str(64,2);
    dayNum=day.Atoi();
    hourNum=hour.Atoi();
    Double_t dayHour;
    dayHour= dayNum/1.0+hourNum/24.0;
    cerr<<"day and hour " <<dayHour<<endl;
    currentDay=dayNum;
    Int_t excludeList[52];
    Int_t numExcluded=0;

        
    wb->SetBranchAddress("target_4Minus2Mean1",&targetPMTQ);
    wb->SetBranchAddress("veto_3MinusMean1",&vetoPMTQ);
    wb->SetBranchAddress("target_1",&targetPMTPed);
    wb->SetBranchAddress("veto_1",&vetoPMTPed);
    wb->SetBranchAddress("time",&time);
        
    slowChain->SetBranchAddress("fit_means",&pedestalGateMean);
    slowChain->SetBranchAddress("fit_std_devs",&pedestalGateSigma);
    slowChain->SetBranchAddress("gateDev",&signalGateSigma);
    slowChain->SetBranchAddress("fit_chi2perndf",&chiSquare);

        
    //wb->SetBranchAddress("veto_summed_charge",&veto_summed_charge);
        
    wb->GetEntry(0);
    runtime=0;
    startTime=time;
        
    // readin pedestal  mean, sigma, signal pedestal sigma.
    //being done here for 1st file in chain - should be made Int_to function, so can be updated for each file in main event loop
        
    Long64_t nSlowEvent = slowChain->GetEntries();
    cout<<nSlowEvent<<" entries in slowChain"<<endl;
    cout<<"get entry"<<endl;
    slowChain->GetEntry(0);
    wb->GetEntry(nEntries-1);
    endTime=time;
    numEvents=nEntries; 
   
    runtime=(endTime-startTime)*4/(pow(10,9));

    //in case error in runtime, make sure we don't crash by diving by zero, but print that there was a problem
    if(runtime==0){
      runtime=3600;
      cerr<<"runtime set to default of 1 hour"<<endl;
    }
    liveTime+=runtime;
    cerr<<numEvents/runtime<<" Hz "<<endl;
    rateVrun<<l<<" "<<numEvents/runtime<<endl;
    h7->Fill(l+dayHour,numEvents/runtime);
    cerr<<"closing file"<<endl;
    //    f1->close();
    cerr<<"deleting file"<<endl;
    delete wb;
    f1->Close();
    delete f1;
    delete slowChain;
    //previousDay=currentDay;
    cerr<<"next event"<<endl;
  }
  ofstream liveTimes;
  liveTimes.open("livetimes.txt",ios_base::out|ios_base::app);
  liveTimes<<liveTime<<" live seconds in "<<month<<endl;
  cerr<<liveTime<<" live seconds in "<<month<<endl;
  liveTimes.close();
  rateVrun.close();
  //draw all 1D histograms on a single plot and write that plot to file
  TFile *f0 = new TFile(canvas,"RECREATE");
  TCanvas *c1 = new TCanvas("c1","Event Rate for Various Cuts",200,10,700,500);
    
  h7->SetMarkerStyle(2);
  h7->Draw("P");

  c1->Write();
  f0->Close();
    

    
}
Example #22
0
void PlotSingle(TString hname){
  TString sam = hname; sam.Remove(0,sam.First('_')+1);
  sam.Remove(sam.First('_'),sam.Length());
  TString smoo = hname;smoo.Remove(0,smoo.Last('_')+1);
  smoo.Remove(smoo.First('.'),smoo.Length());
  TString binString = hname; binString.Remove(binString.Last('_'),binString.Length());
  binString.Remove(0,binString.Last('_')+1);
  int nM2bin = binString.Atoi(); int nPlbin = nM2bin%1000;
  nM2bin = nM2bin/1000;
  TString basename(hname);
  Int_t slashpos = basename.Last('D');
  if (slashpos>=0) {
    basename.Remove(0,slashpos+1); basename.Remove(basename.First('.'),basename.Length());
  } else { cout<<hname<<" is incorrect"<<endl; return;}

  TString Base = "_"; Base += sam; Base += "_"; 
  Base += binString; Base += "_"; Base += smoo; 

  TFile hfile(hname); 
  TH2F *h2 = (TH2F *)gDirectory->Get("h2");
  TString inputfile = "fitSamples/pdfSample"; inputfile += sam; inputfile += ".root";
  cout << "File = " << inputfile << endl;	
  TChain c("ntp1");
  c.Add(inputfile);
  TCanvas mm("mm","KEYS fits to mmiss-pstarl",1200,800);
  double m2min = -4, m2max = 12, plmin = 0, plmax = 2.4;
  double xlow = m2min,xhigh = m2max, ylow = plmin,yhigh = plmax;
  Int_t nbinx = 80,nbiny = 80, Sam = sam.Atoi();
  if (Sam==0 || Sam==2 || Sam==10 || Sam==12 || Sam == 20 || Sam == 23 || Sam == 26 || Sam == 29) {
    xlow = -2; xhigh = 4;
    if (Sam > 12) {nbinx = 40; nbiny = 40;}
  } else if (Sam==1 || Sam==11) { xlow = -2; xhigh = 6;}
  if (Sam==6 || Sam==7 || Sam==16 || Sam==17) {nbinx = 40; nbiny = 40;}
  if (Sam==8 || Sam==18) {xhigh = 4; nbinx = 40; nbiny = 40;}
  if (Sam==9 || Sam==19) {nbinx = 40; nbiny = 40;}
  if (Sam==21 || Sam==22 || Sam==24 || Sam==25 || Sam==27 || Sam==28 || Sam==30 || Sam==31) {
    xhigh = 8; nbinx = 40; nbiny = 20;}
  if (Sam > 31) {nbinx = 40; nbiny = 20;}
  if(Sam==0){xlow=-1; xhigh=1;}
  double entries = c.GetEntries();
  Double_t hIntegral=h2->Integral();

  TString M2titles[] = {"0 < p*_{l} < 1 GeV","1 < p*_{l} < 1.4 GeV","1.4 < p*_{l} < 1.8 GeV",
		      "1.8 < p*_{l} < 2.4 GeV","0 < p*_{l} < 2.4 GeV"};
  TString Pltitles[] = {"-4 < m^{2}_{miss} < 1 GeV^{2}","1 < m^{2}_{miss} < 12 GeV^{2}",
			"-4 < m^{2}_{miss} < 12 GeV^{2}"};
  TCut M2cuts[] = {"candPstarLep<1","candPstarLep>1&&candPstarLep<1.4",
		      "candPstarLep>1.4&&candPstarLep<1.8","candPstarLep>1.8&&candPstarLep<2.4", ""};
  TCut Plcuts[] = {"candM2<1","candM2>=1",""};
  double PlLimits[] = {0, 1, 1.4, 1.8, 2.4};
  double M2Limits[] = {0., 5., 16.};
  int binlim[5]; int plbinlim[3];
  for(int i=0;i<5;i++) {
    PlLimits[i] = PlLimits[i]/2.4*(double)nPlbin;
    binlim[i] = (int)PlLimits[i];
    if(i<3){
      M2Limits[i] = M2Limits[i]/16.*(double)nM2bin;
      plbinlim[i] = (int)M2Limits[i];
    }
  }

  TString psname = "AWG82/results/keys/eps/Stitch/epsKeys"; psname += Base; psname += ".ps";
  mm.Print(psname+"[");
  TH1F *hm2[5], *m2[5], *hpl[3], *pl[3];
  TString M2names[5], Plnames[3];
  for(int i=0;i<5;i++){
    M2names[i] = "hm2_"; M2names[i] += i;
    hm2[i] = new TH1F(M2names[i],M2titles[i],nM2bin,m2min,m2max); 
    if(i<3) {
      Plnames[i] = "hpl_"; Plnames[i] += i;
      hpl[i] = new TH1F(Plnames[i],Pltitles[i],nPlbin,plmin,plmax); 
    }
  }
  
  hIntegral = h2->Integral();
  for(int i=0;i<5;i++){
    TString hdname = "dm2"; hdname += i;
    TString vari = "candM2>>"; vari+=hdname; vari+="("; vari+= nbinx; vari+=",";vari+= xlow; 
    vari+=",";vari+= xhigh; vari+=")";
    //M2cuts[i] += "weight<100";M2cuts[i] *= "wFF";
    c.Draw(vari,M2cuts[i]);
    m2[i] = (TH1F*)gDirectory->Get(hdname);
    m2[i]->SetXTitle("m^{2}_{miss} [GeV^{2}]");
    formatHisto(m2[i]);
    gStyle->SetOptStat(0);
    if(i<4){
      for(int j=1; j<nM2bin+1; j++){
	double binVal = 0;
	for(int binp = binlim[i]+1; binp < binlim[i+1]+1; binp++){
	  binVal+=h2->GetBinContent(j,binp)*entries*nM2bin*(xhigh-xlow)/nbinx/(m2max-m2min)/hIntegral;
	}
	hm2[i]->SetBinContent(j,binVal);
      }
    } 
    hm2[i]->SetLineColor(4);
    hm2[i]->SetLineWidth(1);
    if(i<4) hm2[4]->Add(hm2[i]);
  }
  for(int i=0;i<3;i++){
    TString hdname = "pl"; hdname += i;
    TString vari = "candPstarLep>>"; vari+=hdname; vari+="("; vari+= nbiny; vari+=",";vari+= ylow; 
    vari+=",";vari+= yhigh; vari+=")";
    cout<<vari<<"  "<<endl;
    //Plcuts[i] += "weight<100";Plcuts[i] *= "wFF";
    c.Draw(vari,Plcuts[i]);
    pl[i] = (TH1F*)gDirectory->Get(hdname);
    pl[i]->SetXTitle("p*_{l} [GeV]");
    formatHisto(pl[i]);
    gStyle->SetOptStat(0);
    if(i<2){
      for(int j=1; j<nPlbin+1; j++){
	double binVal = 0;
	for(int binp = plbinlim[i]+1; binp < plbinlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(binp,j)*entries*nPlbin/nbiny/hIntegral;	
	}
	hpl[i]->SetBinContent(j,binVal);
      }
    }
    hpl[i]->SetLineColor(4);
    hpl[i]->SetLineWidth(1);
    if(i<2) hpl[2]->Add(hpl[i]);
  }
  cout<<"End for"<<endl;
  m2[4]->Draw("e0"); m2[4]->Draw("e1 same"); hm2[4]->Draw("c same"); mm.Print(psname);
  pl[2]->Draw("e0"); pl[2]->Draw("e1 same"); hpl[2]->Draw("c same"); mm.Print(psname);
  for(int i=0;i<4;i++){
    m2[i]->Draw("e0"); m2[i]->Draw("e1 same"); hm2[i]->Draw("c same"); mm.Print(psname);
  }
  for(int i=0;i<2;i++){
    pl[i]->Draw("e0"); pl[i]->Draw("e1 same"); hpl[i]->Draw("c same"); mm.Print(psname);
  }
  mm.Print(psname+"]");

  TLatex *label = new TLatex(); label->SetNDC(kTRUE); label->SetTextSize(0.055);

  TCanvas all6("all6","KEYS fits to mmiss-pstarl",1700,1800);
  all6.cd();
  all6.Divide(2,3,0.001,0.001);
  all6.cd(1);gPad->SetTopMargin(0.004);gPad->SetRightMargin(0.003);gPad->SetBottomMargin(0.11);
  gPad->SetFillColor(10);gPad->SetFrameFillColor(10);
  m2[4]->Draw("e0");  m2[4]->Draw("e1 same"); hm2[4]->Draw("c same");
  all6.cd(2);gPad->SetTopMargin(0.004);gPad->SetRightMargin(0.003);gPad->SetBottomMargin(0.11);
  gPad->SetFillColor(10);gPad->SetFrameFillColor(10);
  pl[2]->Draw("e0");  pl[2]->Draw("e1 same"); hpl[2]->Draw("c same");
  for(int i=0;i<4;i++){
    all6.cd(i+3);gPad->SetTopMargin(0.003);gPad->SetRightMargin(0.003);gPad->SetBottomMargin(0.11);
    gPad->SetFillColor(10);gPad->SetFrameFillColor(10);
    m2[i]->Draw("e0"); label->DrawLatex(0.69,0.92,M2titles[i]);
    m2[i]->Draw("e1 same"); hm2[i]->Draw("c same"); 
  }
  TString epsname = "AWG82/results/keys/eps/Stitch/EpsKeys";
  epsname += Base; epsname += ".eps";
  all6.SaveAs(epsname);

  h2->Delete();
  return; 

}
//void main_makePlots()
int main(int argc, char* argv[])
{
  // Output filenames options - for creation of a log file and a histogram file in the given directory
    TString dir = "control_plots/";
    TString tst = fileTimeStamp();
    TString pfx = "_plots_";
    TString sfx = "_NO_MET_CUT";

  // Process input
    if(argc<3)
    {
        cout << "\n    ERROR: Please enter a decay chain, dataset, and (optional) a max number of events.\n" << endl;
        return 1;
    }

    TString decayChain       = argv[1];
    TString dataset          = argv[2];
    TString maxEventsStr     = ""     ;
    if(argc>=4)
    {
        maxEventsStr = argv[3];
        if(!maxEventsStr.IsFloat())
        {
            cout << "\n    ERROR: Please enter the number of events you want to process for your third option"
                    "\n    (or nothing if you want to process them all).\n"
                 << endl;
            return 1;
        }
    }

    if(decayChain!="Zuu" && decayChain!="Zee" && decayChain!="Zttuu" && decayChain!="Zttee")
    {
        cout << "\n    ERROR: Please specify one of the following decay chains for your first option: Zuu, Zee, Zttuu, Zttee\n" << endl;
        return 1;
    }

  // Open files and map trees
    TFile* f_input;
    if     (dataset == "muon"    ) f_input = TFile::Open(fn_muon   );
    else if(dataset == "elec"    ) f_input = TFile::Open(fn_elec   );
    else if(dataset == "dy"      ) f_input = TFile::Open(fn_dy     );
    else if(dataset == "dy1j"    ) f_input = TFile::Open(fn_dy1j   );
    else if(dataset == "ww"      ) f_input = TFile::Open(fn_ww     );
    else if(dataset == "wz"      ) f_input = TFile::Open(fn_wz     );
    else if(dataset == "zz"      ) f_input = TFile::Open(fn_zz     );
    else if(dataset == "tthad"   ) f_input = TFile::Open(fn_tthad  );
    else if(dataset == "ttlep"   ) f_input = TFile::Open(fn_ttlep  );
    else if(dataset == "ttsemi"  ) f_input = TFile::Open(fn_ttsemi );
    else if(dataset == "t_s"     ) f_input = TFile::Open(fn_t_s    );
    else if(dataset == "t_t"     ) f_input = TFile::Open(fn_t_t    );
    else if(dataset == "t_tw"    ) f_input = TFile::Open(fn_t_tw   );
    else if(dataset == "tbar_s"  ) f_input = TFile::Open(fn_tbar_s );
    else if(dataset == "tbar_t"  ) f_input = TFile::Open(fn_tbar_t );
    else if(dataset == "tbar_tw" ) f_input = TFile::Open(fn_tbar_tw);
    else
    {
        cout << "\n    ERROR: Please specify one of the following datasets for your second option:"
                "\n                muon, elec, dy, dy1j, ww, wz, zz, tthad, ttlep, ttsemi, t(bar)_(s/t/tw)\n" << endl;
        return 1;
    }

    // If tau tau decays specified on a non-dy set.
    if( (decayChain=="Zttuu" || decayChain=="Zttee") && (dataset!="dy" && dataset!="dy1j"))
    {
        cout << "\n    ERROR: Tau decay split only valid for DY datasets\n" << endl;
        return 1;
    }

    TTree* t_input = (TTree*)f_input->Get("tree");
    
  // Create an instance of the ZCControlPlotMaker and input options
    ZCControlPlotMaker *plotMaker = new ZCControlPlotMaker();
    TString outputFileName = dir+tst+pfx+decayChain+"_"+dataset+sfx;
    TString options = decayChain;
    if(dataset!="muon" && dataset!="elec") options+=",sim";
    if(dataset=="dy")                      options+=",dy";

  // Process tree and save output
    if(maxEventsStr!="")
         t_input->Process(plotMaker, options, maxEventsStr.Atoi() );
    else t_input->Process(plotMaker, options                      );
    cout << plotMaker->saveOutputToFile(outputFileName) << endl;


return 0;

}
Example #24
0
void MPDummyForLowStat(const char* stfile, int thr=30, int nGen=40,Bool_t bin=kTRUE)
{
  // show degrees of freedom with low stat
  TFile* fl = TFile::Open(stfile);
  if (!fl) {printf("Failed to open %s\n",stfile); return;}
  TList* lst = (TList*)fl->Get("clist");
  if (!lst) {printf("No clist in %s\n",stfile); return;}
  TH1* hstdof = (TH1*)lst->FindObject("DOFstat");
  if (!hstdof) {printf("No DOFstat histo in %s\n",stfile); return;}
  //
  int ndof = hstdof->GetNbinsX();
  TAxis* xax = hstdof->GetXaxis();
  printf("%4s\t%-50s\t%s","cnt"," DOF ID_name","entries");
  Mille* ml = 0;
  AliAlgSteer* algSteer=0;
  AliAlgMPRecord* mpRec=0;
  //
  if (bin) ml = new Mille(Form("%s.%s",mpDummy.Data(),"mille"));
  else {
    algSteer = new AliAlgSteer();
    algSteer->SetMPDatFileName(mpDummy.Data());
    algSteer->SetMPOutType(AliAlgSteer::kMPRec);
    algSteer->InitMPRecOutput();
    mpRec = algSteer->GetMPRecord();
  }
  //
  int   labDum[1] = {0}, cnt=0;
  float locDum[1] = {0}, gloDum[1] = {kDummyDer};
  //
  for (int i=1;i<=ndof;i++) {
    if (hstdof->GetBinContent(i)>thr) continue;
    TString labS = xax->GetBinLabel(i);
    printf("%4d\t%-50s\t%7d\n",cnt++,labS.Data(),(int)hstdof->GetBinContent(i));
    int indL = labS.Index("_");
    if (indL>0) labS.Resize(indL);
    else {
      printf("Failed to extract label from %s\n",labS.Data());
      exit(1);
    }
    labDum[0] = labS.Atoi();
    if (bin) {
      for (int j=nGen;j--;) {
	ml->mille(0, locDum, 1, gloDum, labDum, kDummyRes, kDummyErr);
	ml->end();
      }
    }
    else {
      mpRec->DummyRecord(kDummyRes,kDummyErr,kDummyDer,labDum[0]);
      for (int j=nGen;j--;) algSteer->GetMPRecTree()->Fill();
    }
  }
  //
  if (bin) delete ml;
  else {
    algSteer->CloseMPRecOutput();
    delete algSteer;
  }
  //
  lst->SetOwner();
  delete lst;
  fl->Close();
  delete fl;
}
Example #25
0
void keys(TString sam="0", TString smooth = "100") {
  gSystem->Load("libHtml");
  gSystem->Load("libMinuit");
  gSystem->Load("libRooFitCore.so");
  gSystem->Load("libRooFitModels.so");
  using namespace RooFit;
  time_t start,end;
  time (&start);
  double dif;
  RooRealVar mmiss2("candM2","candM2",-4,12);
  RooRealVar pstarl("candPstarLep","candPstarLep",0.,2.4);

  RooArgSet myVars(mmiss2,pstarl);

  TString inputfile = "fitSamples/pdfSample"; inputfile += sam; inputfile += ".root";
  cout << "File = " << inputfile << endl;	
  TChain c("ntp1");
  c.Add(inputfile);
  RooDataSet  data("data","data",myVars);

  Int_t MCType,MCSubmode,MCDssmode,MCD,MCPions,MCCombB,MCCombDs,MCDoubleSL,
    candTruLep,candDstarType,isBzero,isSP6,MCTaumode,trueLepCharge;
  Float_t candM2,candPstarLep;
  Float_t truePPi0,trueDssPPi0,CTL,CTV,Chi,Q2,trueDmass;
  c.SetBranchAddress("MCType",&MCType);
  c.SetBranchAddress("MCSubmode",&MCSubmode);
  c.SetBranchAddress("MCDssmode",&MCDssmode);
  c.SetBranchAddress("MCD",&MCD);
  c.SetBranchAddress("MCPions",&MCPions);
  c.SetBranchAddress("MCCombB",&MCCombB);
  c.SetBranchAddress("MCCombDs",&MCCombDs);
  c.SetBranchAddress("MCDoubleSL",&MCDoubleSL);
  c.SetBranchAddress("candLepTru",&candTruLep);
  c.SetBranchAddress("candDstarType",&candDstarType);
  c.SetBranchAddress("isBzero",&isBzero);
  c.SetBranchAddress("isSP6",&isSP6);
  c.SetBranchAddress("MCTaumode",&MCTaumode);
  c.SetBranchAddress("truePPi0",&truePPi0);
  c.SetBranchAddress("trueDssPPi0",&trueDssPPi0);
  c.SetBranchAddress("trueCTL",&CTL);
  c.SetBranchAddress("trueCTV",&CTV);
  c.SetBranchAddress("trueChi",&Chi);
  c.SetBranchAddress("trueQ2",&Q2);
  c.SetBranchAddress("trueLepCharge",&trueLepCharge);
  c.SetBranchAddress("trueDmass",&trueDmass);
  c.SetBranchAddress("candM2",&candM2);
  c.SetBranchAddress("candPstarLep",&candPstarLep);
  TRandom3 rand; int ran;
  int transform = 1;
  TCanvas mm("mm","KEYS fits to mmiss-pstarl",1200,800);
  gStyle->SetPalette(1);
  double All = 8;
  TH2F rotated("rotated","Rotated m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  TH2F ori("ori","Original m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  //TH2F totcov("ori2","Original m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  double r11, r12, Xmean, Ymean;
  double x[] = {-2,-1,1,2};
  double y[] = {-4,-2,2,4};
  if(transform ==1){
    c.Draw("candPstarLep:candM2>>cov(200,-4,12,200,0,2.4)","","contz");
    TH2F *totcov = (TH2F*)gDirectory->Get("cov");
    //for(int i=0;i<4;i++)totcov.Fill(x[i],y[i]);
    double xx = totcov->GetRMS(1); xx = xx*xx;
    double yy = totcov->GetRMS(2); yy = yy*yy;
    double xy = totcov->GetCovariance();
    Xmean = totcov->GetMean(1);
    Ymean = totcov->GetMean(2);
    double lambda = (-sqrt(xx*xx-2*xx*yy+4*xy*xy+yy*yy)+xx+yy)/2;
    double lambda2 = (sqrt(xx*xx-2*xx*yy+4*xy*xy+yy*yy)+xx+yy)/2;
    if(lambda2>lambda) lambda = lambda2;
    r11 = (lambda-yy)/xy;
    r12 = -1/sqrt(r11*r11+1);
    r11 = -r11/sqrt(r11*r11+1);
    if(r12*r11>0&&r12<0 || r12*r11<0&&r11<0){
      r12 = -r12;
      r11 = -r11;
    }
    cout<<"RMSx "<<xx<<", RMSy "<<yy<<", lambda "<<lambda<<" and covariance "<<xy<<endl;
  }
  double mmp, plp;
  double entries = c.GetEntries();
  //entries = 4;
  for (int evt = 0 ; evt < entries; evt ++) {
    ran = rand.Uniform(entries);
    //c.GetEvent(ran);
    c.GetEvent(evt);
    double Mx = candM2-Xmean, Py = candPstarLep-Ymean;
    mmp = r11*(Mx)+r12*(Py);
    plp = -r12*(Mx)+r11*(Py);
    ori.Fill(Mx,Py);
    rotated.Fill(mmp,plp);
    mmiss2.setVal(candM2);
    pstarl.setVal(candPstarLep);
//     if (MCType == 0)
//       totWeight.setVal(myWM->getCombWeight(MCCombB,MCCombDs,MCDoubleSL,candTruLep));
//     else
//       totWeight.setVal(myWM->getEventWeight(candType,candDstarType,MCType,MCSubmode,MCDssmode,MCD,MCPions,
// 					    isBzero,isSP6,MCTaumode,truePPi0,trueDmass,CTL,CTV,Chi,Q2,
// 					    trueLepCharge,candM2));
    data.add(RooArgSet(mmiss2,pstarl));
  }
  //data.setWeightVar(totWeight);
  ori.Draw("contz");
  mm.SaveAs("original.eps");
  rotated.Draw("contz");
  mm.SaveAs("rotated.eps");
  cout<<"("<<r11<<", "<<r12<<") and covariance "<<rotated.GetCovariance()<<endl;
  return;

  double smoo = smooth.Atof()/100.;
  Roo2DKeysPdf DPpdf("DPpdf","DPpdf",mmiss2,pstarl,data,"av",smoo);
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after finding the KEYS function"<<endl;
  time (&start);
  int ntotbin = 800;
  TH2F *h2 = new TH2F("h2","KEYS",ntotbin,-4,12,ntotbin,0,2.4);
  DPpdf.fillHistogram(h2,RooArgList(mmiss2,pstarl));
  TString hname = "AWG82/results/keys/root/hKeys"; hname += sam; hname += "_"; hname += smooth; hname += ".root";
  TFile* hfile = new TFile(hname,"RECREATE"); 
  h2->Write();
  hfile->Close();
  cout<<"KEYS histogram saved in "<<hname<<endl;
  RooDataHist* Rdh2 = new RooDataHist("Rdh2","KEYS",RooArgList(mmiss2,pstarl),h2);
  RooHistPdf* Rh2 = new RooHistPdf("Rh2","KEYS",RooArgList(mmiss2,pstarl),*Rdh2,2);
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after making histogram"<<endl;
  time (&start);

  Float_t xlow,xhigh;
  Int_t nbinx,nbiny,Sam = sam.Atoi();
  xlow = -4;
  xhigh = 12;
  nbinx = 80;
  nbiny = 80;
  if (Sam==0 || Sam==2 || Sam==10 || Sam==12 || Sam == 20 || Sam == 23 || Sam == 26 || Sam == 29) {
    xlow = -2; xhigh = 4;
    if (Sam > 12) {nbinx = 40; nbiny = 40;}
  }
  else if (Sam==1 || Sam==11) {
    xlow = -2; xhigh = 6;
  }
  if (Sam==6 || Sam==7 || Sam==16 || Sam==17) {
    nbinx = 40; nbiny = 40;
  }
  if (Sam==8 || Sam==18) {
    xhigh = 4; nbinx = 40; nbiny = 40;
  }
  if (Sam==9 || Sam==19) {
    nbinx = 40; nbiny = 40;
  }
  if (Sam==21 || Sam==22 || Sam==24 || Sam==25 || Sam==27 || Sam==28 || Sam==30 || Sam==31) {
    xhigh = 8; nbinx = 40; nbiny = 20;
  }
  if (Sam > 31) {
    nbinx = 40; nbiny = 20;
  }

  TString M2titles[] = {"0 < p*_{l} < 1 GeV","1 < p*_{l} < 1.4 GeV","1.4 < p*_{l} < 1.8 GeV",
		      "1.8 < p*_{l} < 2.4 GeV","0 < p*_{l} < 2.4 GeV"};
  TString Pltitles[] = {"-4 < m^{2}_{miss} < 1.5 GeV^{2}","1.5 < m^{2}_{miss} < 12 GeV^{2}",
			"-4 < m^{2}_{miss} < 12 GeV^{2}"};
  TString M2cuts[] = {"candPstarLep<1","candPstarLep>1&&candPstarLep<1.4",
		      "candPstarLep>1.4&&candPstarLep<1.8","candPstarLep>1.8&&candPstarLep<2.4", ""};
  TString Plcuts[] = {"candM2<1.5","candM2>=1.5",""};
  double limits[] = {0, 1, 1.4, 1.8, 2.4};
  int binlim[5];
  for(int i=0;i<5;i++) binlim[i] = limits[i]/2.4*ntotbin;

  TString psname = "AWG82/results/keys/eps/eps2Keys"; psname+=sam; psname+="_";
  psname += smooth; psname += ".ps";
  double tot = 0;
  mm.Print(psname+"[");
  TH1F *hm2[5], *m2[5], *hpl[3], *pl[3];
  TString M2names[5], Plnames[3];
  for(int i=0;i<5;i++){
    M2names[i] = "hm2_"; M2names[i] += i;
    hm2[i] = new TH1F(M2names[i],M2titles[i],ntotbin,-4,12); 
    if(i<3) {
      Plnames[i] = "hpl_"; Plnames[i] += i;
      hpl[i] = new TH1F(Plnames[i],Pltitles[i],ntotbin,0,2.4); 
    }
  }    
  for(int i=0;i<5;i++){
    TString hname = "m2"; hname += i;
    TString vari = "candM2>>"; vari+=hname; vari+="("; vari+= nbinx; vari+=",";vari+= xlow; 
    vari+=",";vari+= xhigh; vari+=")";
    c.Draw(vari,M2cuts[i]);
    m2[i] = (TH1F*)gDirectory->Get(hname);
    m2[i]->SetXTitle("m^{2}_{miss} [GeV^{2}]");
    m2[i]->SetTitle(M2titles[i]);
    m2[i]->Sumw2();
    m2[i]->SetMarkerStyle(20);
    m2[i]->SetMarkerSize(1);
    gStyle->SetOptStat(0);
    if(i<4){
      for(int j=1; j<ntotbin+1; j++){
	double binVal = 0;
	for(int binp = binlim[i]+1; binp < binlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(j,binp)*entries*ntotbin*(xhigh-xlow)/nbinx/16;	
	}
	hm2[i]->SetBinContent(j,binVal);
      }
    } 
    hm2[i]->SetLineColor(4);
    hm2[i]->SetLineWidth(2);
    if(i<4) hm2[4]->Add(hm2[i]);
  }
  int plbinlim[3] = {0,ntotbin*5.5/16,ntotbin};
  for(int i=0;i<3;i++){
    TString hname = "pl"; hname += i;
    TString vari = "candPstarLep>>"; vari+=hname; vari+="("; vari+= nbiny; vari+=",0,2.4)";
    c.Draw(vari,Plcuts[i]);
    pl[i] = (TH1F*)gDirectory->Get(hname);
    pl[i]->SetXTitle("p*_{l} [GeV]");
    pl[i]->SetTitle(Pltitles[i]);
    pl[i]->Sumw2();
    pl[i]->SetMarkerStyle(20);
    pl[i]->SetMarkerSize(1);
    gStyle->SetOptStat(0);
    if(i<2){
      for(int j=1; j<ntotbin+1; j++){
	double binVal = 0;
	for(int binp = plbinlim[i]+1; binp < plbinlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(binp,j)*entries*ntotbin/nbiny;	
	}
	hpl[i]->SetBinContent(j,binVal);
      }
    }
    hpl[i]->SetLineColor(4);
    hpl[i]->SetLineWidth(2);
    if(i<2) hpl[2]->Add(hpl[i]);
  }
  m2[4]->Draw("e1"); hm2[4]->Draw("c same"); mm.Print(psname);
  pl[2]->Draw("e1"); hpl[2]->Draw("c same"); mm.Print(psname);
  for(int i=0;i<4;i++){
    m2[i]->Draw("e1"); hm2[i]->Draw("c same"); mm.Print(psname);
  }
  for(int i=0;i<2;i++){
    pl[i]->Draw("e1"); hpl[i]->Draw("c same"); mm.Print(psname);
  }
  mm.Print(psname+"]");
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after plotting data. Written "<<psname<<endl;
  return; 

} 
Example #26
0
void TExpenser::drawIncomeTab() {

    // create the income tab
    fIncomeTab = fTab->AddTab("Income");
    fIncomeTab -> SetLayoutManager(new TGHorizontalLayout(fIncomeTab));

    // create table interface
    const unsigned ncolumns =  3;
    TGExpenserTableInterface * income_table = new TGExpenserTableInterface(ncolumns);
    TString columns[ncolumns]={"amount", "description", "date"};
    income_table -> setColumnNames(columns);

    fIncomeXMLParser->selectMainNode();
    fIncomeXMLParser->selectNode("entry");
    vector<expense> incomes;
    while (fIncomeXMLParser->getCurrentNode() != 0) {
        XMLNodePointer_t current_node = fIncomeXMLParser->getCurrentNode();

        fIncomeXMLParser -> selectNode("date");
        TString year = fIncomeXMLParser -> getNodeContent("year");
        TString month = fIncomeXMLParser -> getNodeContent("month");
        fIncomeXMLParser -> setCurrentNode(current_node);

        if (month.Atoi()<10) month="0"+month;

        expense in;
        in.amount = fIncomeXMLParser -> getNodeContent("amount");
        in.description = fIncomeXMLParser -> getNodeContent("description");
        in.date = year+month;
        in.dateForCell = month+"/"+year;
        incomes.push_back(in);

        fIncomeXMLParser->selectNextNode("entry");
    }

    sort(incomes.begin(), incomes.end(), compare);

    for (unsigned i=0; i<incomes.size(); i++) {
        income_table -> addCell (i, incomes[i].amount);
        income_table -> addCell (i, incomes[i].description);
        income_table -> addCell (i, incomes[i].dateForCell);
    }
    unsigned entries = incomes.size();

    // Create the table
    TGTable * fInTable = new TGTable(fIncomeTab, 999, income_table, NROWSTABLE, income_table->GetNColumns());
    fIncomeTab -> AddFrame(fInTable, new TGLayoutHints(kLHintsCenterY,2,2,2,2));

    /*
    TGVerticalFrame *vframe = new TGVerticalFrame(fIncomeTab, 60, 40);
    fIncomeTab -> AddFrame(vframe, new TGLayoutHints(kLHintsCenterX,2,2,2,2));

    // year selector
    TDatime time;
    TGComboBox * income_tab_year = new TGComboBox(vframe);
    for (unsigned i = FIRST_YEAR; i <= LAST_YEAR; i++) {
        income_tab_year->AddEntry(toStr(i), i+1-FIRST_YEAR);
    }
    income_tab_year->Resize(100, 20);
    income_tab_year->Select(time.GetYear()-FIRST_YEAR+1);
    vframe->AddFrame(income_tab_year, new TGLayoutHints(kLHintsLeft,5,10,5,5));

    TGTextButton * apply_button = new TGTextButton(vframe,"&Apply");
    apply_button -> Connect("Clicked()", "TExpenser", this, "calculate_monthly()");
    vframe -> AddFrame(apply_button, new TGLayoutHints(kLHintsLeft,5,5,3,4));
    */
}
Example #27
0
void KVGeoNavigator::ExtractDetectorNameFromPath(KVString& detname)
{
   // We analyse the current path in order to construct the full (unique) name
   // of the detector, i.e. if the current path is
   //
   // /TOP_1/STRUCT_BLOCK_2/CHIO_WALL_1/DET_CHIO_2/WINDOW_1
   //
   // then the default name of the detector will be "BLOCK_2_CHIO_2"
   // (see below to override this)
   //
   // This method also fills the fCurrentStructures array with elements
   // deduced from the path, e.g. if the path is
   //
   // /TOP_1/STRUCT_BLOCK_2/STRUCT_QUARTET_1/DET_SI1-T1
   //
   // then by default
   //  fCurrentStructures[0] = KVGeoStrucElement(name = "BLOCK_2", type = "BLOCK", number = 2)
   //  fCurrentStructures[1] = KVGeoStrucElement(name = "QUARTET_1", type = "QUARTET", number = 1)
   //
   // and the default name of the detector will be "BLOCK_2_QUARTET_1_SI1-T1"
   //
   // STRUCTURE & DETECTOR NAME FORMATTING
   // ====================================
   //    -- STRUCTURES --
   // The default names for structures are taken from the node name by stripping off
   // the "STRUCT_" prefix. It is assumed that the remaining string is of the form
   //    "[structure type]_[structure number]"
   // (the structure number is always taken after the last occurence of '_' in the
   // node name). This is the name that will be used by default for the structure.
   // However, this format can be change by calling method
   //    SetStructureNameFormat("[structure type]", "[format]")
   // where format can contain any of the following tokens:
   //    $type$         - will be replaced by the structure type name
   //    $type%[fmt]$   - will be replaced by the structure type name using given format
   //    $number$       - will be replaced by the structure number
   //    $number%[fmt]$ - will be replaced by the structure number using given format
   //
   // Example: to change the name of the block in the previous example to "B-02",
   //   SetStructureNameFormat("BLOCK", "$type%.1s$-$number%02d$")
   //
   //    -- DETECTORS --
   // The default base names for detectors are taken from the node name by stripping off
   // the "DET_" prefix. In order to ensure that all detectors have unique names,
   // by default we prefix the names of the parent structures to the basename in
   // order to generate the full name of the detector:
   //    [struc1-name]_[struc2-name]_..._[detector-basename]
   // However, this format can be changed by calling method
   //    SetDetectorNameFormat("[format]")
   // where format can contain any of the following tokens:
   //    $det:name$             - will be replaced by the detector basename
   //    $struc:[type]:name$    - will be replaced by the name of the parent structure of given type
   //    $struc:[type]:type$    - will be replaced by the type of the parent structure of given type
   //    $struc:[type]:number$  - will be replaced by the number of the parent structure of given type
   // plus additional formatting information as for SetStructureNameFormat (see above).
   //
   // Example: to change the name of the "SI1-T1" detector in the previous example to
   //  "SI1-T1-Q1-B2":
   //   SetDetectorNameFormat("$det:name$-Q$struc:QUARTET:number$-B$struc:BLOCK:number$")
   // Or if you also change the format of the structure names:
   //   SetStructureNameFormat("BLOCK", "$type%.1s$$number$")
   //   SetStructureNameFormat("QUARTET", "$type%.1s$$number$")
   //   SetDetectorNameFormat("$det:name$-$struc:QUARTET:name$-$struc:BLOCK:name$")


   KVString path = GetCurrentPath();
   path.Begin("/");
   detname = "";
   fCurrentStructures.Clear("C");
   fCurStrucNumber = 0;
   while (!path.End()) {
      KVString elem = path.Next();
      if (elem.BeginsWith("STRUCT_")) {
         // structure element. strip off "STRUCT_" and extract type and number of structure.
         KVString struc_name(elem(7, elem.Length() - 7));
         KVGeoStrucElement* gel = (KVGeoStrucElement*)fCurrentStructures.ConstructedAt(fCurStrucNumber++);
         Ssiz_t last_ = struc_name.Last('_'); // find last '_' in structure name
         TString type = struc_name(0, last_);
         TString nums = struc_name(last_ + 1, struc_name.Length() - last_ - 1);
         Int_t number = nums.Atoi();
         KVString name;
         FormatStructureName(type, number, name);
         gel->SetNameTitle(name, type);
         gel->SetNumber(number);
      } else if (elem.BeginsWith("DET_")) {
         // detector name. strip off "DET_" and use rest as basename
         KVString basename(elem(4, elem.Length() - 4));
         FormatDetectorName(basename, detname);
      }
   }
}
Example #28
0
void onecut::assignBranch(TString var, TString val){
  if(var == "ht"){
    cutType_ = kFloat;
    bf_ = &baby_base::ht;
  } else if(var == "st"){
    cutType_ = kFloat;
    bf_ = &baby_base::st;
  }else if(var=="met"){
    cutType_ = kFloat;
    bf_ = &baby_base::met;
  }else if(var=="met_tru"){
    cutType_ = kFloat;
    bf_ = &baby_base::met_tru;
  }else if(var=="ht_ra2"){
    cutType_ = kFloat;
    bf_ = &baby_base::ht_ra2;
  }else if(var=="ht_clean"){
    cutType_ = kFloat;
    bf_ = &baby_base::ht_clean;
  }else if(var=="mht"){
    cutType_ = kFloat;
    bf_ = &baby_base::mht;
  }else if(var=="mt"){
    cutType_ = kFloat;
    bf_ = &baby_base::mt;
  }else if(var=="elelv_pt"){
    cutType_ = kFloat;
    bf_ = &baby_base::elelv_pt;
  }else if(var=="elel_pt"){
    cutType_ = kFloat;
    bf_ = &baby_base::elel_pt;
  }else if(var=="elelv_m"){
    cutType_ = kFloat;
    bf_ = &baby_base::elelv_m;
  }else if(var=="elel_m"){
    cutType_ = kFloat;
    bf_ = &baby_base::elel_m;
  }else if(var=="mumuv_pt"){
    cutType_ = kFloat;
    bf_ = &baby_base::mumuv_pt;
  }else if(var=="mumu_pt"){
    cutType_ = kFloat;
    bf_ = &baby_base::mumu_pt;
  }else if(var=="mumuv_m"){
    cutType_ = kFloat;
    bf_ = &baby_base::mumuv_m;
  }else if(var=="mumu_m"){
    cutType_ = kFloat;
    bf_ = &baby_base::mumu_m;
  }else if(var=="mj"){
    cutType_ = kFloat;
    bf_ = &baby_base::mj;
  }else if(var=="mj08"){
    cutType_ = kFloat;
    bf_ = &baby_base::mj08;
  }else if(var=="mj14"){
    cutType_ = kFloat;
    bf_ = &baby_base::mj14;
  }else if(var=="mj16"){
    cutType_ = kFloat;
    bf_ = &baby_base::mj16;
  }else if(var=="nleps"){
    cutType_ = kInt;
    bi_ = &baby_base::nleps;
  }else if(var=="nvels"){
    cutType_ = kInt;
    bi_ = &baby_base::nvels;
  }else if(var=="nels"){
    cutType_ = kInt;
    bi_ = &baby_base::nels;
  }else if(var=="nvmus"){
    cutType_ = kInt;
    bi_ = &baby_base::nvmus;
  }else if(var=="nveto"){
    cutType_ = kInt;
    bi_ = &baby_base::nveto;
  }else if(var=="nmus"){
    cutType_ = kInt;
    bi_ = &baby_base::nmus;
  }else if(var=="ntruleps"){
    cutType_ = kInt;
    bi_ = &baby_base::ntruleps;
  }else if(var=="ntrutaush"){
    cutType_ = kInt;
    bi_ = &baby_base::ntrutaush;
  }else if(var=="njets"){
    cutType_ = kInt;
    bi_ = &baby_base::njets;
  }else if(var=="njets_ra2"){
    cutType_ = kInt;
    bi_ = &baby_base::njets_ra2;
  }else if(var=="njets_clean"){
    cutType_ = kInt;
    bi_ = &baby_base::njets_clean;
  }else if(var=="run"){
    cutType_ = kInt;
    bi_ = &baby_base::run;
  }else if(var=="nbm"){
    cutType_ = kInt;
    bi_ = &baby_base::nbm;
  }else if(var=="pass"){
    cutType_ = kBool;
    bb_ = &baby_base::pass;
  }else if(var=="stitch"){
    cutType_ = kBool;
    bb_ = &baby_base::stitch;
  }else if(var=="nonblind"){
    cutType_ = kBool;
    bb_ = &baby_base::nonblind;
  }else if(var=="pass_ra2"){
    cutType_ = kBool;
    bb_ = &baby_base::pass_ra2;
  }else if(var=="pass_jets"){
    cutType_ = kBool;
    bb_ = &baby_base::pass_jets;
  } else if(var.Contains("[")){ // if var is a vector element
    TString index_s(var);
    var.Remove(var.Index("["), var.Length());
    index_s.Remove(0, index_s.Index("[")+1);
    index_s.Remove(index_s.Index("]"), index_s.Length());
    ivector_ = index_s.Atoi();
    if(var=="trig"){
      cutType_ = kvBool;
      bvb_ = &baby_base::trig;
    }else if(var=="sys_pass"){
      cutType_ = kvBool;
      bvb_ = &baby_base::sys_pass;
    }else if(var=="sys_ht"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_ht;
    }else if(var=="sys_st"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_st;
    }else if(var=="sys_met"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_met;
    }else if(var=="leps_pt"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::leps_pt;
    }else if(var=="sys_njets"){ 
      cutType_ = kvInt;
      bvi_ = &baby_base::sys_njets;
    }else if(var=="sys_nbm"){ 
      cutType_ = kvInt;
      bvi_ = &baby_base::sys_nbm;
    }else if(var=="sys_mj"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_mj;
    }else if(var=="sys_mj14"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_mj14;
    }else if(var=="sys_mt"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_mt;
    }else {
      cout<<endl<<"Branch \""<<var<<" not defined. Add it to onecut::assignBranch in bcut.cpp"<<endl<<endl;
      exit(0);
    }
  }else {
    cout<<endl<<"Branch \""<<var<<" not defined. Add it to onecut::assignBranch in bcut.cpp"<<endl<<endl;
    exit(0);
  } 

  if(cutType_ == kFloat || cutType_ == kvFloat) cutf_ = val.Atof();
  if(cutType_ == kInt || cutType_ == kvInt)     cuti_ = val.Atoi();
}
Example #29
0
//_____________________________________________________________________________
void ProofSimpleFile::SlaveBegin(TTree * /*tree*/)
{
   // The SlaveBegin() function is called after the Begin() function.
   // When running with PROOF SlaveBegin() is called on each slave server.
   // The tree argument is deprecated (on PROOF 0 is passed).

   TString option = GetOption();

   // Number of histograms (needed in terminate)
   Ssiz_t iopt = kNPOS;
   if (fInput->FindObject("ProofSimpleFile_NHist")) {
      TParameter<Long_t> *p =
         dynamic_cast<TParameter<Long_t>*>(fInput->FindObject("ProofSimpleFile_NHist"));
      fNhist = (p) ? (Int_t) p->GetVal() : fNhist;
   } else if ((iopt = option.Index("nhist=")) != kNPOS) {
      TString s;
      Ssiz_t from = iopt + strlen("nhist=");
      if (option.Tokenize(s, from, ";") && s.IsDigit()) fNhist = s.Atoi();
   }

   // The file for merging
   fProofFile = new TProofOutputFile("SimpleFile.root", "M");
   TNamed *out = (TNamed *) fInput->FindObject("PROOF_OUTPUTFILE");
   if (out) fProofFile->SetOutputFileName(out->GetTitle());
   TDirectory *savedir = gDirectory;
   fFile = fProofFile->OpenFile("RECREATE");
   if (fFile && fFile->IsZombie()) SafeDelete(fFile);
   savedir->cd();

   // Cannot continue
   if (!fFile) {
      TString amsg = TString::Format("ProofSimpleFile::SlaveBegin: could not create '%s':"
                                     " instance is invalid!", fProofFile->GetName());
      Abort(amsg, kAbortProcess);
      return;
   }

   // Histos arrays
   if (CreateHistoArrays() != 0) {
      Abort("ProofSimpleFile::SlaveBegin: could not create histograms", kAbortProcess);
      return;
   }

   // Create directory
   if (!(fFileDir = fFile->mkdir("blue"))) {
      Abort("ProofSimpleFile::SlaveBegin: could not create directory 'blue' in file!",
            kAbortProcess);
      return;
   }

   // Create the histograms
   for (Int_t i=0; i < fNhist; i++) {
      fHistTop[i] = new TH1F(Form("ht%d",i), Form("ht%d",i), 100, -3., 3.);
      fHistTop[i]->SetFillColor(kRed);
      fHistTop[i]->SetDirectory(fFile);
      fHistDir[i] = new TH1F(Form("hd%d",i), Form("hd%d",i), 100, -3., 3.);
      fHistDir[i]->SetFillColor(kBlue);
      fHistDir[i]->SetDirectory(fFileDir);
   }

   // Set random seed
   fRandom = new TRandom3(0);
}
void plotxsec_CommonBins(seq_t seq/*=ACC_CORR*/, bool sim/*=kFALSE*/, int Q2Wbin/*=0*/){
  if (setup("vm")==kFALSE) return;

  //! Stats. Box option for this function
  if (Q2Wbin>0) gStyle->SetOptStat("nemMrRi");
  else          gStyle->SetOptStat(0);
  
  //!sim or data
  TFile* fy[5];
  if (sim) memcpy(fy,_fysim,sizeof(_fysim));
  else     memcpy(fy,_fyexp,sizeof(_fyexp));
 
  //!data objects for 5D yields for each Top
  THnSparse* hY5D[nTOP];

  //![Q2,W] binning information
  TString wbng   = _q2w_bng.Tokenize("__")->At(1)->GetName();
  TString nwbins = wbng.Tokenize("-")->At(0)->GetName();
  TString wmin   = wbng.Tokenize("-")->At(1)->GetName();
  TString wmax   = wbng.Tokenize("-")->At(2)->GetName();

  //! Some constants needed to define good variable names
  //! Yield(all-bins)= Yield(com-bins) + Yield(noncom-bins)
  const int kNumBinGrps = 3;
  enum BinGrps {kAll=0,kCom=1,kNonCom=2};
  TString bingrp_name[kNumBinGrps] ={"all_bins","com_bins","noncom_bins"};
  TString bingrp_title[kNumBinGrps]={"All Bins", "Common Bins", "NonCommon Bins"};

  //! Per Q2W bin: Data Objects for Yield vs W for each Top and each BinGrp therein
  TH1F* hYvW[nTOP][kNumBinGrps];
  
  TLegend* leg[kNumBinGrps];
  for (int ibingrp=0;ibingrp<kNumBinGrps;ibingrp++){
      leg[ibingrp] = new TLegend(0.1,0.7,0.5,0.9);
      leg[ibingrp]->SetHeader(TString::Format("%s Yield(%s)", seqTitle[seq].Data(), bingrp_title[ibingrp].Data()));
  }

  for(int iTop=0;iTop<nTOP;iTop++){
    for (int ibingrp=0;ibingrp<kNumBinGrps;ibingrp++){
      //TString hname = TString::Format("hYvW_%d_%s",iTop+1,bingrp_name[ibingrp].Data());
      //TString hname = TString::Format("hYvW_%s",bingrp_name[ibingrp].Data());
      TString hname = TString::Format("hYvW");
      TString htitle = hname;
      hYvW[iTop][ibingrp] = new TH1F(hname,htitle, nwbins.Atoi(), wmin.Atof(), wmax.Atof());
      hYvW[iTop][ibingrp]->SetXTitle("W[GeV]");
      hYvW[iTop][ibingrp]->SetMarkerStyle(20+iTop); //+5
      hYvW[iTop][ibingrp]->SetMarkerColor(2+iTop);
      leg[ibingrp]->AddEntry( hYvW[iTop][ibingrp], TString::Format("%s", _topNames[iTop].Data()) );
    }
  }
  
 
  //!Loop over Q2W dirs, get h5Ds and their yields only common bins!
  TIter nextkey(fy[0]->GetListOfKeys());
  TKey *key;
  int counterQ2Wbin=0;
  bool draw=kFALSE;
  if (Q2Wbin>0) draw=kTRUE;

  while (key = (TKey*)nextkey()) {
    TString Q2Wdirname = key->GetName();
    if(Q2Wdirname.EqualTo("hYW_Dir") || Q2Wdirname.EqualTo("hYW"))continue;
    printf("Processing %s\n", Q2Wdirname.Data());
    counterQ2Wbin+=1;
    
    //!if Q2Wbin option > 0, then process only the specified Q2Wbin
    if (Q2Wbin>0 && (counterQ2Wbin != Q2Wbin)) continue; 

    TString wrange = Q2Wdirname.Tokenize("_")->At(1)->GetName();
    TString wlow = wrange.Tokenize(",")->At(0)->GetName();
    wlow.Remove(0,1); //remove "["
    double w = wlow.Atof();
      
    char hname[200];                 
    sprintf(hname, "%s/hY5D/Varset1/hY5D_%s", Q2Wdirname.Data(), seqTitle[seq].Data());
    for(int iTop=0;iTop<nTOP;iTop++){
      hY5D[iTop] = (THnSparse*)fy[iTop]->Get(hname);
    }

    //! Reset Data structures 
    float    intg_hY5D[nTOP][kNumBinGrps] = {0.0};
    float intgErr_hY5D[nTOP][kNumBinGrps] = {0.0};
    
    myTHnTool hntool(kFALSE);

    //!F1. Get integral over all bins
    //printf("Integral over all bins\n");
    for(int iTop=0;iTop<nTOP;iTop++){
      if (iTop==2 || iTop==3) continue; //not doing for now
      hntool.GetIntegral(hY5D[iTop], intg_hY5D[iTop][kAll], intgErr_hY5D[iTop][kAll]);
      //printf("Top%d = %f\n",iTop+1,intg_hY5D[iTop][kAll]);
    }

    //!2. Get integral over only common-bins
    //NOTE, in hntool.GetIntegralCommonBins(), currently, hY5D[2] & hY5D[3] are not considered
    int num_combins = hntool.GetIntegralCommonBins(
                  hY5D[0],              hY5D[1],              hY5D[2],              hY5D[3],
             intg_hY5D[0][kCom],   intg_hY5D[1][kCom],   intg_hY5D[2][kCom],   intg_hY5D[3][kCom],
          intgErr_hY5D[0][kCom],intgErr_hY5D[1][kCom],intgErr_hY5D[2][kCom],intgErr_hY5D[3][kCom],
          draw);
    printf("Number of common bins for q2w bin %s = %d\n", Q2Wdirname.Data(), num_combins);
    
    //!2. Get integral over non-common-bins
    for(int iTop=0;iTop<nTOP;iTop++){
      if (iTop==2 || iTop==3) continue; //not doing for now
      intg_hY5D[iTop][kNonCom] = intg_hY5D[iTop][kAll] - intg_hY5D[iTop][kCom];
      intgErr_hY5D[iTop][kNonCom] = TMath::Sqrt(TMath::Power(intgErr_hY5D[iTop][kAll],2)+
                                                TMath::Power(intgErr_hY5D[iTop][kCom],2));
    }

    //! Now fill Histogram Objects
    for(int iTop=0;iTop<nTOP;iTop++){
      if (iTop==2 || iTop==3) continue; //not doing for now
      for (int ibingrp=0; ibingrp<kNumBinGrps;ibingrp++){
        hYvW[iTop][ibingrp]->SetBinContent(hYvW[iTop][ibingrp]->FindBin(w+.005), intg_hY5D[iTop][ibingrp]); //+5Mev = _instrinsic.Wbinw
        hYvW[iTop][ibingrp]->  SetBinError(hYvW[iTop][ibingrp]->FindBin(w+.005), intgErr_hY5D[iTop][ibingrp]); //+5Mev = _instrinsic.Wbinw
      }
    }
  }

  //!Now Draw the Histogram Objects
  TString cname = TString::Format("%s Yield Analysis", seqTitle[seq].Data());
  TCanvas* cy = new TCanvas(cname, cname);
  cy->Divide(kNumBinGrps,1);
  for(int iTop=0;iTop<nTOP;iTop++){
    if (iTop==2 || iTop==3) continue; //not doing for now
    for (int ibingrp=0; ibingrp<kNumBinGrps;ibingrp++){
      cy->cd(ibingrp+1);
      if (iTop==0) {
        if (seq==HOLE) {
          gPad->SetLogy();
          hYvW[iTop][ibingrp]->SetMinimum(.0001);
        }else{
          hYvW[iTop][ibingrp]->SetMinimum(0);
          //set max of histograms as per [Top=2][kAll]
          float max_t1 = hYvW[0][kAll]->GetBinContent(hYvW[0][kAll]->GetMaximumBin()) + 100;
          float max_t2 = hYvW[1][kAll]->GetBinContent(hYvW[1][kAll]->GetMaximumBin()) + 100;
          if (max_t2>max_t1) hYvW[iTop][ibingrp]->SetMaximum(max_t2);
          //printf("max_t2 = %f\n",max_t2);
        }
        hYvW[iTop][ibingrp]->Draw("p");
      }else {
        hYvW[iTop][ibingrp]->Draw("p sames");
      }
    }
  }
  //!Finally draw the Legend
  for (int ibingrp=0; ibingrp<kNumBinGrps;ibingrp++){
    cy->cd(ibingrp+1);
    leg[ibingrp]->Draw("same");
  }
}