bool PlotBundle::drawHistsAndGraphs(const PlotStyle &plot_style) const { if (hasDrawables()) { std::vector<DrawableDataObjectDrawOptionPair<TH1*> >::const_iterator hist_it; for (hist_it = histograms.begin(); hist_it != histograms.end(); hist_it++) { TH1* hist = hist_it->data_object; std::string draw_option(hist_it->draw_option); if (hist) { if (hist->GetDimension() > 1) { hist->GetZaxis()->SetLimits(plot_axis.z_axis_range.low, plot_axis.z_axis_range.high); hist->GetZaxis()->SetRangeUser(plot_axis.z_axis_range.low, plot_axis.z_axis_range.high); } draw_option.append("SAME"); hist->Draw(draw_option.c_str()); } } std::vector<DrawableDataObjectDrawOptionPair<TGraph*> >::const_iterator graph_it; for (graph_it = graphs.begin(); graph_it != graphs.end(); graph_it++) { TGraph* graph = graph_it->data_object; std::string draw_option(graph_it->draw_option); if (graph) { draw_option.append("SAME"); graph->Draw(draw_option.c_str()); } } std::vector<DrawableDataObjectDrawOptionPair<TGraph2D*> >::const_iterator graph2d_it; for (graph2d_it = graphs2d.begin(); graph2d_it != graphs2d.end(); graph2d_it++) { TGraph2D* graph = graph2d_it->data_object; std::string draw_option(graph2d_it->draw_option); if (graph) { draw_option.append("SAME"); graph->Draw(draw_option.c_str()); } } return true; } else { std::cout << "Dude, you forgot to add a histogram or graph in the plot bundle..." << " Please add at least one and make sure it points to an existing object!" << std::endl; return false; } }
TH1* getHistogram(TFile* inputFile, const TString& dqmDirectory, const TString& meName) { TString histogramName = dqmDirectory; if ( histogramName.Length() > 0 && !histogramName.EndsWith("/") ) histogramName.Append("/"); histogramName.Append(meName); TH1* histogram = (TH1*)inputFile->Get(histogramName.Data()); std::cout << "histogramName = " << histogramName.Data() << ": histogram = " << histogram; if ( histogram ) std::cout << ", integral = " << histogram->Integral(); std::cout << std::endl; if ( !histogram->GetSumw2N() ) histogram->Sumw2(); if ( histogram->GetDimension() == 1 ) histogram->Rebin(5); return histogram; }
void writeFile(const char* inRootFile) { TFile inRoot(inRootFile); if(!inRoot.IsOpen()){ cout << "Cannot open " << inRootFile << endl; return; } TIterator* iterator = inRoot.GetListOfKeys()->MakeIterator(); TKey* key; TString outText = inRootFile; outText.Replace(0,outText.Last('/')+1,""); ofstream os(outText.Data()); char buf[500]; int count(0); while( (key=dynamic_cast<TKey*>(iterator->Next())) != 0){ cout << key->GetName() << endl; TH1* h = (TH1*)inRoot.Get(key->GetName()); if(h->GetDimension()!=1) continue; if(++count>1) break; int nBin = h->GetNbinsX(); os << "name: " << h->GetName() << endl << "title: " << h->GetTitle() << endl << "bins: " << h->GetNbinsX() << endl << "min: " << h->GetXaxis()->GetBinLowEdge(1) << ", max: " << h->GetXaxis()->GetBinUpEdge(h->GetNbinsX()) << endl; for(int i=1; i<=nBin; i++){ os << "bin: " << i << " value: " << (float)h->GetBinContent(i) << " error: " << (float)h->GetBinError(i) << endl; } } }
/////////////////////////////////////////////////////////////////// //////// Go4 GUI example script addhistos.C // J.Adamczewski, gsi, May 2006 // JAM May 2015: added support for 2d histograms // NOTE: to be run in Go4 GUI local command line only! // NEVER call this script in remote analysis process!!! /////// Functionality: // adds histogram of name2 to histogram of name1 /////// Usage: // histogram name2 will be scaled by factor. // (e.g. if factor==-1, his2 is substracted from his1) // The draw flag switches if the results are displayed each time this makro is called // if display is switched off, the result histogram is just updated in browser and existing displays /////// Bool_t addhistos(const char* name1, const char* name2, Double_t factor, Bool_t draw) { if(TGo4AbstractInterface::Instance()==0 || go4!=TGo4AbstractInterface::Instance()) { std::cout <<"FATAL: Go4 gui macro executed outside Go4 GUI!! returning." << std::endl; return kFALSE; } TString fullname1 = go4->FindItem(name1); TObject* ob1=go4->GetObject(fullname1,1000); // 1000=timeout to get object from analysis in ms TH1 *his1(0), *his2(0); if(ob1 && ob1->InheritsFrom("TH1")) his1 = (TH1*) ob1; if(his1==0) { std::cout <<"addhistos could not get histogram "<<fullname1 << std::endl; return kFALSE; } TString fullname2 = go4->FindItem(name2); TObject* ob2=go4->GetObject(fullname2,1000); // 1000=timeout to get object from analysis in ms if(ob2 && ob2->InheritsFrom("TH1")) his2 = (TH1*)ob2; if(his2==0) { std::cout <<"addhistos could not get histogram "<<fullname2 << std::endl; return kFALSE; } if((his1->GetDimension()) != (his2->GetDimension())) { std::cout <<"addhistos could not add histograms of different dimensions "<< std::endl; return kFALSE; } TH1* result = (TH1*) his1->Clone(); TString n1 = his1->GetName(); TString n2 = his2->GetName(); TString t1 = his1->GetTitle(); TString t2 = his2->GetTitle(); TString soper; if(factor>0) soper.Form(") + %4.1E * (",factor); else soper.Form(") - %4.1E * (",-1*factor); TString finalname = TString("(")+n1+soper+n2+")"; TString finaltitle = TString("(")+t1+soper+t2+")"; result->SetName(finalname); result->SetTitle(finaltitle); result->Sumw2(); result->Add(his2,factor); result->SetDirectory(0); TString rname = go4->SaveToMemory("Sums", result, kTRUE); std::cout<< "Saved result histogram to " << rname.Data() <<std::endl; if(draw) { ViewPanelHandle vpanel = go4->StartViewPanel(); if(result->GetDimension()>1) { // superimpose mode is not supported for 2d histograms go4->DrawItem(rname, vpanel); } else { go4->SetSuperimpose(vpanel,kTRUE); go4->DrawItem(fullname1, vpanel); go4->DrawItem(fullname2, vpanel); go4->DrawItem(rname, vpanel); } } return kTRUE; }
// --------------------------------------------------------------------------------------------- // returns scaling (change in normalization, in log 10) or -666 if failed // optional parameter accepts the desired unit prefix (in log 10) int adjustUnits( TH1& h1, int forceNewPrefix = -666) { if( h1.GetDimension() != 1) {cerr<<"ERROR! 'adjustUnits' works only for 1D histograms!"<<endl; return -666;} bool forced = forceNewPrefix != -666; TString ss( h1.GetYaxis()->GetTitle() ); ss.ReplaceAll ("_{T}", "_%@#"); // otherwise it messes up the reg. exp. // all backslashes are doubled, to get by the compiler string parsing, leaving \[ for TRegexp --> literal [s & ]s int iOpenBracket = ss.Index (TRegexp ("\\[[^\\]]*\\][^\\[\\]]*$"));// That is, the start of the last square brackets int iCloseBracket = ss.Last(']'); // no need for quotes with char if( iOpenBracket < 0 || iCloseBracket <= iOpenBracket ) { // can't find units return -666; } Double_t oldMax = h1.GetMaximum(); h1.SetMaximum(); // unsets Double_t max = h1.GetMaximum(); Double_t max10 = TMath::Log10( max ); if( -3 < max10 && max10 < 3 && ! forced ) return 0; // no rescaling needed // parse input units TString inputUnits = ss( 1+iOpenBracket, -1 + iCloseBracket - iOpenBracket); int curPrefix = 0, prefixLength = 0; if( inputUnits.BeginsWith( "m" ) ) {curPrefix = -3; prefixLength = 1;} if( inputUnits.BeginsWith( "#mu" ) ) {curPrefix = -6; prefixLength = 3;} if( inputUnits.BeginsWith( "n" ) ) {curPrefix = -9; prefixLength = 1;} if( inputUnits.BeginsWith( "p" ) ) {curPrefix = -12; prefixLength = 1;} if( inputUnits.BeginsWith( "f" ) ) {curPrefix = -15; prefixLength = 1;} if( inputUnits.BeginsWith( "k" ) ) {curPrefix = 3; prefixLength = 1;} // add more as needed.... TString baseUnit( inputUnits( prefixLength, inputUnits.Length() - prefixLength ) ); // find target units int iNewPrefix = 3 * TMath::Floor( 0.5 + (curPrefix + max10)/3. ); if( forced ) iNewPrefix = forceNewPrefix; // prepare new units and scaling TString sNewPrefix; int scale10 = 1; if( iNewPrefix > 3 ) {cerr<<"adjustUnits - NYI for >kilo"<<endl;} if( iNewPrefix >= 3 ) {sNewPrefix = "k"; scale10 = curPrefix - 3;} if( -15 < iNewPrefix && iNewPrefix < 3 ) scale10 = curPrefix- iNewPrefix; if( iNewPrefix == 0 ) sNewPrefix = ""; if( iNewPrefix == -3 ) sNewPrefix = "m"; if( iNewPrefix == -6 ) sNewPrefix = "#mu"; if( iNewPrefix == -9 ) sNewPrefix = "n"; if( iNewPrefix == -12 ) sNewPrefix = "p"; if( iNewPrefix < -15 ) {cerr<<"adjustUnits - NYI for <femto"<<endl;} if( iNewPrefix <= -15 ) {sNewPrefix = "f"; scale10 = curPrefix + 15;} // sanity checks if( forced && forceNewPrefix != 0 && sNewPrefix == "" ) { cerr<<"adjustUnits - illegal new prefix forced!"<<endl; return -666; } if( scale10 == 0 && ! forced ) {cerr<<"Bug in adjustUnits? scale10 == 0 .... "<<endl; return -666;} // good to go - changing the histogram Double_t scale = TMath::Power( 10, scale10 ); h1.Scale( scale ); h1.SetMaximum( oldMax * scale ); h1.GetYaxis()->SetTitle( ss( 0, iOpenBracket + 1 ) + sNewPrefix + baseUnit + ss( iCloseBracket, ss.Length() - iCloseBracket ) ); return scale10; }
static PyObject * fill_hist_with_ndarray(PyObject *self, PyObject *args, PyObject* keywords) { using namespace std; PyObject *hist_ = NULL; PyObject *array_ = NULL; PyObject *weights_ = NULL; PyArrayObject *array = NULL; PyArrayObject *weights = NULL; TH1* hist = NULL; TH2* hist2d = NULL; TH3* hist3d = NULL; unsigned int dim = 1; unsigned int array_depth = 1; unsigned int i, n, k; char *array_data; char *weights_data = NULL; npy_intp array_stride_n; npy_intp array_stride_k = 1; npy_intp weights_stride = 1; static const char* keywordslist[] = { "hist", "array", "weights", NULL}; if(!PyArg_ParseTupleAndKeywords( args, keywords, "OO|O", const_cast<char **>(keywordslist), &hist_, &array_, &weights_)) { return NULL; } if(!PyCObject_Check(hist_)) { PyErr_SetString(PyExc_TypeError,"Unable to convert hist to PyCObject"); return NULL; } //this is not safe so be sure to know what you are doing type check in python first //this is a c++ limitation because void* have no vtable so dynamic cast doesn't work hist = static_cast<TH1*>(PyCObject_AsVoidPtr(hist_)); if (hist == NULL) { PyErr_SetString(PyExc_TypeError,"Unable to convert hist to TH1*"); return NULL; } dim = hist->GetDimension(); if (dim == 2) { hist2d = static_cast<TH2*>(PyCObject_AsVoidPtr(hist_)); if (hist2d == NULL) { PyErr_SetString(PyExc_TypeError,"Unable to convert hist to TH2*"); return NULL; } } else if (dim == 3) { hist3d = static_cast<TH3*>(PyCObject_AsVoidPtr(hist_)); if (hist3d == NULL) { PyErr_SetString(PyExc_TypeError,"Unable to convert hist to TH3*"); return NULL; } } else if (dim > 3) { PyErr_SetString(PyExc_ValueError,"dim must not be greater than 3"); return NULL; } if (dim > 1) array_depth = 2; array = (PyArrayObject *) PyArray_ContiguousFromAny( array_, PyArray_DOUBLE, array_depth, array_depth); if (array == NULL) { PyErr_SetString(PyExc_TypeError, "Unable to convert object to array"); return NULL; } if (dim > 1) { k = array->dimensions[1]; if (k != dim) { PyErr_SetString(PyExc_ValueError, "length of the second dimension must equal the dimension of the histogram"); Py_DECREF(array); return NULL; } array_stride_k = array->strides[1]; } n = array->dimensions[0]; array_stride_n = array->strides[0]; array_data = array->data; if (weights_) { weights = (PyArrayObject *) PyArray_ContiguousFromAny( weights_, PyArray_DOUBLE, 1, 1); if (weights == NULL) { PyErr_SetString(PyExc_TypeError, "Unable to convert object to array"); Py_DECREF(array); return NULL; } if (n != weights->dimensions[0]) { PyErr_SetString(PyExc_ValueError, "array and weights must have the same length"); Py_DECREF(weights); Py_DECREF(array); return NULL; } weights_data = weights->data; weights_stride = weights->strides[0]; } if (dim == 1) { // weighted fill if (weights) { for (i = 0; i < n; ++i) { hist->Fill( *(double *)(array_data + i * array_stride_n), *(double *)(weights_data + i * weights_stride)); } } else { // unweighted fill for (i = 0; i < n; ++i) { hist->Fill(*(double *)(array_data + i * array_stride_n)); } } } else if (dim == 2) { // weighted fill if (weights) { for (i = 0; i < n; ++i) { hist2d->Fill( *(double *)(array_data + i * array_stride_n), *(double *)(array_data + i * array_stride_n + array_stride_k), *(double *)(weights_data + i * weights_stride)); } } else { // unweighted fill for (i = 0; i < n; ++i) { hist2d->Fill( *(double *)(array_data + i * array_stride_n), *(double *)(array_data + i * array_stride_n + array_stride_k)); } } } else if (dim == 3) { // weighted fill if (weights) { for (i = 0; i < n; ++i) { hist3d->Fill( *(double *)(array_data + i * array_stride_n), *(double *)(array_data + i * array_stride_n + array_stride_k), *(double *)(array_data + i * array_stride_n + 2 * array_stride_k), *(double *)(weights_data + i * weights_stride)); } } else { // unweighted fill for (i = 0; i < n; ++i) { hist3d->Fill( *(double *)(array_data + i * array_stride_n), *(double *)(array_data + i * array_stride_n + array_stride_k), *(double *)(array_data + i * array_stride_n + 2 * array_stride_k)); } } } if (weights) Py_DECREF(weights); Py_DECREF(array); Py_RETURN_NONE; }