void hsimpleReader() { // Create a histogram for the values we read. TH1F *myHist = new TH1F("h1","ntuple",100,-4,4); // Open the file containing the tree. TFile *myFile = TFile::Open("$ROOTSYS/tutorials/hsimple.root"); if (!myFile || myFile->IsZombie()) { gROOT->ProcessLine(".x $ROOTSYS/tutorials/hsimple.C"); myFile = TFile::Open("$ROOTSYS/tutorials/hsimple.root"); if (!myFile || myFile->IsZombie()) { return; } } // Create a TTreeReader for the tree, for instance by passing the // TTree's name and the TDirectory / TFile it is in. TTreeReader myReader("ntuple", myFile); // The branch "px" contains floats; access them as myPx. TTreeReaderValue<Float_t> myPx(myReader, "px"); // The branch "py" contains floats, too; access those as myPy. TTreeReaderValue<Float_t> myPy(myReader, "py"); // Loop over all entries of the TTree or TChain. while (myReader.Next()) { // Just access the data as if myPx and myPy were iterators (note the '*' // in front of them): myHist->Fill(*myPx + *myPy); } myHist->Draw(); }
void combineHistos(std::string type) { bool _dt = (type == "DATA"); bool _mc = !_dt; TDirectory *curdir = gDirectory; // Input file: normalized pT spectra TFile *fin = new TFile(Form("outputs/output-%s-2a.root", type.c_str()), "READ"); assert(fin && !fin->IsZombie()); // Top-level directory _top = gDirectory; // Output file: combined spectra TFile *fout = new TFile(Form("outputs/output-%s-2b.root", type.c_str()), "RECREATE"); assert(fout && !fout->IsZombie()); std::cout << "Calling combineHistos(" << type << ");" << std::endl; std::cout << "Input file " << fin->GetName() << std::endl; std::cout << "Output file " << fout->GetName() << std::endl; std::cout << "Starting recursions. These may take a few seconds" << std::endl; // Store pT ranges to a nice map for (int itrg = 0; itrg != _jp_ntrigger; ++itrg) { std::string name = _jp_triggers[itrg]; double lower = _jp_trigranges[itrg][0]; double upper = _jp_trigranges[itrg][1]; _ptranges[name] = pair<double, double>(lower, upper); } // Loop over all the directories recursively recurseFile(fin, fout, "hpt"); recurseFile(fin, fout, "hpt_pre"); if (_dt) recurseFile(fin, fout, "hlumi"); if (_mc) recurseFile(fin, fout, "hpt_g0tw"); curdir->cd(); std::cout << std::endl << "Output stored in " << fout->GetName() << std::endl; // Close files fout->Close(); fout->Delete(); std::cout << "Output file closed" << std::endl; fin->Close(); fin->Delete(); std::cout << "Input file closed" << std::endl; }
void normalizeHistos(string type) { assert(type==_jp_type); _nh_mc = (type=="MC" || type=="HW"); _nh_dt = (type=="DATA"); assert((_nh_mc || _nh_dt) && !(_nh_mc && _nh_dt)); TFile *fin = new TFile(Form("output-%s-1.root",type.c_str()),"READ"); assert(fin && !fin->IsZombie()); TFile *fout = new TFile(Form("output-%s-2a.root",type.c_str()),"RECREATE"); assert(fout && !fout->IsZombie()); if (_lumiscale!=1 && !_nh_mc) cout << "Attention! : Scaling luminosity to the new estimate" << " by multiplying with " << _lumiscale << endl; if (_jp_usetriglumi) { cout << "Reading trigger luminosity from settings.h" << endl; for (int i = 0; i != _jp_ntrigger; ++i) { double lumi = _jp_triglumi[i]/1e6; // /ub to /pb cout << Form(" *%s: %1.3f /pb", _jp_triggers[i].c_str(),lumi) << endl; triglumi[_jp_triggers[i]] = lumi; } } cout << "Calling normalizeHistos("<<type<<");" << endl; cout << "Input file " << fin->GetName() << endl; cout << "Output file " << fout->GetName() << endl; cout << "Starting recursive loop. This may take a minute" << endl << flush; // Loop over all the directories recursively recurseFile(fin, fout); cout << endl; cout << "Recursive loop done." << endl; cout << "Writing output to " << fout->GetName() << endl; cout << "This may again take a minute" << endl << flush; fout->Write(); cout << "Output written in " << fout->GetName() << endl; fout->Close(); cout << "Output file closed" << endl; fout->Delete(); cout << "Output file pointer deleted" << endl << flush; fin->Close(); fin->Delete(); } // normalizeHistos
void KVFAZIAReconDataAnalyser::ProcessRun() { // Perform treatment of a given run // Before processing each run, after opening the associated file, user's InitRun() method is called. // After each run, user's EndRun() is called. // For each event of each run, user's Analysis() method is called. // // For further customisation, the pre/post-methods are called just before and just after // each of these methods (preInitRun(), postAnalysis(), etc. etc.) TString fullPathToRunfile = gDataSet->GetFullPathToRunfile(fDataType.Data(), fRunNumber); TFile* f = (TFile*)gDataSet->OpenRunfile(fDataType.Data(), fRunNumber); if (!(f && !f->IsZombie())) { Error("ProcessRun", "file %s does not exist or is made zombie", fullPathToRunfile.Data()); return; } theTree = (TTree*)f->Get("ReconstructedEvents"); TFile* ffriend = 0; if (fLinkRawData) { fullPathToRunfile = gDataSet->GetFullPathToRunfile("raw", fRunNumber); ffriend = (TFile*)gDataSet->OpenRunfile("raw", fRunNumber); if (!(ffriend && !ffriend->IsZombie())) { Warning("ProcessRun", "file %s does not exist or is made zombie\n Reading of raw data is not possible", fullPathToRunfile.Data()); } else { theTree->AddFriend("FAZIA", ffriend); } } TString option(""); // Add any user-defined options if (GetUserClassOptions() != "") { if (option != "") option += ","; option += GetUserClassOptions(); } Info("SubmitTask", "Beginning TTree::Process... Option=%s", option.Data()); if (nbEventToRead) { theTree->Process(GetUserClass(), option.Data(), nbEventToRead); } else { theTree->Process(GetUserClass(), option.Data()); } if (ffriend && ffriend->IsOpen()) ffriend->Close(); f->Close(); }
void appendRootFile() { TFile* pRootFile = new TFile("myfile.root", "UPDATE"); if (pRootFile != NULL) { TDirectory* pTestDir = (TDirectory*)pRootFile->Get("TestDir"); if (pTestDir != NULL) { pTestDir->cd(); MyROOTObject* pMyObj = NULL; std::string name = "testobj"; pMyObj = (MyROOTObject*)pTestDir->Get(name.c_str()); if (pMyObj != NULL) { std::cout << *pMyObj << std::endl; delete pMyObj; } name = "newobj"; MyROOTObject* pNewObj = NULL; pNewObj = new MyROOTObject(42, 5.9e2, name); if (pNewObj != NULL) { std::cout << *pMyObj << std::endl; pNewObj->Write(pNewObj->GetName()); delete pNewObj; } } if (pRootFile->IsOpen() && !pRootFile->IsZombie()) { pRootFile->Close(); delete pRootFile; } } }
TFile *openRootFile(const std::string& rootfn, const std::string& option="") { TFile *rootfile = NULL; // Now check to see if this file has already been opened... map<string,TFile*>::const_iterator it = glmap_id2rootfile.find(rootfn); if( it != glmap_id2rootfile.end() ) { rootfile = it->second; if (!rootfile->IsOpen()) rootfile->Open(rootfn.c_str(),option.c_str()); else rootfile->cd(); } else { if (strstr(rootfn.c_str(),"dcache") || strstr(rootfn.c_str(),"dcap") ) { rootfile = new TDCacheFile(rootfn.c_str(),option.c_str()); } else rootfile = new TFile(rootfn.c_str(),option.c_str()); if( rootfile->IsZombie() ) { cerr << "File failed to open, " << rootfn << endl; rootfile = NULL; } else { glmap_id2rootfile.insert(pair<string,TFile*>(rootfn,rootfile)); } } return rootfile; }
void overwriteRootFile() { TFile* pRootFile = new TFile("myfile.root", "UPDATE"); if (pRootFile != NULL) { TDirectory* pTestDir = (TDirectory*)pRootFile->Get("TestDir"); if (pTestDir != NULL) { pTestDir->cd(); pTestDir->Delete("testobj;*"); std::string name = "testobj"; MyROOTObject* pNewObj = NULL; int ival = rand() % 100 + 1; double dval = (double)(rand() % 1000 + 1)/1000.0; pNewObj = new MyROOTObject(ival, dval, name); if (pNewObj != NULL) { std::cout << *pNewObj << std::endl; pNewObj->Write(pNewObj->GetName(), TObject::kOverwrite); delete pNewObj; } } if (pRootFile->IsOpen() && !pRootFile->IsZombie()) { pRootFile->Close(); delete pRootFile; } } }
double singlePointLimit(std::string filename, float tanb, unsigned int LIMIT_TYPE, unsigned int verbosity=0) { /* Get the observed, expected and +/-1 ans +/-2 sigma band from limit trees, which are the output of combine */ TString fullpath; fullpath = TString::Format(filename.c_str(), tanb); TFile* file = new TFile(fullpath); if(file->IsZombie()){ if( verbosity>0 ){ std::cout << "> File not found: " << fullpath << std::endl; } return -999.; } TTree* tree = (TTree*) file->Get("limit"); if(!tree){ if( verbosity>0 ){ std::cout << "> Tree not found in file: " << fullpath << std::endl; } return -999.; } int nevent = tree->GetEntries(); if( nevent<=0 ){ if( verbosity>0 ){ std::cout << "> Tree is empty" << std::endl; } return -999.; } float type; double value; tree->SetBranchAddress("quantileExpected", &type ); tree->SetBranchAddress("limit" , &value); float target = LimitTypes[LIMIT_TYPE]; double limit = -999; for(int idx=0; idx<nevent; ++idx){ tree->GetEvent(idx); if( fabs(type-target)<0.001 ){ // allow for some tolerance for determination of type if( verbosity>1 ){ std::cout << "tanb: " << tanb << " limit (" << limitType(LIMIT_TYPE) << ") = " << value/tanb << " Undivided limit = " << value << std::endl; } limit = value/tanb; } } file->Close(); return limit; }
int createRootFile() { TFile* pRootFile = new TFile("myfile.root", "RECREATE"); if (pRootFile == NULL) { std::cout << "Error creating ROOT file" << std::endl; return 1; } TDirectory* pTestDir = pRootFile->mkdir("TestDir"); if (pTestDir == NULL) { std::cout << "Error creating directory in ROOT file" << std::endl; delete pRootFile; return 1; } std::string name = "testobj"; MyROOTObject* pMyObj = new MyROOTObject(17, 1.2e3, name); std::cout << *pMyObj << std::endl; pTestDir->cd(); pMyObj->Write(pMyObj->GetName()); if (pMyObj != NULL) { delete pMyObj; } if (pRootFile != NULL) { if (pRootFile->IsOpen() && !pRootFile->IsZombie()) { pRootFile->Close(); delete pRootFile; } } }
void macro() { cout << "Example macro for testing the ROOTobject library from CINT" << endl; TFile* pRootFile = new TFile("myfile.root", "READ"); if (pRootFile != NULL) { TDirectory* pTestDir = (TDirectory*)pRootFile->Get("TestDir"); if (pTestDir != NULL) { pTestDir->cd(); MyROOTObject* pMyObj = NULL; std::string name = "testobj"; pMyObj = (MyROOTObject*)pTestDir->Get(name.c_str()); if (pMyObj != NULL) { std::cout << *pMyObj << std::endl; } } if (pRootFile->IsOpen() && !pRootFile->IsZombie()) { pRootFile->Close(); delete pRootFile; } } }
void mjjshapes() { SigData_t m_sigdata; std::map<TString,TGraph *> m_backgrounds; getItAll(m_sigdata,m_backgrounds); makeGaussianSignals(m_sigdata); std::map<TString,std::vector<TH1D *> >::iterator it; for (it = m_sigdata.begin(); it != m_sigdata.end(); it++) { TString sigmodel = it->first; TString outfname = "mjj-histo-shapes-"+sigmodel+".root"; TFile *allHistFile = new TFile(outfname.Data(), "RECREATE"); if (allHistFile->IsZombie()) { cerr << "Couldn't open output file " << outfname << endl; exit(-1); } writeSignalHistosForModel (it->second,sigmodel,allHistFile); writeDataBackgroundHistosForModel (m_backgrounds, it->second, // for channel binning allHistFile); allHistFile->Close(); delete allHistFile; } }
//__________________________________________________________________________ Bool_t BuildUniformField(const TGeoHMatrix& matrix) { // Create a Uniform Magnetic field and write it to file cout << "Building Uniform Mag Field" << endl; MagFieldArray* magFieldArray = new MagFieldArray(); // -- Define solenoid field - uniform magnetic field // Define shape of field TGeoShape* fieldShape = new Tube("SolenoidFieldShape",hvCellRMin, hvCellRMax, hvCellHalfZ); // Define transformation that locates field in geometry TGeoMatrix* fieldPosition = new TGeoHMatrix(matrix); // Define field vector in Coordinate system of Field TVector3 fieldStrength(solenoidBx, solenoidBy, solenoidBz); cout << "Local Coordinates - "; cout << "Bx: " << fieldStrength[0] << "\t By: " << fieldStrength[1]; cout << "\t Bz: " << fieldStrength[2] << endl; // Define field object MagField* uniformField = new UniformMagField("SolenoidField", fieldStrength, fieldShape, fieldPosition); // Add field to magfield manager magFieldArray->AddField(uniformField); // -- Write magfieldmanager to geometry file const char *magFileName = "$(UCN_GEOM)/fields.root"; TFile *f = TFile::Open(magFileName,"recreate"); if (!f || f->IsZombie()) { Error("Export","Cannot open file: %s", magFileName); return kFALSE; } magFieldArray->Write(magFieldArray->GetName()); f->ls(); f->Close(); if (magFieldArray) delete magFieldArray; magFieldArray = 0; return kTRUE; }
/// Open new data file bool DDG4EventHandler::Open(const std::string&, const std::string& name) { if ( m_file.first ) m_file.first->Close(); m_hasFile = false; m_hasEvent = false; TFile* f = TFile::Open(name.c_str()); if ( f && !f->IsZombie() ) { m_file.first = f; TTree* t = (TTree*)f->Get("EVENT"); if ( t ) { TObjArray* br = t->GetListOfBranches(); m_file.second = t; m_entry = -1; m_branches.clear(); for(Int_t i=0; i<br->GetSize(); ++i) { TBranch* b = (TBranch*)br->At(i); if ( !b ) continue; m_branches[b->GetName()] = make_pair(b,(void*)0); printout(INFO,"DDG4EventHandler::open","+++ Branch %s has %ld entries.",b->GetName(),b->GetEntries()); } for(Int_t i=0; i<br->GetSize(); ++i) { TBranch* b = (TBranch*)br->At(i); if ( !b ) continue; b->SetAddress(&m_branches[b->GetName()].second); } m_hasFile = true; return true; } throw runtime_error("+++ Failed to access tree EVENT in ROOT file:"+name); } throw runtime_error("+++ Failed to open ROOT file:"+name); }
Float_t read_tree(const char *filename = "data.root", Double_t bytes = 10000000) { printf("Reading events from a root tree \n"); TFile *filein = new TFile(filename,"READ"); if ( filein->IsZombie() ) { printf("Cannot open file \n"); return 0.0; } Int_t nbgamma; Int_t e[1000]; // up to 1000 energies ..should be ok TTree *treein; treein = (TTree *)filein->Get("TEST"); if ( treein == NULL ) return 0; else { treein->SetBranchAddress("mult",&nbgamma); treein->SetBranchAddress("e",&e); } // write events and compute the needed time TStopwatch watch; watch.Start(); treein->Draw("e","","goff"); watch.Stop(); cout << " --> Reading rate " << bytes / (1024*1024*watch.RealTime()) << " MB/s"<< endl ; filein->Close(); delete filein; return bytes / (1024*1024*watch.RealTime()) ; }
int testSimpleFile(const char *filename, Long64_t entries, Int_t compSetting, Long64_t fileSize, UInt_t tolerance = 0) { fprintf(stdout,"Checking %s\n",filename); TFile *file = TFile::Open(filename); if (file == nullptr || file->IsZombie()) { Error("testSimpleFile", "Could not open %s.",filename); return 1; } //file->ls(); if (file->GetCompressionSettings() != compSetting) { Error("testSimpleFile","Compression level of %s should have been %d but is %d\n",file->GetName(), 206, file->GetCompressionSettings() ); return 3; } if (abs(file->GetSize()-fileSize) > tolerance) { Error("testSimpleFile","Disk size of %s should have been %lld but is %lld (tolerance %u bytes)\n",file->GetName(), fileSize, file->GetSize(), tolerance); return 4; } TTree *ntuple; file->GetObject("ntuple",ntuple); if (ntuple == 0) { Error("testSimpleFile", "Could not retrieve ntuple from %s.",file->GetName()); return 2; } if (ntuple->GetEntries() != entries) { Error("testSimpleFile","Number of entries in ntuple in %s should have been %lld but is %lld\n",file->GetName(), entries, ntuple->GetEntries()); return 4; } delete file; return 0; }
Float_t write_tree(const char *filename = "data.root", Int_t nbevents = 10000000, Int_t compression = 0) { printf("Writing %d events in a root tree with compression level %d \n",nbevents,compression); TFile *fileout = new TFile(filename,"recreate"); if ( fileout->IsZombie() ) { printf("Cannot open file \n"); return 0.0; } fileout->SetCompressionLevel(compression); Double_t wbytes = 0.0; Int_t nbgamma; Int_t e[1000]; for (Int_t i = 1; i < 1000; i++) e[i] = 200*i; TTree *treeout; treeout = new TTree("TEST","TEST"); treeout->Branch("mult",&nbgamma,"nbgamma/I"); treeout->Branch("e",e,"e[nbgamma]/I"); // write events and compute the needed time TStopwatch watch; watch.Start(); for (int i = 0; i < nbevents; i++ ) { nbgamma = 2 + i % 5; wbytes += 4.0; wbytes += nbgamma * 4.0; treeout->Fill(); } watch.Stop(); printf(" --> Writing rate %f MB/s [%f] \n",wbytes/(1024*1024*watch.RealTime()),wbytes/(1024*1024)); fileout->Close(); delete fileout; return wbytes; }
void loadRootFile() { TFile* pRootFile = new TFile("myfile.root", "READ"); if (pRootFile != NULL) { TDirectory* pTestDir = (TDirectory*)pRootFile->Get("TestDir"); if (pTestDir != NULL) { pTestDir->cd(); MyROOTObject* pMyObj = NULL; std::string name = "testobj"; pMyObj = (MyROOTObject*)pTestDir->Get(name.c_str()); if (pMyObj != NULL) { std::cout << *pMyObj << std::endl; delete pMyObj; } } if (pRootFile->IsOpen() && !pRootFile->IsZombie()) { delete pTestDir; pRootFile->Close(); delete pRootFile; } } }
int testMergedFile(const char *filename, Int_t compSetting, Long64_t fileSize) { TFile *file = TFile::Open(filename); if (file == nullptr || file->IsZombie()) { Error("testSimpleFile", "Could not open %s.",filename); return 1; } file->ls(); file->cd("hist"); gDirectory->ls(); gDirectory->Get("Gaus")->Print(); file->cd("named"); gDirectory->ls(); file->Get("MyList")->Print(); if (file->GetCompressionSettings() != compSetting) { Error("execTestMultiMerge","Compression level of %s should have been %d but is %d\n",file->GetName(), 206, file->GetCompressionSettings() ); return 3; } if (file->GetSize() != fileSize) { Error("execTestMultiMerge","Disk size of %s should have been %lld but is %lld\n",file->GetName(), fileSize, file->GetSize() ); return 4; } delete file; return 0; }
void initialize( const char* countdbfn = "counts.root" ) { XSWeightTool::update( "Xsection8TeV_bkg_v4.txt" ); XSWeightTool::update( "Xsection8TeV_sig_v4.txt" ); // XSWeightTool::print(); using namespace std; TFile* f = TFile::Open( countdbfn, "read" ); if( f == NULL || f->IsZombie() ) { return; } TIter next( f->GetListOfKeys() ); TKey *key; int nhist = 0; while( (key = (TKey*)next()) ) { nhist++; // cout << "Key " << nhist << endl; // cout << " Classname " << key->GetClassName() << endl; // cout << " Title " <<key->GetTitle() << endl; if( key->ReadObj()->InheritsFrom( TH1::Class() ) ) { TH1* h = (TH1*)( key->ReadObj() ); long run_num = TString( h->GetName() ).Atoi(); num_events[run_num] = h->GetBinContent( 1 ); // cout << " Run, # of events : " << run_num << ", " << h->GetBinContent( 21 ) << endl; } } // cout << "Done" << endl; }
void init( const char* hfile ) { TFile* f = TFile::Open( hfile, "read" ); if( f!=0x0 and !f->IsZombie() ) { h_jhu_gg = (TH1*)(f->Get( "jhu_gg" )); h_jhu_qq = (TH1*)(f->Get( "jhu_qq" )); } }
void PixelMergeSmallFiles(){ TFile * oFilebDist = new TFile("bDistr2.root", "RECREATE"); TNtuple* SimEventsGlobal = new TNtuple("SimEventGlob", "SimEventGlob", "EvN:b"); TFile * oFileLinks = new TFile("Links2.root", "RECREATE"); TNtuple* LinksGlobal = new TNtuple("LinksGlob", "LinksGlob", "EvN:fedid:linkn:nHits"); char FileInNumber[5]; string FileInPath = "/net/pstore01/d00/scratch/icali/CMSSW_2_1_11/PixelAnalysis/PixelNTuple_hydjet_x2_mb_oldPL_d20081106/"; string FileInNameRoot= "hydjet_x2_mb_oldPL_d20081106_r0"; Float_t j = 0; for(int FileN = 901; FileN <1801; ++FileN){ sprintf(FileInNumber, "%.5d", FileN); string FileInName = FileInPath+FileInNameRoot+FileInNumber+".root"; TFile *iFile = new TFile((const char*)FileInName.c_str()); if(!iFile->IsZombie()){ PixelAnalyzer->cd(); TNtuple *FEDLinks = (TNtuple*)iFile->FindObjectAny("Links"); TNtuple *SimEvents = (TNtuple*)iFile->FindObjectAny("SimEvent"); Float_t FEDEvN, fedid, linkn, nHits; FEDLinks->SetBranchAddress("EventN",&FEDEvN); FEDLinks->SetBranchAddress("fedid",&fedid); FEDLinks->SetBranchAddress("linkn",&linkn); FEDLinks->SetBranchAddress("nHits",&nHits); Long64_t FEDLinkLenght =FEDLinks->GetEntries(); Float_t SimEvN, b; SimEvents->SetBranchAddress("EventN",&SimEvN); SimEvents->SetBranchAddress("mult",&b); Long64_t SimEventLenght =SimEvents->GetEntries(); Long64_t i; for(i=0; i < SimEventLenght; ++i){ SimEvents->GetEntry(i); SimEventsGlobal->Fill(i, b); } Float_t OldEvN= -1; for(i=0; i < FEDLinkLenght; ++i){ FEDLinks->GetEntry(i); if(OldEvN != FEDEvN){ OldEvN= FEDEvN; ++j; } LinksGlobal->Fill(j, fedid, linkn, nHits); } } } oFilebDist->Write(); oFileLinks->Write(); }
TGraph *getGraphFromSpec(const string& gid, const string& fullspec) // alias expansion assumed { TGraph *gr = NULL; TFile *rootfile = NULL; vector<string> v_tokens; string gspec; string rootfn; if (gl_verbose) cout << "processing " << fullspec << endl; // process the (expanded) specification Tokenize(fullspec,v_tokens,":"); if ((v_tokens.size() != 2) || (!v_tokens[0].size()) || (!v_tokens[1].size()) ) { cerr << "malformed root graph path file:folder/subfolder/.../graph " << fullspec << endl; return NULL; } else { rootfn = v_tokens[0]; gspec = v_tokens[1]; } map<string,string>::const_iterator it = glmap_objpath2id.find(fullspec); if (it != glmap_objpath2id.end()) { // Allow the possibility to run the script a second time in root if (gl_verbose) cout << "Object " << fullspec << " already read in, here it is" << endl; map<string,wGraph_t *>::const_iterator git = glmap_id2graph.find(it->second); if (git == glmap_id2graph.end()) { if (gl_verbose) cout << "oops, sorry, I lied." << endl; return NULL; } gr = git->second->gr; } else { // Now check to see if this file has already been opened... map<string,TFile*>::const_iterator fit = glmap_id2rootfile.find(rootfn); if (fit != glmap_id2rootfile.end()) rootfile = fit->second; else rootfile = new TFile(rootfn.c_str()); if (rootfile->IsZombie()) { cerr << "File failed to open, " << rootfn << endl; } else { glmap_id2rootfile.insert(pair<string,TFile*>(rootfn,rootfile)); gr = (TGraph *)rootfile->Get(gspec.c_str()); if (!gr) { cerr << "couldn't find " << gspec << " in " << rootfn << endl; } else { // success, record that you read it in. glmap_objpath2id.insert(pair<string,string>(fullspec,gid)); } } } return gr; } // getGraphFromSpec
//------------------------------------------------------------------------------------------------- void makeCMS2ClassFiles (const std::string& fname, bool paranoid = true, const std::string& treeName="", const std::string& branchNamesFile="", const std::string& className="CMS2", const std::string& nameSpace="tas", const std::string& objName="cms2") { using namespace std; TFile *f = TFile::Open( fname.c_str() ); if(f==NULL) { cout << "File does not exist. Exiting program" << endl; return; } if(f->IsZombie()) { cout << "File is not a valid root file, or root file is corruped" << endl; cout << "Exiting..." << endl; return; } //check if the branchNamesFile exists if(branchNamesFile != "") { struct stat results; int intStat = stat(branchNamesFile.c_str(), &results); if(intStat != 0) { cout << "Cannot open " << branchNamesFile << endl; cout << "Please make sure that the file exists" << endl; return; } } //class is CMS2 by default //std::string Classname = className=="" ? "CMS2" : className; headerf.open((className+".h").c_str()); implf.open((className+".cc").c_str()); codef.open("ScanChain.C"); implf << "#include \"" << className+".h" << "\"\n" << className << " " << objName << ";" << endl; makeHeaderFile(f, treeName, paranoid, className, nameSpace, objName); makeSrcFile(className, nameSpace, branchNamesFile, treeName, objName); if(branchNamesFile!="") makeBranchFile(branchNamesFile, treeName); implf << "}" << endl; implf.close(); headerf << "}" << endl; headerf << "#endif" << endl; headerf.close(); codef.close(); makeDriverFile(fname, treeName); f->Close(); }
void PlotImages() { gStyle->SetOptStat(0); gStyle->SetPadRightMargin(0.2); string filename[1]; char buffer[100]; char buffertext[100]; for (int seed=55; seed<56; seed++) { int n=sprintf(buffer, "/home/les67/locust_faketrack_waterfall.root"); const char *file = buffer; TFile* f = TFile::Open(file); if (!((!f)||f->IsZombie())) { TH2D* hspectrogram = GetSpectrogram(file); TH2D* hlabels = GetLabels(hspectrogram, 40e-21); // threshold for labeling goes here. // TGraph* grlabels = GetLabelGraph(hlabels); // PrintLabels(grlabels); // print labels to terminal. hspectrogram->GetXaxis()->SetRangeUser(0.,0.02); hspectrogram->GetYaxis()->SetRangeUser(149.e6, 170.e6); TCanvas *c = new TCanvas; n=sprintf(buffertext, "hspectrogram_%d.png", seed); const char *pngname = buffertext; hspectrogram->GetYaxis()->SetTitleOffset(1.25); hspectrogram->DrawCopy("colz"); /* grlabels->SetMarkerColor(2); grlabels->SetMarkerStyle(8); grlabels->SetMarkerSize(0.6); grlabels->SetLineWidth(3.); grlabels->SetLineColor(2); grlabels->Draw("psame"); */ /* TImage *img = TImage::Create(); img->FromPad(c); img->WriteImage(pngname); delete img; delete hspectrogram; delete c; */ f->Close(); } } }
void displaySingleChannelWaveforms(TString fdat, int board, int channel) { gStyle->SetOptStat(0); TFile *f = new TFile(fdat); if (f->IsZombie()){ cout << "Cannot open file: " << fdat << endl; return; } TBEvent *event = new TBEvent(); TTree *t1041 = (TTree*)f->Get("t1041"); TBranch *bevent = t1041->GetBranch("tbevent"); bevent->SetAddress(&event); TCanvas * canv = new TCanvas("canv", "canv", 2000, 2000); canv->cd(); TH1F * dummy = new TH1F("dummy", "dummy", 120, 0, 120); dummy->GetYaxis()->SetRangeUser(0, 2500); dummy->Draw(); vector<TH1F*> waves; TH1F * wave = new TH1F("wave", "wave", 120, 0, 120); int nplots = 0; for (Int_t i = 0; i < t1041->GetEntries(); i++) { t1041->GetEntry(i); for (int j = 0; j < event->NPadeChan(); j++){ PadeChannel pch = event->GetPadeChan(j); if((int)pch.GetBoardID() != board || (int)pch.GetChannelID() != channel) continue; pch.GetHist(wave); nplots++; TH1F * wavecopy = (TH1F*)wave->Clone("wave_"+TString(Form("%d", nplots))); waves.push_back(wavecopy); } } int nBigPeaks = 0; for(unsigned int ui = 0; ui < waves.size(); ui++) { if(waves[ui]->GetMaximum() > 400) { waves[ui]->SetLineColor(nBigPeaks+2); nBigPeaks++; } waves[ui]->Draw("same"); } }
void CalibrationScanAnalysis::addFile(const std::string& filename) { TFile* test = new TFile(filename.c_str()); bool noFile = test->IsZombie(); test->Close(); delete test; if(!noFile) { TFile* newFile = new TFile(filename.c_str(),"UPDATE"); addFile(newFile); } }
int reader_wrapper::getTree(TString infile, TString treename, TString outfile) { m_infile = TFile::Open(infile,"update"); if (nullptr == m_infile || m_infile->IsZombie() || m_infile->GetNkeys() <= 0) { std::cerr << "File " << infile << " could not be opened properly." << std::endl; return 1; } m_intree = dynamic_cast<TTree*>(m_infile->Get(treename.Data())); if (nullptr == m_intree) { std::cerr << "Tree " << treename << " could not be opened properly." << std::endl; return 2; } m_outfile = TFile::Open(outfile,"create"); if (nullptr == m_outfile || m_outfile->IsZombie()) { std::cerr << "File " << outfile << " could not be opened properly." << std::endl; return 3; } return 0; }
// generic function that creates mass bin directory structure and // returns array of event files and trees, one for each mass bin bool createMassBinFiles(vector<TFile*>& pwaFiles, vector<TTree*>& pwaTrees, const string& dirBaseName = "/tmp/", const unsigned int nmbMassBins = 50, const double massBinWidth = 50, // [MeV/c^2] const double massRangeMin = 500, // [MeV/c^2] const string& treeName = "rootPwaEvtTree") { printInfo << "creating mass bin directories/files in '" << dirBaseName << "':" << endl; // cleanup for (unsigned int i = 0; i < pwaTrees.size(); ++i) if (pwaTrees[i]) delete pwaTrees[i]; pwaTrees.clear(); for (unsigned int i = 0; i < pwaFiles.size(); ++i) if (pwaFiles[i]) { pwaFiles[i]->Close(); delete pwaFiles[i]; } pwaFiles.clear(); pwaFiles.resize(nmbMassBins, 0); pwaTrees.resize(nmbMassBins, 0); bool success = true; for (unsigned int i = 0; i < nmbMassBins; ++i) { const double binMin = massRangeMin + i * massBinWidth; const double binMax = binMin + massBinWidth; // create mass bin directory stringstream n; n << binMin << "." << binMax; const string dirName = dirBaseName + "/" + n.str(); mkdir(dirName.c_str(), S_IRWXU | S_IRWXG); // create directory read/writable by owner and group // create output file const string pwaFileName = dirName + "/" + n.str() + ".root"; TFile* pwaFile = TFile::Open(pwaFileName.c_str(), "RECREATE"); if (not pwaFile or pwaFile->IsZombie()) { printWarn << "problems creating file '" << pwaFileName << "'" << endl; success = false; } else { pwaFiles[i] = pwaFile; pwaTrees[i] = new TTree(treeName.c_str(), treeName.c_str()); if (not pwaTrees[i]) { printWarn << "problems creating tree '" << treeName << "' " << "in file " << "'" << pwaFileName << "'" << endl; success = false; } else { pwaTrees[i]->SetDirectory(pwaFile); printSucc << "created tree '" << treeName << "' in file " << "'" << pwaFileName << "'" << endl; } } } return success; }
bool PlotManager::setOutFile(const string& fileName) { if ( theOutFile_ ) theOutFile_->Close(); string pwd(gDirectory->GetPath()); theOutFile_ = new TFile(fileName.c_str(), "RECREATE"); if ( !theOutFile_ || theOutFile_->IsZombie() ) return false; gDirectory->cd(pwd.c_str()); return true; }
void LegendreMomentShape::Open(const std::string filename) { TFile* file; if(!filename.empty()) { std::cout << "Opening " << filename << std::endl; file = TFile::Open(filename.c_str()); } else return; if(file->IsZombie()) { std::cerr << "No file found. Defaulting to uniform shape." << std::endl; delete file; return; } TTree* tree = (TTree*)file->Get("LegendreMomentsTree"); if(tree == nullptr) throw std::runtime_error("LegendreMomentsTree not found"); tree->SetBranchAddress("mKK_min",&mKK_min); tree->SetBranchAddress("mKK_max",&mKK_max); std::string limbranchtitle = tree->GetBranch("c")->GetTitle(); // Read the index maxima from the name of the branch size_t found = 0; for(int* maximum: {&l_max, &i_max, &k_max, &j_max}) { found = limbranchtitle.find('[',found+1); limbranchtitle.find(']',found); *maximum = atoi(limbranchtitle.substr(found+1,1).c_str()); } double**** c = newcoefficients(); // Set up the 4D array and prepare to read from the tree char branchtitle[10]; // the letter "c" + four 2-digit numbers + 1 for luck // Seriously I don't expect *any* 2-digit numbers for ( int l = 0; l < l_max; l++ ) for ( int i = 0; i < i_max; i++ ) for ( int k = 0; k < k_max; k++ ) for ( int j = 0; j < j_max; j++ ) { sprintf(branchtitle,"c%d%d%d%d",l,i,k,j); tree->SetBranchAddress(branchtitle,&c[l][i][k][j]); } tree->GetEntry(0); storecoefficients(c); deletecoefficients(c); if(coeffs.size() == 0) { std::cerr << "No coefficients found. Defaulting to uniform shape." << std::endl; return; } printcoefficients(); delete tree; delete file; init = false; }