//-------------------------------------------------------------------------------------------------- void catalogFile(const char *dir, const char *file) { TString fileName = TString(dir) + slash + + TString(file); //printf("Index: %d\n",fileName.Index("castor/cern.ch")); if (fileName.Index("castor/cern.ch") != -1) fileName = TString("castor:") + fileName; if (fileName.Index("pnfs/cmsaf.mit.edu") != -1) { fileName = dCacheDoor + fileName; } if (fileName.Index("mnt/hadoop/cms/store") != -1) { fileName.Remove(0,15); fileName = hadoopDoor + fileName; } printf("\n Opening: %s\n\n",fileName.Data()); TFile* f = TFile::Open(fileName.Data()); TTree* tree = (TTree*) f->FindObjectAny("Delphes"); if (tree) { printf("0000 %s %d %d\n",fileName.Data(),tree->GetEntries(),tree->GetEntries()); return; } TTree* tree = (TTree*) f->FindObjectAny("Events"); if (tree) printf("XX-CATALOG-XX %s %d\n",fileName.Data(),tree->GetEntries()); TTree* allTree = (TTree*) f->FindObjectAny("AllEvents"); if (tree && allTree) printf("XX-CATALOG-XX %s %d %d\n",fileName.Data(),tree->GetEntries(),allTree->GetEntries()); }
void KV_CCIN2P3_GE::GetBatchSystemParameterList(KVNameValueList& nl) { // Fill the list with all relevant parameters for batch system, // set to their default values. // // Parameters defined here are: // JobTime [string] // JobMemory [string] // JobDisk [string] // MultiJobsMode [bool] // RunsPerJob [int] // EMailOnStart [bool] // EMailOnEnd [bool] // EMailAddress [string] KVBatchSystem::GetBatchSystemParameterList(nl); nl.SetValue("JobTime", fDefJobTime); nl.SetValue("JobMemory", fDefJobMem); nl.SetValue("JobDisk", fDefJobDisk); nl.SetValue("MultiJobsMode", MultiJobsMode()); nl.SetValue("RunsPerJob", fRunsPerJob); nl.SetValue("EMailOnStart", kFALSE); nl.SetValue("EMailOnEnd", kFALSE); TString email = gSystem->GetFromPipe("email"); if (email.Index('=') > -1) { email.Remove(0, email.Index('=') + 2); nl.SetValue("EMailAddress", email); } else nl.SetValue("EMailAddress", ""); }
/** * Get the job url. * * @param name Production name * @param mc Should be true for MC * @param url On return, the job url * * @return true on success */ Bool_t GetJobUrl(const TString& name, Bool_t mc, TString& url) { url = ""; TString index("raw.jsp"); if (!Download((mc ? "job_details.jsp" : "production/raw.jsp"), index)) return false; std::ifstream in(index.Data()); TString line; TString tgt(Form("<td class=\"table_row\">%s</td>", name.Data())); do { line.ReadLine(in); if (!line.Contains(tgt)) continue; line.ReadLine(in); Int_t first = line.Index("href=\""); Int_t last = line.Index("\"", first+7); url = line(first+6,last-first-6); break; } while (!in.eof()); in.close(); if (url.IsNull()) { Error("GetJobUrl", "Production %s not found", name.Data()); return false; } return true; }
//-------------------------------------------------------------------------------------------------- void catalogFile(const char *dir, const char *file) { // set up the modules gMod->SetMetaDataString((TString(dir)+slash+TString(file)).Data()); gMod->SetNFileSet(0); // set up analysis //hMod->Add(gMod); //gAna->SetSuperModule(hMod); gAna->SetSuperModule(gMod); TString fileName = TString(dir) + slash + + TString(file); //printf("Index: %d\n",fileName.Index("castor/cern.ch")); if (fileName.Index("castor/cern.ch") != -1) fileName = TString("castor:") + fileName; if (fileName.Index("mnt/hadoop/cms/store") != -1) { fileName.Remove(0,15); fileName = hadoopDoor + fileName; gMod->SetMetaDataString(fileName.Data()); } printf(" Adding: %s\n",fileName.Data()); gAna->AddFile(fileName); gAna->SetUseHLT(0); gAna->SetCacheSize(64*1024*1024); // run the analysis after successful initialisation gAna->Run(false); }
vector <TString> OnlineConfig::SplitString(TString instring,TString delim) { // Utility to split up a string on the deliminator. // returns a vector of strings. vector <TString> v; TString remainingString = instring; TString tempstring = instring; int i; while (remainingString.Index(delim) != -1) { i = remainingString.Index(delim); tempstring.Remove(i); v.push_back(tempstring); remainingString.Remove(0,i+1); while(remainingString.Index(delim) == 0) { remainingString.Remove(0,1); } tempstring = remainingString; } while(tempstring.EndsWith(delim)) { tempstring.Chop(); } if(!tempstring.IsNull()) v.push_back(tempstring); return v; }
//_____________________________________________________________________________ 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; } }
// Helper functions to set argument inline TString parseArg(const TString& input, TString arg, const TString dfval="") { if (!arg.EndsWith("=")) arg += "="; if (input.Contains(arg)) { int sidx = input.Index(arg) + arg.Sizeof() - 1; int eidx = input.Index(",", sidx); if (eidx < 0) eidx = input.Sizeof(); return input(sidx, eidx-sidx); } else { return dfval; } }
void MakeCutLog(const char *inputRootFile = "AnalysisResults",const char *path = "./", const char* outputDir="./Output/"){ fstream outputFile(Form("%sCutSelection.log",outputDir),ios::out); if(!outputFile.is_open()){ cout<<"Problem opening file"<<endl; return; } // Char_t filename_input1[200] = (Form("%s%s",path,input1)); TString filename = Form("%s%s.root",path,inputRootFile); TFile f(filename.Data()); TList *directories = f.GetListOfKeys(); // get the list of directories in the file for(Int_t entFile=0;entFile<directories->GetEntries();entFile++){ TObject * o = f.Get(directories->At(entFile)->GetName()); // get the object in the base directory if(TString(o->IsA()->GetName())=="TDirectoryFile"){ // means that this is a directory (PWGGA......) TDirectory *pwg4dir =(TDirectory*)o; TString baseDirName = pwg4dir->GetName(); TString reconstructionFlagString = ""; // this is for new scheme where also the flags are coded in numbers in the PWGGA.... name if(baseDirName.Length()>31){ reconstructionFlagString = baseDirName(baseDirName.Index("GammaConversion_")+16,8); } TList *pwg4list = pwg4dir->GetListOfKeys(); // list of the yeys inside the base directory for(Int_t entHist=0;entHist<pwg4list->GetEntries();entHist++){ TString name = pwg4list->At(entHist)->GetName(); if(name.Contains("container")==0){ // does not try to read the container (get errors if tried) TObject * oHist = pwg4dir->Get(pwg4list->At(entHist)->GetName()); // get the object if(TString(oHist->IsA()->GetName())=="TList"){ // check if the object is a TList TString listname = oHist->GetName(); cout<<"Reading: "<<listname.Data()<<endl; TString cutString = listname(listname.Index("_")+1,listname.Length()) + "\n";// get the Cut string from the name outputFile << cutString.Data(); } } } } } outputFile.close(); }
TString nPart(Int_t part,TString string) { if (part <= 0) return ""; for (int i = 1; i < part; i++) //part-1 times { if (string.Index(";") < 0) return ""; string.Replace(0,string.Index(";")+1,"",0); } if (string.Index(";") >= 0) string.Remove(string.Index(";")); return string; }
/// /// Compute the file name of the parameter file defining the Asimov /// point where the Asimov toy is generated at. /// The combiner name will be followed by the Asimov addition (getAsimovCombinerNameAddition()), /// but without the number denoting the Asimov point in the file, as the file contains all points. /// Format of returned filename: /// /// plots/par/basename_combinernameAsimov[_+N][_-N]_var1[_var2]_genpoints.dat /// /// \param c - Combiner object /// \return - filename /// TString FileNameBuilder::getFileNameAsimovPar(const Combiner *c) { TString name = "plots/par/"; name += getFileBaseName(c); // remove any string after the "Asimov" token and the first "_" after that // e.g.: "combinerAsimov3_" -> "combinerAsimov_" int startOfToken = name.Index(m_asimov); int startOfFirstUnderscore = name.Index("_",startOfToken); int length = startOfFirstUnderscore-(startOfToken+m_asimov.Sizeof())+1; name.Replace(startOfToken+m_asimov.Sizeof()-1, length, ""); name += "_genpoints.dat"; return name; }
//_____________________________________________________________________________ Int_t THaDebugModule::THaDebugModule::ParseList() { // Parse the list of variable/cut names and store pointers // to the found objects. Called from Process() the first time // this module is used. Int_t nopt = fVarString.GetNOptions(); if( nopt > 0 ) { for( Int_t i=0; i<nopt; i++ ) { const char* opt = fVarString.GetOption(i); if( !strcmp(opt,"NOSTOP") ) fFlags &= ~kStop; else { // Regexp matching bool found = false; TRegexp re( opt, kTRUE); TObject* obj; // We can inspect analysis variables and cuts/tests if( gHaVars ) { TIter next( gHaVars ); while( (obj = next()) ) { TString s = obj->GetName(); if( s.Index(re) != kNPOS ) { found = true; fVars.push_back(obj); } } } if( gHaCuts ) { const TList* lst = gHaCuts->GetCutList(); if( lst ) { TIter next( lst ); while( (obj = next()) ) { TString s = obj->GetName(); if( s.Index(re) != kNPOS ) { found = true; fVars.push_back(obj); } } } } if( !found ) { Warning( Here("ParseList"), "Global variable or cut %s not found. Skipped.", opt ); } } } } return 0; }
/** * Get the pass from the path * * @param dir Directory * @param run Run number * @param path On return, the path * @param pass On return, the pass * * @return true on success */ Bool_t GetPathPass(const TString& dir, ULong_t run, TString& path, TString& pass) { Int_t first = dir.Index(Form("%lu", run)); Int_t last = dir.Index("/", first); if (last == kNPOS) last = dir.Length(); if (first == kNPOS) { Error("GetPathPass", "Run number %lu not in path %s", run, dir.Data()); return false; } while (dir[first-1] == '0') first--; path = dir(0, first); pass = dir(last+1,dir.Length()-last-1); return true; }
/// /// Scale the error of a given observable. /// Both stat and syst errors are being scaled by the same factor. /// In order to become effective, the PDF needs to be rebuild by /// calling buildCov() and buildPdf(). /// /// \param obsname - observable name. It may or may not include a unique ID string, both works. /// \param scale - the scale factor the current error is being multiplied with /// \return - true if successful /// bool PDF_Abs::ScaleError(TString obsname, float scale) { // remove unique ID if necessary TString UID = "UID"; if ( obsname.Contains(UID) ){ obsname.Replace(obsname.Index(UID), obsname.Length(), ""); // delete the unique ID. That should leave just the observable name. } // find the index of the observable - if it exists at all! if ( !hasObservable(obsname) ){ cout << "PDF_Abs::ScaleError() : ERROR : observable '" << obsname << "' not found." << endl; return false; } int index = -1; for ( int i=0; i<getNobs(); i++ ){ if ( observables->at(i)->GetName()==obsname ){ index = i; break; } } if ( index==-1 ){ // this should never happen... cout << "PDF_Abs::ScaleError() : ERROR : internal self inconsistency discovered. Exit." << endl; assert(0); } // scale error StatErr[index] *= scale; SystErr[index] *= scale; // update error source string obsErrSource += " (PDF_Abs::ScaleError(): scaled error of " + obsname + ")"; return true; }
void Finish(TString sDir = "") { // Finishing Macro for running with Worker printf("Events: %d Events Accepted: %d\n", gAN->GetNEvent(), gAN->GetNEvAnalysed() ); printf("\nEnd-of-Run macro executing\n"); // If user has not specified output directory, pull from AR if(sDir.Length() == 0) sDir = gAR->GetTreeDir(); if(sDir.Length() == 0) sDir = "~/"; // Append "/" to Directory if unspecified if(!(sDir.EndsWith("/"))) sDir.Append("/"); // Create output filename from input file name TString sFile; if (gAR->IsOnline()) sFile = gAR->GetFileName(); else sFile = gAR->GetTreeFile()->GetName(); while(sFile.Contains("/")) sFile.Remove(0,1+sFile.Index("/")); sFile.ReplaceAll(".dat",".root"); sFile.Prepend("Hist_"); sFile.Prepend(sDir); // Save histograms to file and close it TFile f(sFile, "recreate"); f.SetCompressionLevel(4); gROOT->GetList()->Write(); f.Close(); cout << "All histograms saved to " << sFile << endl; gSystem->Exit(0); }
//_____________________________________________________________________________ Int_t THaOutput::BuildBlock(const string& blockn) { // From the block name, identify and save a specific grouping // of global variables by adding them to the fVarnames list. // // For efficiency, at the end of building the list we should // ensure that variables are listed only once. // // Eventually, we can have some specially named blocks, // but for now we simply will use pattern matching, such that // block L.* // would save all variables from the left spectrometer. TRegexp re(blockn.c_str(),kTRUE); TIter next(gHaVars); TObject *obj; Int_t nvars=0; while ((obj = next())) { TString s = obj->GetName(); if ( s.Index(re) != kNPOS ) { s.Append('\0'); string vn(s.Data()); fVarnames.push_back(vn); nvars++; } } return nvars; }
void ConnectFriends() { // Connect the friends tree as soon as available. // // Handle the friends first // if (!esdTree->FindBranch("ESDfriend.")) { // Try to add ESDfriend. branch as friend TString esdFriendTreeFName; esdFriendTreeFName = (esdTree->GetCurrentFile())->GetName(); TString basename = gSystem->BaseName(esdFriendTreeFName); Int_t index = basename.Index("#")+1; basename.Remove(index); basename += "AliESDfriends.root"; TString dirname = gSystem->DirName(esdFriendTreeFName); dirname += "/"; esdFriendTreeFName = dirname + basename; // TTree* cTree = esdTree->GetTree(); if (!cTree) cTree = esdTree; cTree->AddFriend("esdFriendTree", esdFriendTreeFName.Data()); cTree->SetBranchStatus("ESDfriend.", 1); esdFr = (AliESDfriend*)(esdEv->FindListObject("AliESDfriend")); if (esdFr) cTree->SetBranchAddress("ESDfriend.", &esdFr); } }
void onecut::parseCut(TString cut){ if(cut=="" || cut=="1"){ cutType_ = kAlwaysTrue; return; } if(cut.Contains("&") || cut.Contains("|") || cut.Contains("(") || cut.Contains(")")){ cout<<"Cut "<<cut<<" not fundamental. Exiting"<<endl; cutType_ = kAlwaysFalse; return; } vector<TString> cTypes_s({"!=", "==", "<=", ">=", "<", ">"}); vector<comparisonType> cTypes({kNotEqual, kEqual, kLessEqual, kGreaterEqual, kLess, kGreater}); TString var(cut), val(cut); int pos(-1); for(size_t ind(0); ind < cTypes.size(); ind++){ pos = cut.Index(cTypes_s[ind]); if(pos == -1) continue; var.Remove(pos, var.Length()); val.Remove(0, pos+cTypes_s[ind].Length()); assignBranch(var, val); compType_ = cTypes[ind]; break; } // Loop over comparison types if(pos == -1) assignBranch(var, val); // Assigning boolean branches }
void FinishBatch(TString sInput="", TString sOutput="ARHist"){ // Stuff to do at the end of an analysis run // Here all spectra are saved to disk printf("Events: %d Events Accepted: %d\n", gAN->GetNEvent(), gAN->GetNEvAnalysed() ); printf("End-of-Run macro executing\n"); TString sDir = gAR->GetTreeDir(); TString sFile; if (gAR->IsOnline()) sFile = gAR->GetFileName(); else sFile = gAR->GetTreeFile()->GetName(); while(sFile.Contains("/")) sFile.Remove(0,1+sFile.Index("/")); sFile.ReplaceAll(".dat",".root"); if(sInput.Length() && sFile.BeginsWith(sInput)) sFile.Remove(0,sInput.Length()); else sFile.Prepend("_"); sFile.Prepend(sOutput); sFile.Prepend(sDir); // Save histograms to file and close it TFile f(sFile, "recreate"); if( !f ){ printf("Open file %s for histogram save FAILED!!\n",sFile.Data()); return; } gROOT->GetList()->Write(); f.Close(); printf("All histograms saved to %s\n",sFile.Data()); if (!(gAR->IsOnline())) gSystem->Exit(0); }
/** * Get the size of a given run * * @param in Input stream * @param runNo Run number to search for * @param mc True for simulations * @param minSize Least size * * @return true on success */ Bool_t GetSize(std::istream& in, ULong_t runNo, Bool_t mc, ULong_t minSize=100000) { TString line; TString tgt2(mc ? "table_row_right" : "ESDs size"); Int_t cnt = 0; do { line.ReadLine(in); if (!line.Contains(tgt2)) continue; cnt++; if (mc && cnt < 3) continue; if (!mc) line.ReadLine(in); if (fDebug) Info("", line); TString ssiz; if (mc) { Int_t first = line.Index(">"); Int_t last = line.Index("<",first+1); if (first == kNPOS || last == kNPOS) { Error("GetDir", "Failed to get directory from %s", line.Data()); return false; } ssiz = line(first+1, last-first-1); } else { for (Int_t i = 0; i < line.Length(); i++) { if (line[i] == '<') break; if (line[i] == ' ' || line[i] == '\t' || line[i] == ',') continue; ssiz.Append(line[i]); } } Long_t size = ssiz.Atoll(); if (fDebug) Info("", "Got run %lu %lu" , runNo, size); if (size < 0) { Error("GetSize", "Failed to extract size for run %lu", runNo); return false; } if (ULong_t(size) < minSize) { Warning("GetSize","Run %lu does not have enough events %lu",runNo,size); return false; } break; } while (!in.eof()); return true; }
/** * Get list of runs associated with production * * @param url The production URL * @param mc True of MC * @param minSize Least size of runs to use * * @return true on success */ Bool_t GetRuns(const TString& url, Bool_t mc, ULong_t minSize) { TString index("job"); if (!Download(Form("%s%s", (mc ? "" : "raw/"), url.Data()), index)) return false; std::ifstream in(index.Data()); TString tgt1(mc ? "window.open" : "runDetails"); TString line = ""; do { line.ReadLine(in); if (!line.Contains(tgt1)) continue; Int_t first = -1; Int_t last = -1; if (!mc) { first = line.Index(tgt1); last = line.Index(")", first+tgt1.Length()+1); } else { Int_t tmp = line.Index(">"); first = line.Index(">", tmp+1); last = line.Index("<", first); } if (first == kNPOS || last == kNPOS) { Error("GetDir", "Failed to get directory from %s", line.Data()); return false; } first += (mc ? 1 : tgt1.Length()+1); last -= first; TString srun = line(first, last); ULong_t runNo = srun.Atoll(); if (fDebug) Info("", "Got run %lu (%s)", runNo, srun.Data()); if (!GetSize(in, runNo, mc, minSize)) continue; if (!GetDir(in, runNo, mc)) continue; if (!fRuns.IsNull()) fRuns.Append(","); fRuns.Append(Form("%lu", runNo)); } while (!in.eof()); in.close(); if (fRuns.IsNull()) return false; return true; }
/** * Get a directory * * @param in Input stream * @param runNo The run number * @param mc True for MC * * @return true on success */ Bool_t GetDir(std::istream& in, ULong_t runNo, Bool_t mc) { TString line; TString tgt3("/catalogue/index.jsp"); do { line.ReadLine(in); // Info("", "line=%s", line.Data()); if (!line.Contains(tgt3)) continue; if (fDebug) Info("", line); Int_t tmp = mc ? line.Index(">")+1 : 0; Int_t first = line.Index(">", tmp); Int_t last = line.Index("<",first+1); if (first == kNPOS || last == kNPOS) { Error("GetDir", "Failed to get directory from %s", line.Data()); return false; } TString dir = line(first+1,last-first-1); if (fDebug) Info("", "Got run %lu %s", runNo, dir.Data()); TString path, pass; if (!GetPathPass(dir, runNo, path, pass)) return false; if (fDebug) Info("", "Got run %lu %s %s", runNo,path.Data(),pass.Data()); if (fPath.IsNull()) fPath = path; else if (!fPath.EqualTo(path)) { Warning("GetDir", "Run %lu location %s not %s", runNo, path.Data(), fPath.Data()); return false; } if (fPass.IsNull()) fPass = pass; else if (!fPass.EqualTo(pass)) { Warning("GetDir", "Run %lu pass %s not %s", runNo, pass.Data(), fPass.Data()); return false; } break; } while (!in.eof()); return true; }
//________________________________________________________ TObjArray GFOverlay::FindAllBetween(const TString &text, const char *startStr, const char *endStr) const { TObjArray result; // TObjStrings... if (text.Contains(startStr, TString::kIgnoreCase)) { Ssiz_t start = text.Index(startStr); while (start != kNPOS && start < text.Length()) { TString name = this->FindNextBetween(text, start, startStr, endStr); if (!name.IsNull()) { result.Add(new TObjString(name)); start = text.Index(startStr, start + name.Length() + TString(endStr).Length()); } else { break; } } } return result; }
void bcut::parseCuts(TString cuts){ vcuts_.clear(); // Starting the parsing every time cuts.ReplaceAll(" ", ""); TString cut; int pos; do{ pos = cuts.Index("&&"); cut = cuts; if(pos != -1) cut.Remove(pos, cut.Length()); vcuts_.push_back(onecut(cut)); cuts.Remove(0, pos+2); } while(pos != -1); }
int doRebin(TString fname) { TFile file(fname,"read"); if (!file.IsOpen()) { std::cout << "failed to open the file <" << fname << ">\n"; return 0; } TH1D *h1=(TH1D*)file.Get("xsec"); h1->SetDirectory(0); file.Close(); h1->SetName("xsec_inp"); int lastMassBin=(fname.Index("200to1500")>0) ? 1:0; if (lastMassBin) std::cout << "lastMassBin determined\n"; TString htitle=fname; htitle.ReplaceAll(".root",""); int nYbins=(lastMassBin) ? 12 : 24; TH1D *hout=new TH1D("xsec",htitle,nYbins,0.,2.4); hout->SetDirectory(0); hout->GetXaxis()->SetTitle( h1->GetXaxis()->GetTitle() ); hout->GetXaxis()->SetNdivisions( h1->GetXaxis()->GetNdivisions() ); hout->GetYaxis()->SetTitle( h1->GetYaxis()->GetTitle() ); if (!lastMassBin) { double factor=20.; // 2/0.1 for (int ibin=1; ibin<=h1->GetNbinsX(); ++ibin) { hout->SetBinContent(ibin, factor * h1->GetBinContent(ibin)); hout->SetBinError (ibin, factor * h1->GetBinError(ibin)); } } else { double factor=10.; // 2/0.2 for (int ibin=1; ibin<=hout->GetNbinsX(); ++ibin) { double v1=h1->GetBinContent(2*ibin-1); double v2=h1->GetBinContent(2*ibin ); double e1=h1->GetBinError (2*ibin-1); double e2=h1->GetBinError (2*ibin ); hout->SetBinContent(ibin, factor * (v1+v2) ); hout->SetBinError (ibin, factor * sqrt(e1*e1+e2*e2)); } } TString foutName=fname; foutName.ReplaceAll(".root","-mdf.root"); TFile fout(foutName,"recreate"); hout->Write(); fout.Close(); std::cout << "file <" << fout.GetName() << "> created\n"; return 1; }
//_____________________________________________________________________________ THaCut::EvalMode THaCut::ParsePrefix( TString& expr ) { // Parse the given expression for a mode prefix (e.g. "OR:") // and return its value. If the expression does not have a mode prefix, // return the default kAND (=0). // The expression is expected to have all whitespace removed. // If the prefix was found, it is stripped from the expression. // If a mode prefix seems to be present, but is not found in // the defined modes, return kModeErr. const EvalMode kDefaultMode = kOR; const char* const here = "THaCut"; struct ModeDef_t { const char* prefix; EvalMode mode; }; const ModeDef_t mode_defs[] = { { "OR", kOR }, { "ANY", kOR }, { "AND", kAND }, { "ALL", kAND }, { "XOR", kXOR }, { "ONE", kXOR }, { "ONEOF", kXOR }, { 0, kModeErr } }; Ssiz_t colon = expr.Index(":"); if( colon == kNPOS ) return kDefaultMode; const ModeDef_t* def = mode_defs; while( def->prefix ) { if( expr.BeginsWith(def->prefix) && static_cast<Ssiz_t>(strlen(def->prefix)) == colon ) { expr.Remove(0,colon+1); break; } ++def; } EvalMode mode = def->mode; if( mode == kModeErr ) { TString prefix = expr(0,colon); Error(here, "Unknown prefix %s", prefix.Data() ); } else if( expr.Length() == 0 ) { Error(here, "expression may not be empty"); mode = kModeErr; } if( mode == kModeErr ) SetBit(kError); return mode; }
void bcut::parseWeights(TString weights){ weights.ReplaceAll(" ", ""); cutTypes_.clear(); fWeights_.clear(); fvWeights_.clear(); indWeights_.clear(); TString wgt; int pos; do{ pos = weights.Index("*"); wgt = weights; if(pos != -1) wgt.Remove(pos, wgt.Length()); parseWeight(wgt); weights.Remove(0, pos+1); } while(pos != -1); }
void bcut::parseWeight(TString wgt){ cutTypes_.push_back(kFloat); fWeights_.push_back(NULL); fvWeights_.push_back(NULL); indWeights_.push_back(-1); constWeights_.push_back(1.); if(wgt=="weight") fWeights_.back() = &baby_base::weight; else if(wgt=="w_lumi") fWeights_.back() = &baby_base::w_lumi; else if(wgt=="w_pu") fWeights_.back() = &baby_base::w_pu; else if(wgt=="w_lep") fWeights_.back() = &baby_base::w_lep; else if(wgt=="w_fs_lep") fWeights_.back() = &baby_base::w_fs_lep; else if(wgt=="w_toppt") fWeights_.back() = &baby_base::w_toppt; else if(wgt=="w_btag") fWeights_.back() = &baby_base::w_btag; else if(wgt=="eff_trig") fWeights_.back() = &baby_base::eff_trig; else if(wgt.Contains("[")){ // if weight is a vector element TString index_s(wgt); wgt.Remove(wgt.Index("["), wgt.Length()); index_s.Remove(0, index_s.Index("[")+1); index_s.Remove(index_s.Index("]"), index_s.Length()); indWeights_.back() = index_s.Atoi(); cutTypes_.back() = kvFloat; if(wgt=="w_pdf") fvWeights_.back() = &baby_base::w_pdf; else if(wgt=="sys_pdf") fvWeights_.back() = &baby_base::sys_pdf; else if(wgt=="sys_isr") fvWeights_.back() = &baby_base::sys_isr; else if(wgt=="sys_mur") fvWeights_.back() = &baby_base::sys_mur; else if(wgt=="sys_muf") fvWeights_.back() = &baby_base::sys_muf; else if(wgt=="sys_murf") fvWeights_.back() = &baby_base::sys_murf; else if(wgt=="sys_trig") fvWeights_.back() = &baby_base::sys_trig; else if(wgt=="sys_lep") fvWeights_.back() = &baby_base::sys_lep; else if(wgt=="sys_fs_lep") fvWeights_.back() = &baby_base::sys_fs_lep; else if(wgt=="sys_bctag") fvWeights_.back() = &baby_base::sys_bctag; else if(wgt=="sys_fs_bctag") fvWeights_.back() = &baby_base::sys_fs_bctag; else if(wgt=="sys_udsgtag") fvWeights_.back() = &baby_base::sys_udsgtag; else if(wgt=="sys_fs_udsgtag") fvWeights_.back() = &baby_base::sys_fs_udsgtag; else { cout<<"Weight \""<<wgt<<" not defined. Add it to bcut::parseWeight in bcut.cpp"<<endl; exit(0); } }else if(wgt.Atof()>0) { constWeights_.back() = wgt.Atof(); cutTypes_.back() = kConst; } else { cout<<"Weight \""<<wgt<<" not defined. Add it to bcut::parseWeight in bcut.cpp"<<endl; exit(0); } }
TString effDataKindString(const TString str) { TString effKind="xx", dataKind="xx"; if (str.Index("RECO")!=-1) effKind="RECO"; else if (str.Index("ID")!=-1) effKind="ID"; else if (str.Index("HLTleg1")!=-1) effKind="HLTleg1"; else if (str.Index("HLTleg2")!=-1) effKind="HLTleg2"; else if (str.Index("HLT")!=-1) effKind="HLT"; if (str.Index("data")!=-1) dataKind="data"; else if (str.Index("mc")!=-1) dataKind="mc"; TString final=dataKind+TString(" ")+effKind; return final; }
Int_t KVRTGIDManager::WriteAsciiFile ( const Char_t * filename, const TCollection *selection, Bool_t update ) { // Write identification functions in file 'filename'. // If selection=0 (default), write all grids. // If update=true, call UpdateListFromIDGridManager() before writing // If selection!=0, write only grids in list. // Returns number of functions written in file. if( update ) UpdateListFromIDGridManager(); if( !fIDGlobalList ){ Warning("KVRTGIDManager::WriteAsciiFile","No listed identification functions to write"); return 0; } ofstream tgidfile ( filename ); if( !tgidfile.is_open() ){ Error("KVRTGIDManager::WriteAsciiFile","No write permission for file %s", filename); return 0; } const TCollection *list_tgid = ( selection ? selection : fIDGlobalList ); TIter next ( list_tgid ); KVTGID *tgid = NULL; Int_t n_saved = 0; while ( ( tgid = (KVTGID *)next() ) ) { // Not write a KVTGID copy TString tmp = tgid->GetTitle(); if(tmp.Contains("COPY")){ tmp.Remove(0, tmp.Index("0x")); KVTGID *tmp_tgid = reinterpret_cast<KVTGID *>((Int_t)tmp.Atof()); Warning("KVRTGIDManager::WriteAsciiFile","The function %s (%s, %p) is not written because it is a copy of %s (%s, %p)" , tgid->GetName(), tgid->ClassName(), tgid , tmp_tgid->GetName(), tmp_tgid->ClassName(), tmp_tgid); continue; } tgid->WriteToAsciiFile ( tgidfile ); Info( "KVRTGIDManager::WriteAsciiFile", "%s (%s, %p) saved", tgid->GetName(), tgid->ClassName(), tgid ); n_saved++; } tgidfile.close(); return n_saved; }
void weightBkgMC(TString inputFileName,TString outputFileName,float weight,TString treeName="SusyHggTree") { float inw,outw; bool isSherpa = (inputFileName.Index("DiPhotonJetsBox_M60_8TeV-sherpa") != -1); int Nj; TFile inputFile(inputFileName); TTree* inputTree = (TTree*)inputFile.Get(treeName); TFile outputFile(outputFileName,"RECREATE"); TTree* outputTree = inputTree->CloneTree(0); inputTree->SetBranchAddress("pileupWeight",&inw); inputTree->SetBranchAddress("Njets",&Nj); outputTree->SetBranchAddress("pileupWeight",&outw); Long64_t iEntry=-1; if(isSherpa) { double wSum=0; double entries=0; while(inputTree->GetEntry(++iEntry)) { wSum+=getSherpaWeight(Nj); entries++; } weight = weight*entries/wSum; std::cout << "sherpa: sum of weights: " << wSum << " total entries: " << entries << std::endl; } iEntry=-1; while(inputTree->GetEntry(++iEntry)) { outw = inw*weight; if(isSherpa) outw*=getSherpaWeight(Nj); outputTree->Fill(); } outputFile.cd(); outputTree->Write(); outputFile.Close(); inputFile.Close(); }