void makeTTree(){ // Declaring Double_t num; Double_t xNumBins, yNumBins; // Setting up Canvas to put plot the 2D histogram (from Tamii) and the 2 Bracnh Tree (created by this program) TCanvas *canvas = new TCanvas("canvas","Canvas"); canvas->Divide(2,1); canvas->cd(1); // Opening up histogram file from tamii's analyzer // Remember to do h2root before this program runs. TFile *f1 = new TFile("run6106_test44.root"); TH2F *hist2D = (TH2F*)f1->Get("h159"); // Plotting the 2D histogram on the first part of the Canvas hist2D->Draw("COLZ"); // Going through 2D hist and getting the total number of x and y bins. xNumBins = hist2D->GetNbinsX(); yNumBins = hist2D->GetNbinsY(); // Creating a new file to save the 2 branch tree to. TFile *t1 = new TFile("~/e329/root/13C/runs/run3014.root","recreate"); // This is the actual tree being created. // !!! For you YingYing, instead of x vs theta, you would have theta(fp or target) vs Yfp !!! TNtuple *DATA = new TNtuple("DATA","Xpos vs Theta","Xpos:Theta"); // This is the main nested for loop that goes through each bin in the 2D hist // takes the number of counts in that (x,y)bin and creates that many events // in the 2 branch tree for (int binx = 0; binx < xNumBins+2; binx++){ for (int biny = 0; biny < yNumBins+2; biny++){ //getting the number of events in a particular (x,y)bin num = hist2D->GetBinContent(binx,biny); double x = hist2D->GetXaxis()->GetBinCenter(binx); double y = hist2D->GetYaxis()->GetBinCenter(biny); //cout << num << " at x= " << x << ", y= " << y << endl; //Filling the Tree 'num' times with xbin and ybin events for (int i = 0; i < num; i++){ DATA->Fill(x,y); } } } //Saving the Tree that was just created and filled t1->Write(); //Ploting the Tree in the second part of the canvas. canvas->cd(2); DATA->Draw("Theta:Xpos>>(2000,-600,600,1000,-3,3)","","COLZ"); }
void parallelcoord() { TNtuple *nt = NULL; Double_t s1x, s1y, s1z; Double_t s2x, s2y, s2z; Double_t s3x, s3y, s3z; r = new TRandom();; new TCanvas("c1", "c1",0,0,800,700); gStyle->SetPalette(1); nt = new TNtuple("nt","Demo ntuple","x:y:z:u:v:w"); for (Int_t i=0; i<20000; i++) { r->Sphere(s1x, s1y, s1z, 0.1); r->Sphere(s2x, s2y, s2z, 0.2); r->Sphere(s3x, s3y, s3z, 0.05); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6); generate_random(i); nt->Fill(s1x, s1y, s1z, s2x, s2y, s2z); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6); generate_random(i); nt->Fill(s2x-1, s2y-1, s2z, s1x+.5, s1y+.5, s1z+.5); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6); generate_random(i); nt->Fill(s1x+1, s1y+1, s1z+1, s3x-2, s3y-2, s3z-2); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6); } nt->Draw("x:y:z:u:v:w","","para",5000); TParallelCoord* para = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord"); para->SetDotsSpacing(5); TParallelCoordVar* firstaxis = (TParallelCoordVar*)para->GetVarList()->FindObject("x"); firstaxis->AddRange(new TParallelCoordRange(firstaxis,0.846018,1.158469)); para->AddSelection("violet"); para->GetCurrentSelection()->SetLineColor(kViolet); firstaxis->AddRange(new TParallelCoordRange(firstaxis,-0.169447,0.169042)); para->AddSelection("Orange"); para->GetCurrentSelection()->SetLineColor(kOrange+9); firstaxis->AddRange(new TParallelCoordRange(firstaxis,-1.263024,-0.755292)); }
void Example2(){ gROOT->Reset(); gROOT->Clear(); gROOT->SetStyle("Plain"); gStyle->SetTextSize(0.01908148); gStyle->SetTitleFontSize(0.07); gStyle->SetOptTitle(1); gStyle->SetOptStat(1110); gStyle->SetOptFit(1111); gStyle->SetTitleXOffset(1.1); gStyle->SetTitleYOffset(1.55); gStyle->SetPadTopMargin(0.15); gStyle->SetPadBottomMargin(0.15); gStyle->SetPadLeftMargin(0.15); // select the one of the versus : Hf energy, Centrality, # Charged , # Tracks int Vselect = 1; // number of Trigger you will use , const int Ntr = 2; //if you want to use more than two trigger please specify the Ntr2 for dividivg the canvas const int Ntr2 = 1; TFile* inf = new TFile("openhlt2.root"); string triggers[6] = {"L1Tech_BSC_minBias_threshold1.v0","L1Tech_BSC_minBias_threshold2.v0","L1_SingleJet30","L1_TripleJet30","L1_QuadJet15","L1_DoubleJet70"}; string vers[4] = {"hiHF","hiBin","Ncharged","hiNtracks"}; double bins [4] = {170,40,240,140}; double limits[4] = {170000,40,24000,1400}; TCanvas* c1 = new TCanvas("c1","c1",800,400); c1->Divide(Ntr,Ntr2); TNtuple* nt = (TNtuple*)inf->Get("HltTree"); TProfile* p1[Ntr]; for(unsigned int i =0; i<Ntr ; i++){ c1->cd(i+1); p1[i] = new TProfile("p1",Form(";%s;%s",vers[Vselect].data(),triggers[i].data()),bins[1],0,limits[1]); nt->SetAlias("trigger",triggers[i].data()); nt->SetAlias("versus",vers[Vselect].data()); nt->Draw("trigger:versus>>p1","","prof"); } c1->Print(Form("%s_vsCent.gif",triggers[Vselect].data())); }
double getUncertaintyValue(double m0,double m12, int channel, string valuename, TFile * input) { bool DEBUGuncertaintyValue=false; /* string buffer = doubletostr(m0)+doubletostr(m12)+inttostr(channel)+valuename; map <std::string, double>::iterator iter; iter=UncertaintyValueBuffer.find(buffer); if (bufferValue && iter!=UncertaintyValueBuffer.end()) return iter->second; */ double returnvalue2 ; double min=-10; double max=+10; //cout << "v" ; string leaveName=""; if (valuename=="K") leaveName="K"; if (valuename=="crossSection") {leaveName="crossSection"; min=0; max=100000;}; if (valuename=="PDFUncertainty") leaveName="relUncPDF"; if (valuename=="ScaleUncertainty2Q") leaveName="relScaleUnc2Q"; if (valuename=="ScaleUncertainty12Q") leaveName="relScaleUncHalfQ"; if (leaveName=="") throw "no leave found for that value"; string commandstring=leaveName+">>h1"; string conditionstring= "finalState>" + doubletostr(channel-0.1) +"&& finalState<"+ doubletostr(channel+0.1) +"&& m0>" + doubletostr(m0-0.5) + " && m0<"+doubletostr(m0+0.5) +" && m12>" + doubletostr(m12-0.5) + " && m12<"+doubletostr(m12+0.5); if (DEBUGuncertaintyValue){ cout << " commandstring " << commandstring << endl; cout << " conditionstring " << conditionstring << endl; cout << " leaveName " << leaveName << endl; cout << " valuename :" << valuename << " channel: " << channel << " m0: " << m0 << " m12: " << m12 << endl; } TNtuple *ntuple = (TNtuple*)file_robin->Get("SignalUncertainties"); if (ntuple==0) throw "Ntuple not found"; if (DEBUGuncertaintyValue) cout << "(min,max) "<<min << " "<<max<<endl; TH1F * h1 = new TH1F("h1","h1",100000,min,max); ntuple->Draw(commandstring.c_str(),conditionstring.c_str()); if (DEBUGuncertaintyValue) cout << "mean " << h1->GetMean()<<endl; returnvalue2 = fabs (h1->GetMean()); // UncertaintyValueBuffer[buffer]=returnvalue2; delete h1; return returnvalue2; }
void rootFit(){ TCanvas *c1 = new TCanvas("c1","",600,600); c1->Divide(1,2); TNtuple *T = new TNtuple("T","","x:y:z"); T->ReadFile("histogramData.dat"); T->Draw("y:x"); Double_t *X = T->GetV1(); Double_t *Y = T->GetV2(); for(int loop = 0; loop < 120; loop++){ cout << X[loop] << " " << Y[loop] << endl; } c1->Clear(); TGraph *graphT = new TGraph(120,Y,X); TGraph *graphB = new TGraph(120,Y,X); c1->cd(1); graphT->Draw("APL"); graphT->Fit("gaus+pol2","RME"); }
void unfoldPt(int mode=0) { // Matched Tracklets TFile *inf = new TFile("match-10TeV-12.root"); TNtuple *nt = (TNtuple*)inf->FindObjectAny("nt"); // Test sample TFile *infTest = new TFile("./TrackletTree-Run123596.root"); TNtuple *ntTest = (TNtuple*)infTest->FindObjectAny("TrackletTree12"); TFile *pdfFile; if (mode==0) pdfFile = new TFile("pdf.root","recreate"); else pdfFile = new TFile("pdf.root"); double nPtBin=15; double minPt=log(0.05); double maxPt=log(10); double nDphiBin=600; double maxDphi=0.4; char* mycut = Form("abs(eta)<2&&log(pt)>%f&&log(pt)<%f",minPt,maxPt); char* mycut1=Form("abs(eta)<2&&log(pt)>%f&&log(pt)<%f&&abs(eta-eta1)<0.01&&abs(deta)<0.01",minPt,maxPt); TH2F *h; TH1F *hdphi = new TH1F("hdphi","",nDphiBin,0,maxDphi); TH1F *hdphi2; TH1F *hpt; TH1F *hptH = new TH1F("hptH","",nPtBin,minPt,maxPt); TH1F *hptUnfold = new TH1F("hptUnfold","",nPtBin,minPt,maxPt); TH1F *hptMC = new TH1F("hptMC","",nPtBin,minPt,maxPt); TH1F *hptTemp = new TH1F("hptTemp","",nPtBin,minPt,maxPt); // Delta phi as a function of matched genparticle transverse momentum TCanvas *c = new TCanvas("c","",600,600); if (mode == 0) { h = new TH2F("h","",nPtBin,minPt,maxPt,nDphiBin,0,maxDphi); hdphi2 = new TH1F("hdphiMC","",nDphiBin,0,maxDphi); hpt = new TH1F("hpt","",nPtBin,minPt,maxPt); h->SetXTitle("ln(P_{T}) GeV/c"); h->SetYTitle("|#Delta#phi|"); nt->Draw("abs(dphi):log(pt)>>h",mycut1,"col"); // used to generate pdf nt->Draw("abs(dphi)>>hdphiMC",mycut,""); nt->Draw("log(pt)>>hpt",mycut,""); h->Write(); hpt->Write(); hdphi2->Write(); } else { h = (TH2F*) pdfFile->FindObjectAny("h"); hdphi2 = (TH1F*) pdfFile->FindObjectAny("hdphiMC"); hpt = (TH1F*) pdfFile->FindObjectAny("hpt"); } // Delta phi fit TCanvas *c2 = new TCanvas("c2","",600,600); c2->SetLogy(); c2->SetLogx(); // dphi for unfolding and MC truth: ntTest->Draw("abs(dphi)>>hdphi","abs(eta1)<2&&abs(deta)<0.1","",200000); ntTest->Draw("log(pt)>>hptH",mycut,"",200000); histFunction2D *myfun = new histFunction2D(h); TF1 *test = new TF1("histFun",myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1); TF1 *test2 = new TF1("histFunMC",myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1); for (int i=0;i<nPtBin+1;i++) { test->SetParameter(i,1); } hdphi2->SetXTitle("|#Delta#phi|"); hdphi2->SetYTitle("Arbitrary Normalization"); hdphi2->Fit("histFunMC","M"); hdphi->SetXTitle("|#Delta#phi|"); hdphi->SetYTitle("Arbitrary Normalization"); hdphi->Fit("histFun","M"); hdphi->SetStats(0); hdphi->Draw(); for (int i=0;i<nPtBin+1;i++) { TF1 *testPlot = new TF1(Form("histFun%d",i),myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1); testPlot->SetParameter(i,test->GetParameter(i)); testPlot->SetLineColor(i+2); testPlot->Draw("same"); } int total=0,totalMC=0; for (int i=0;i<nPtBin;i++){ if (test->GetParameter(i)==0) continue; hptUnfold->SetBinContent(i+1,fabs(test->GetParameter(i))); hptUnfold->SetBinError(i+1,test->GetParError(i)); hptMC->SetBinContent(i+1,fabs(test2->GetParameter(i))); hptMC->SetBinError(i+1,test2->GetParError(i)); total+=fabs(test->GetParameter(i)); totalMC+=fabs(test2->GetParameter(i)); } hptUnfold->SetEntries(total); hptMC->SetEntries(totalMC); TCanvas *c3 = new TCanvas("c3","",600,600); hpt->Sumw2(); hptH->Sumw2(); //hptMC->Sumw2(); double normMC=0; double norm=0; double normTruth=0; hptUnfold->SetMarkerColor(2); hptUnfold->SetMarkerStyle(4); // hptUnfold->Scale(1./hptUnfold->GetEntries()); TH1F *hptCorrected = (TH1F*)hptUnfold->Clone(); hptCorrected->SetName("hptCorrected"); hptMC->Divide(hpt); hptCorrected->Divide(hptMC); for (int i=0;i<nPtBin;i++){ if (hptMC->GetBinContent(i)<=0.001)hptCorrected->SetBinContent(i,0); } hptCorrected->Scale(1./(hptCorrected->GetSum())); hptCorrected->SetMarkerStyle(20); hpt->Scale(1./hpt->GetEntries()); if (hptH->GetEntries())hptH->Scale(1./hptH->GetEntries()); hptTemp->SetXTitle("ln(P_{T}) GeV/c"); hptTemp->SetYTitle("Arbitrary Normalization"); hptTemp->Draw(); hptH->SetXTitle("ln(P_{T}) GeV/c"); hptH->SetYTitle("Arbitrary Normalization"); hptH->Draw("hist"); hptH->SetLineColor(4); hpt->Draw("hist same "); hptCorrected->Draw("same"); TH1F *hptUnfoldRatio = (TH1F*)hptUnfold->Clone(); hptUnfoldRatio->SetName("hptUnfoldRatio"); hptUnfoldRatio->Scale(1./hptUnfoldRatio->GetSum()); //hptUnfoldRatio->Divide(hptH); TH1F *hptCorrectedRatio = (TH1F*)hptCorrected->Clone(); hptCorrectedRatio->SetName("hptCorrectedRatio"); hptCorrectedRatio->SetMarkerColor(2); //hptCorrectedRatio->Divide(hptH); TCanvas *c4 = new TCanvas("c4","",600,600); TLine *l = new TLine(-2.5,1,2.5,1); hptUnfoldRatio->Draw(); hptMC->Draw("same"); hptCorrectedRatio->Draw("same"); l->Draw("same"); }
void canvas_write() { //just in case this script is executed multiple times delete gROOT->GetListOfFiles()->FindObject("hsimple.root"); delete gROOT->GetListOfCanvases()->FindObject("c1"); gBenchmark->Start("ntuple1"); // // Connect ROOT histogram/ntuple demonstration file // generated by example hsimple.C. TFile *f1 = new TFile("hsimple.root"); // // Create a canvas, with 4 pads // TCanvas *c1 = new TCanvas("c1","The Ntuple canvas",200,10,700,780); TPad *pad1 = new TPad("pad1","This is pad1",0.02,0.52,0.48,0.98,21); TPad *pad2 = new TPad("pad2","This is pad2",0.52,0.52,0.98,0.98,21); TPad *pad3 = new TPad("pad3","This is pad3",0.02,0.02,0.48,0.48,21); TPad *pad4 = new TPad("pad4","This is pad4",0.52,0.02,0.98,0.48,1); pad1->Draw(); pad2->Draw(); pad3->Draw(); pad4->Draw(); // // Change default style for the statistics box gStyle->SetStatW(0.30); gStyle->SetStatH(0.20); gStyle->SetStatColor(42); // // Display a function of one ntuple column imposing a condition // on another column. pad1->cd(); pad1->SetGrid(); pad1->SetLogy(); pad1->GetFrame()->SetFillColor(15); TNtuple *ntuple = (TNtuple*)f1->Get("ntuple"); ntuple->SetLineColor(1); ntuple->SetFillStyle(1001); ntuple->SetFillColor(45); ntuple->Draw("3*px+2","px**2+py**2>1"); ntuple->SetFillColor(38); ntuple->Draw("2*px+2","pz>2","same"); ntuple->SetFillColor(5); ntuple->Draw("1.3*px+2","(px^2+py^2>4) && py>0","same"); pad1->RedrawAxis(); // // Display the profile of two columns // The profile histogram produced is saved in the current directory with // the name hprofs pad2->cd(); pad2->SetGrid(); pad2->GetFrame()->SetFillColor(32); ntuple->Draw("pz:px>>hprofs","","goffprofs"); TProfile *hprofs = (TProfile*)gDirectory->Get("hprofs"); hprofs->SetMarkerColor(5); hprofs->SetMarkerSize(0.7); hprofs->SetMarkerStyle(21); hprofs->Fit("pol2"); // Get pointer to fitted function and modify its attributes TF1 *fpol2 = hprofs->GetFunction("pol2"); fpol2->SetLineWidth(4); fpol2->SetLineColor(2); // // Display a scatter plot of two columns with a selection. // Superimpose the result of another cut with a different marker color pad3->cd(); pad3->GetFrame()->SetFillColor(38); pad3->GetFrame()->SetBorderSize(8); ntuple->SetMarkerColor(1); ntuple->Draw("py:px","pz>1"); ntuple->SetMarkerColor(2); ntuple->Draw("py:px","pz<1","same"); // // Display a 3-D scatter plot of 3 columns. Superimpose a different selection. pad4->cd(); ntuple->Draw("pz:py:px","(pz<10 && pz>6)+(pz<4 && pz>3)"); ntuple->SetMarkerColor(4); ntuple->Draw("pz:py:px","pz<6 && pz>4","same"); ntuple->SetMarkerColor(5); ntuple->Draw("pz:py:px","pz<4 && pz>3","same"); TPaveText *l4 = new TPaveText(-0.9,0.5,0.9,0.95); l4->SetFillColor(42); l4->SetTextAlign(12); l4->AddText("You can interactively rotate this view in 2 ways:"); l4->AddText(" - With the RotateCube in clicking in this pad"); l4->AddText(" - Selecting View with x3d in the View menu"); l4->Draw(); // c1->cd(); c1->Update(); gStyle->SetStatColor(19); gBenchmark->Show("ntuple1"); TSQLFile* fsql1 = new TSQLFile(dbname, "recreate", username, userpass); if (fsql1->IsZombie()) { delete fsql1; return; } // changing TSQLFile configuration, you may improve speed // of reading or writing object to/from sql database // fsql1->SetUseSuffixes(kFALSE); // fsql1->SetArrayLimit(1000); // fsql1->SetUseIndexes(1); // fsql1->SetTablesType("ISAM"); // fsql1->SetUseTransactions(kFALSE); // Unncomment this line to see all SQL commands in log file // fsql1->StartLogFile("canvas.log"); gBenchmark->Start("writeSQL"); c1->Write("Canvas"); gBenchmark->Show("writeSQL"); delete fsql1; }
void TestEnergy() { TFile *file = TFile::Open("PPCollisionUps1sMilNoTune.root"); TFile *file2 = TFile::Open("PPCollisionMilNoTune.root"); TNtuple* PPTupleUps = (TNtuple*)file->Get("PPTuple"); TNtuple* PPTupleND = (TNtuple*)file2->Get("PPTuple"); TH1D* NCharUps = new TH1D("NCharUps", "Sum of Energy at mid rapdity", 30000, 0, 300); PPTupleUps->Draw("(ETmid-mu1pT-mu2pT)>>NCharUps", "NChar>2 && abs(deta1) < 1.93 && abs(deta2) < 1.93 && mu1pT > 4 && mu2pT > 4"); // NCharUps->Scale(3.35e-6); double sum, percent = 0, centAr[21]; int c, centa[21], i; sum = 0; centAr[0] = 180; centAr[20] = 0; c = 1; //Find Activity Ranges double min = 0, average[20], bins; i = 0; //Activity Range Calculations for Track Count TH1D* Tracks = new TH1D("Tracks", "Number of Tracks", 10000, 0, 300); PPTupleND->Draw("ETmid>>Tracks", "NChar > 0"); double MinBiasEvents; MinBiasEvents = Tracks->GetEntries(); NCharUps->Draw(); Tracks->Draw(); Tracks->Scale(1./Tracks->GetEntries()); int TrackCent[21]; percent = .02; TrackCent[0] = 300; TrackCent[20] = 0; c = 1; double Ranges[12]; int counter = 1; Ranges[0] = 0; //Loop To Get Activity Range Values for (i=0; percent <= .02; percent += .02) { sum = 0; cout << c << " "; for(i=0; sum < percent && i != 10000; i++) { sum += Tracks->GetBinContent(10000-i); } cout << 100*percent - 2 << "-" << 100*percent << "%" << " " << MinBiasEvents*sum << " " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values Ranges[counter] = sum; counter++; TrackCent[c] = Tracks->GetBinCenter(10000-i); c++;} percent = .08; for (i=0; percent <= .08; percent += .02) { sum = 0; cout << c << " "; for(i=0; sum < percent || percent == 1; i++) { sum += Tracks->GetBinContent(10000-i); } cout << 100*percent - 2 << "-" << 100*percent << "%" << " " << MinBiasEvents*sum << " " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values Ranges[counter] = sum; counter++; TrackCent[c] = Tracks->GetBinCenter(10000-i); c++;} percent = .20; for (i=0; percent <= .20; percent += .04) { sum = 0; cout << c << " "; for(i=0; sum < percent || percent == 1; i++) { sum += Tracks->GetBinContent(10000-i); } cout << 100*percent - 4 << "-" << 100*percent << "%" << " " << MinBiasEvents*sum << " " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values Ranges[counter] = sum; counter++; TrackCent[c] = Tracks->GetBinCenter(10000-i); c++;} percent = .30; // for (i=0; percent <= .30; percent += .05) { // sum = 0; // cout << c << "\n"; // for(i=0; sum < percent || percent == 1; i++) { // sum += Tracks->GetBinContent(10000-i); } // cout << 100*percent - 5 << "-" << 100*percent << "%" << " " << sum << " " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values // TrackCent[c] = Tracks->GetBinCenter(10000-i) + .5; // c++; } // percent = .40; for (i=0; percent <= 1; percent += .10) { sum = 0; cout << c << " "; for(i=0; sum <= percent && i != 10000; i++) { sum += Tracks->GetBinContent(10000-i); } cout << 100*percent - 10 << "-" << 100*percent << "%" << " " << MinBiasEvents*sum << " " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values Ranges[counter] = sum; counter++; TrackCent[c] = Tracks->GetBinCenter(10000-i); c++; } cout << "\n" << "Activity Range Values from Array" << "\n"; for(c = 0; c < 11; c++) { cout << c << ") " << TrackCent[c] << "\n"; } min = 0; double TrackAverage[20]; cout << "\n" << NCharUps->GetBinCenter(30000) << "\n"; i = 0; double TotalUps = 0; //cout << "\n" << "Activity Bin Averages" << "\n"; //Loop To Get Average In Each Activity Region for(c = 0; NCharUps->GetBinCenter(30000-i) > TrackCent[c+1] && NCharUps->GetBinCenter(30000-i) <= TrackCent[c]; c++) { sum = 0; bins = 0; for(i = min; (NCharUps->GetBinCenter(30000-i) > TrackCent[c+1] && NCharUps->GetBinCenter(30000-i) <= TrackCent[c]) && i != 30000; i++) { sum += NCharUps->GetBinContent(30000-i)*(NCharUps->GetBinCenter(30000-i)); bins += NCharUps->GetBinContent(30000-i); } TrackAverage[c] = sum/bins; TotalUps += bins; cout << "Point " << c << ": " << bins << " +- " << sqrt(bins) << " Upsilons" << "\n"; min = i; } cout << NCharUps->GetBinCenter(100) << "\n"; // cout << 10*c << "-" << 10*(c+1) << "%" << " " << TrackAverage[c] << "\n"; } cout << "Total number of Upsilons: " << TotalUps << "\n"; cout << "\n" << "Corrected X/Y Track values" << "\n"; double TrackYpoints[20]; for(i = 0; i < 12; i++) { cout << (Ranges[i+1] - Ranges[i])*MinBiasEvents << "\n"; } //Take Average Values and Divide by ND Average to Get X points // for(c = 0; c < 4; c++) { // TrackAverage[c] = TrackAverage[c]/Tracks->GetMean(); // TrackYpoints[c] = (50./NCharUps->Integral(0,25000))*NCharUps->Integral(TrackCent[c+1], TrackCent[c]-1 ); // cout << "(" <<TrackAverage[c] << "," << TrackYpoints[c] << ")" << "\n"; } //for(c = 4; c < 7; c++) { // TrackAverage[c] = TrackAverage[c]/Tracks->GetMean(); // TrackYpoints[c] = (25./NCharUps->Integral(0,25000))*NCharUps->Integral(TrackCent[c+1], TrackCent[c]-1 ); // cout << "(" <<TrackAverage[c] << "," << TrackYpoints[c] << ")" << "\n"; } // for(c = 7; c < 10; c++) { // TrackAverage[c] = TrackAverage[c]/Tracks->GetMean(); // TrackYpoints[c] = (20./NCharUps->Integral(0,25000))*NCharUps->Integral(TrackCent[c+1], TrackCent[c]-1 ); // cout << "(" <<TrackAverage[c] << "," << TrackYpoints[c] << ")" << "\n"; } TrackAverage[0] = TrackAverage[0]/Tracks->GetMean(); TrackYpoints[0] = (50./NCharUps->Integral(0,30000))*NCharUps->Integral(100*TrackCent[1], 100*(TrackCent[0]-1) ); cout << "(" <<TrackAverage[0] << "," << TrackYpoints[0] << ")" << "\n"; TrackAverage[1] = TrackAverage[1]/Tracks->GetMean(); TrackYpoints[1] = (16.67/NCharUps->Integral(0,30000))*NCharUps->Integral(100*TrackCent[2], 100*TrackCent[1]-100 ); cout << "(" <<TrackAverage[1] << "," << TrackYpoints[1] << ")" << "\n"; TrackAverage[2] = TrackAverage[2]/Tracks->GetMean(); TrackYpoints[2] = (8.33/NCharUps->Integral(0,30000))*NCharUps->Integral(100*TrackCent[3], 100*TrackCent[2]-100 ); cout << "(" <<TrackAverage[2] << "," << TrackYpoints[2] << ")" << "\n"; for(c = 3; c < 14; c++) { TrackAverage[c] = TrackAverage[c]/Tracks->GetMean(); TrackYpoints[c] = (10./NCharUps->Integral(0,30000))*NCharUps->Integral(100*TrackCent[c+1], 100*TrackCent[c]-100 ); cout << "(" <<TrackAverage[c] << "," << TrackYpoints[c] << ")" << "\n"; } TF1* line = new TF1("line", "x", 0, 4.5); TF1* line2 = new TF1("line2", "1.8*x", 0, 4.5); line2->SetLineColor(kWhite); sum = 0; double scaledSumE = 0, scaleSumT = 0; scaleSumT = NCharUps->Integral(0,30000); TCanvas* can2 = new TCanvas("can2", "Centrality"); can2->cd(); line->SetLineColor(1); line2->GetYaxis()->SetTitle("#varUpsilon(1S)/<#varUpsilon(1S)>"); line2->GetXaxis()->SetTitle("#Sigma E_{T}^{|#eta| < 2.4}/<#Sigma E_{E}^{|#eta| < 2.4}>"); line2->SetTitle("#varUpsilon(1S) Cross Section vs Track Multiplicity"); line2->Draw(); line->SetLineStyle(3); line->Draw("same"); for(c = 0; c < 18; c++) { cout << TrackCent[c] << " Bin Average: " << 10.32*TrackAverage[c] << "\n";} double Test, Testaverage, Testsum, Testbin, count = 0, TestY = 0; Test = NCharUps->Integral(38,100); for(i = 38; i < 100; i++) { Testsum += NCharUps->GetBinContent(i)*NCharUps->GetBinCenter(i); Testbin += NCharUps->GetBinContent(i); } Testaverage = Testsum/Testbin; TestY = (10./NCharUps->Integral(0,30000))*NCharUps->Integral(38, 100); cout << "\n" << "\n" << TestY << "\n" << "\n"; TH1D* modelT = new TH1D("modelT", "Pythia model", 5000, 0, 5); //Fill Histogram with points from Model for(i = 0; i < 20; i++) { //Track Values modelT->SetBinContent(1000*TrackAverage[i], TrackYpoints[i]); modelT->SetBinError(1000*TrackAverage[i], .01); } modelT->SetMarkerStyle(20); modelT->SetMarkerColor(kBlue); modelT->SetLineColor(kBlue); modelT->Draw("sameE"); //Histogram for STAR Data Points TH1D* data = new TH1D("data", "CMS Data", 4000, 0, 4); data->SetMarkerStyle(20); data->SetMarkerColor(kRed); data->SetLineColor(kRed); data->SetBinContent(3262, 6.67); data->SetBinError(3262, .26); data->SetBinContent(2010, 3.12); data->SetBinError(2010, .15); data->SetBinContent(1240, 1.4); data->SetBinError(1240, .06); data->SetBinContent(630, .240); data->SetBinError(630, .01); data->Draw("sameE"); TLegend* leg = new TLegend(.1,.74,.30,.9); leg->SetHeader("For |#eta| < 2.4"); leg->AddEntry(modelT->DrawCopy("same"), "Pythia 8 Model", "l"); leg->AddEntry(data->DrawCopy("same"), "CMS data", "l"); leg->Draw("same"); return; }
int main( int argc, char* argv[] ) { cout << endl; cout << "\t8888888b. d8b 888 8888888b. 888 888 " << endl; cout << "\t888 Y88b Y8P 888 888 Y88b 888 888 " << endl; cout << "\t888 888 888 888 888 888 888 " << endl; cout << "\t888 d88P 8888b. 88888b. 888 .d88888 888 d88P 888 .d88b. 888888 " << endl; cout << "\t8888888P\" \"88b 888 \"88b 888 d88\" 888 8888888P\" 888 d88\"\"88b 888 " << endl; cout << "\t888 T88b .d888888 888 888 888 888 888 888 888 888 888 888 " << endl; cout << "\t888 T88b 888 888 888 d88P 888 Y88b 888 888 888 Y88..88P Y88b. " << endl; cout << "\t888 T88b \"Y888888 88888P\" 888 \"Y88888 888 888 \"Y88P\" \"Y888 " << endl; cout << "\t 888 " << endl; cout << "\t 888 " << endl; cout << "\t 888 " << endl; cout << endl << endl; cout << "Usage:" << endl; cout << "\t" << argv[0] << "\tSomeFile.root\t" << "phys_param1\tphys_param2\toutput_directory" << endl; cout << endl << "\teg:\t" << argv[0] << "\tLLcontourData.root\tdeltaGamma\tPhi_s\toutputdir"<<endl; cout << endl; cout << "6th (Optional) Option:"<<endl; cout << "\t\t\tCV\t\t(Plot the CV of 'nuisence' Physics Parameters)"<<endl; cout << "\t\t\tRelCV\t\t(Plot the variation in the CV of the 'nuisence' Physics Parameters)"<<endl; cout << "\t\t\tExtraCV\t\t(Plot all of the CV, errors and pulls for each 'nuisence' Physics Parameter)"<<endl; cout << "\t\t\tNOFC\t\t(Don't process FC data in a file if any is there)"<<endl; cout << endl; if( (argc != 5) && (argc != 6) ) exit(-1); // Use UUID based seed from ROOT, just used for unique identification of ROOT objects TRandom3* rand_gen = new TRandom3(0); // Setup the Canvas and such EdStyle* RapidFit_Style = new EdStyle(); RapidFit_Style->SetStyle(); // By Design TString outputdir = argv[4]; TString param1string = argv[2]; TString param2string = argv[3]; // Make OutputDir gSystem->mkdir( outputdir ); // Open the File TFile * input = TFile::Open( argv[1] ); TNtuple* allresults; input->GetObject("RapidFitResult", allresults); if(!allresults){ input->GetObject("RapidFitResult/RapidFitResult",allresults); if(!allresults){ cout << "Couldn't find ntuple RapidFitResult in TFile" << endl; exit(1); } } // Switches for different plotting bool CV_Drift = false; bool Want_Physics_Params=false; bool Want_Extra_Physics_Param_Info=false; bool want_FC = true; bool high_res = true; // False method may only call plot fully once... still in development if( argc == 6 ) { if( string(argv[5]) == "CV" ) Want_Physics_Params = true; if( string(argv[5]) == "RelCV" ) { Want_Physics_Params = true; CV_Drift = true; } if( string(argv[5]) == "ExtraCV" ) { Want_Physics_Params = true; Want_Extra_Physics_Param_Info = true; } if( string(argv[5]) == "NOFC" ) want_FC = false; } // Strings that are universally defined TString Double_Tolerance="0.000001"; TString Fit_Status = "Fit_Status"; TString NLL = "NLL"; TString notgen = "-9999."; TString error_suffix = "_error"; TString value_suffix = "_value"; TString pull_suffix = "_pull"; TString gen_suffix = "_gen"; TString Copy_Option = "fast"; // Strings that are relevent to this plot // This is currently given by the user, but in time we can write an algorithm to determine this TString param1_gen = param1string + gen_suffix; TString param1_val = param1string + value_suffix; TString param1_err = param1string + error_suffix; TString param2_gen = param2string + gen_suffix; TString param2_val = param2string + value_suffix; TString param2_err = param2string + error_suffix; // Get a list of ALL parameters within the file, this is given for free in the algorithms I wrote above // Get a list of all branches in allresults vector<TString> all_parameters = get_branch_names( allresults ); // Get a list of all branches in allresults with '_value' in their name vector<TString> all_parameter_values = filter_names( all_parameters, value_suffix ); vector<TString> all_parameter_errors = filter_names( all_parameters, error_suffix ); vector<TString> all_parameter_pulls = filter_names( all_parameters, pull_suffix ); // Now to read in the Global Minima // Store the Global fit corrdinate and value Float_t nll=0, Global_Best_NLL=0, x_point=0, y_point=0; // Store the value of the 'nuisence' parameters as well Float_t* best_fit_values = new Float_t[all_parameter_values.size()]; // Construct an array to hold the best values for the rest of the parameters Float_t* best_fit_temp_values = new Float_t[all_parameter_values.size()]; allresults->SetBranchAddress(NLL,&nll); // Tell ROOT where to store the values for( unsigned short int i=0; i < all_parameter_values.size(); ++i ) { allresults->SetBranchAddress(all_parameter_values[i],&best_fit_temp_values[i]); } // Actually store the values in resident memory of the program cout << endl << "BEST FIT RESULTS AS DETERMINED FROM THE STANDARD FIT:" << endl; allresults->GetEntry(0); Global_Best_NLL = nll; for( unsigned short int i=0; i < all_parameter_values.size(); ++i ) { cout << all_parameter_values[i] << ":\t" << best_fit_temp_values[i] << endl; best_fit_values[i] = best_fit_temp_values[i]; if( string(all_parameter_values[i].Data()).compare(param1_val.Data()) == 0 ) x_point = best_fit_temp_values[i]; if( string(all_parameter_values[i].Data()).compare(param2_val.Data()) == 0 ) y_point = best_fit_temp_values[i]; } cout << endl; // General Cuts to be applied for various plots // Fit_Status == 3 TString Fit_Cut = "(abs(" + Fit_Status + "-3.0)<"+Double_Tolerance+")"; // param1_gen == notgen && param1_err == 0 TString Param_1_Cut = "(abs(" + param1_gen + "-" + notgen +")<" + Double_Tolerance + ")&&(abs("+ param1_err + "-0.0)<"+ Double_Tolerance + ")"; // param2_gen == notgen && param2_err == 0 TString Param_2_Cut = "(abs(" + param2_gen + "-" + notgen + ")<"+ Double_Tolerance + ")&&(abs(" +param2_err +"-0.0)<" + Double_Tolerance + ")"; // Combine the individual Cuts TString Fit_Cut_String = Param_1_Cut + "&&" + Param_2_Cut + "&&" + Fit_Cut; // Toys have a defined generation Value, Fits to Data DO NOT // param1_gen != notgen TString p1isatoy = "(abs(" + param1_gen + "-" + notgen + ")>" + Double_Tolerance + ")"; // param2_gen != notgen TString p2isatoy = "(abs(" + param2_gen + "-" + notgen + ")>" + Double_Tolerance + ")"; // Combine the individual Cuts TString Toy_Cut_String = p1isatoy + "&&" + p2isatoy; // Check for Toys in the file and wether I should run the FC code allresults->Draw( NLL, Toy_Cut_String, "goff" ); bool Has_Toys = allresults->GetSelectedRows() > 0; cout << endl << "NUMBER OF TOYS IN FILE:\t" << allresults->GetSelectedRows() << endl; if( int(allresults->GetEntries() - allresults->GetSelectedRows()) == 0 ) { cerr << "SERIOUS ERROR:\tSOMETHING HAS REALLY GOTTEN SCREWED UP!" << endl; exit(-3498); } // Fit values for the global fit are now stored in: // // Global_Best_NLL, best_fit_values, x_point, y_point // Tell the user cout << "GLOBAL DATA BEST FIT NLL:\t" << setprecision(10) << Global_Best_NLL << "\tAT:\tX:" << setprecision(10) << x_point << "\tY:\t" <<setprecision(10)<< y_point << endl; // Check wether the minima as defined from the Global fit is the true minima within the phase-space //Check_Minima( allresults, Fit_Cut_String, &Global_Best_NLL, NLL, Double_Tolerance, param1_val, param2_val ); TString NLL_Min; // Of course ROOT doesn't have USEFUL constructors! NLL_Min+=Global_Best_NLL; // Plot the distribution of successfully fitted grid points for the PLL scan // NB: For FC this will likely saturate due to multiple layers of fits cout << endl << "FOUND UNIQUE GRID POINTS, PLOTTING" << endl; LL2D_Grid( allresults, Fit_Cut_String, param1string, param2string, rand_gen, "LL", outputdir ); // Construct a plot string for the NLL plot and plot it // PLL part of Draw_String TString PLL = "(" + NLL + "-" + NLL_Min + ")"; // Gridding part of Draw_String TString Param1_Param2 = ":" + param1_val + ":" + param2_val; // Draw String for PLL TString NLL_DrawString = PLL + Param1_Param2; cout << endl << "PLOTTING NLL VARIATION" << endl; // PLL plot TH2* pllhist=NULL; TGraph2D* pllgraph=NULL; if( high_res ) { pllhist = Plot_From_Cut( allresults, NLL_DrawString, Fit_Cut_String, rand_gen, param1string, param2string ); } else { pllgraph = Plot_From_Cut_lo( allresults, NLL_DrawString, Fit_Cut_String, rand_gen, param1string, param2string ); } // Array storing the addresses of all of the Physics Plots still in memory TH2** All_Physics_Plots = new TH2*[all_parameter_values.size()]; TH2** All_Physics_Errors = new TH2*[all_parameter_values.size()]; TH2** All_Physics_Pulls = new TH2*[all_parameter_values.size()]; // Making use of switch if( Want_Physics_Params ) { // Physics Plots Physics_Plots( all_parameter_values, best_fit_values, allresults, rand_gen, Param1_Param2, CV_Drift, All_Physics_Plots, Fit_Cut_String); cout << endl << "Finalising CV Plots" << endl << endl; Finalize_Physics_Plots( All_Physics_Plots, all_parameter_values, param1string, param2string, outputdir, CV_Drift ); if( Want_Extra_Physics_Param_Info ) { // Physics Plots // // Passing false as Highly unlikely that I will 'ever' want to watch error/pull drift rather than the absolute value Float_t* null_pointer=NULL; Physics_Plots( all_parameter_errors, null_pointer, allresults, rand_gen, Param1_Param2, false, All_Physics_Errors, Fit_Cut_String); Physics_Plots( all_parameter_pulls, null_pointer, allresults, rand_gen, Param1_Param2, false, All_Physics_Pulls, Fit_Cut_String); cout << endl << "Finalising Extra CV Plots" << endl << endl; Finalize_Physics_Plots( All_Physics_Errors, all_parameter_errors, param1string, param2string, outputdir, false ); Finalize_Physics_Plots( All_Physics_Pulls, all_parameter_pulls, param1string, param2string, outputdir, false ); } } TFile* new_FC_Output = NULL; TTree* FC_Output = new TTree( "FC_Output", "FC_Output" );; TH2* FC_Plot = NULL; // Making use of switch if( Has_Toys && want_FC ) { // FC Plot cout << "FOUND TOYS IN FILE, PLOTTING FC" <<endl; TString FC_Tuple_File( outputdir+ "/FC_Tuple.root" ); new_FC_Output = new TFile( FC_Tuple_File, "RECREATE" ); FC_Plot = FC_TOYS( allresults, Fit_Cut_String, param1string, param2string, NLL, Fit_Cut, Global_Best_NLL, FC_Output, Double_Tolerance, rand_gen ); FC_Output->Write(); //LL2D_Grid( FC_Output, Fit_Cut, param1_val, param2_val, rand_gen, "FC" ); } // Contours to be used in plotting int cont_num = 3; double* pllconts = new double[unsigned(cont_num)]; pllconts[0] = 1.15; pllconts[1] = 2.36; pllconts[2] = 3.0;// pllconts[3] = 4.61; double* fcconts = new double[unsigned(cont_num)]; fcconts[0] = 0.68; fcconts[1] = 0.9; fcconts[2] = 0.95;// fcconts[3] = 0.99; double* confs = new double[unsigned(cont_num)]; confs[0] = 68.0; confs[1] = 90.0; confs[2] = 95.0;// confs[3] = 99.0; cout <<endl<< "SAVING GRAPHS" << endl; if( high_res ) { Plot_Styled_Contour( pllhist, cont_num, pllconts, confs, outputdir, "Likelihood Profile" ); } else { //Plot_Styled_Contour2( pllgraph, cont_num, pllconts, confs, outputdir, "Likelihood Profile" ); } if( Has_Toys && want_FC ) // If FC was generated { // Thinking of implementing a PLL Plot for the FC as it's easier to plot that (and looks more impressive) //TH2* FC_PLL = Invert_PLL( FC_Plot ); Plot_Styled_Contour( FC_Plot, cont_num, fcconts, confs, outputdir, "FeldmanCousins Profile" ); //Plot_Styled_Contour( FC_PLL, cont_num, fcconts, confs, outputdir, "FeldmanCousins Profile PLL" ); //TString FC_Tuple_File( outputdir+ "FC_Tuple.root" ); //TFile* new_FC_Output = new TFile( FC_Tuple_File, "RECREATE" ); //FC_Output->Write(); Plot_Both( pllhist, FC_Plot, cont_num, fcconts, pllconts, confs, outputdir ); FC_Stats( FC_Output, param1string, param2string, rand_gen, outputdir ); if( new_FC_Output != NULL ) new_FC_Output->Close(); } return 0; }
void PFcorr(bool isMC=false) { gStyle->SetOptStat(0); gStyle->SetTitleOffset(1.8,"Y"); TString filename = "../test/pftuple"; if(isMC) filename += "MC"; filename += ".root"; TFile *f = new TFile(filename.Data()); TNtuple *nt = (TNtuple*) f->Get("pfCandidateAnalyzer/nt"); TCanvas *c1 = new TCanvas("c1","c1",800,800); c1->Divide(2,2); TString hadron = "tkptmax>10"; //hadron += " && type==1"; nt->SetAlias("trksel","(algo<=7 && nhits>=5 && relpterr<=0.05 && abs(nd0)<3 && abs(ndz)<3)"); TString seltrk = " && trksel"; TString fakehadron = hadron + " && fake"; Float_t axisrange=500.; if(!isMC) axisrange=350.; c1->cd(1); nt->Draw(Form("tkptsum:eetsum+hetsum>>h1(50,0,%f,50,0,%f)",axisrange,axisrange),hadron.Data(),"goff"); h1->SetTitle("PF candidate with p_{T}>10 GeV/c track element; PF calo cluster E_{T} sum (ECAL+HCAL); Track p_{T} sum"); h1->Draw("colz"); if(isMC) { nt->Draw(Form("tkptsum:eetsum+hetsum>>h1f(50,0,%f,50,0,%f)",axisrange,axisrange),fakehadron.Data(),"goff"); TH2F* h1 = h1; h1f->Divide(h1); h1f->Scale(100.); h1f->Draw("boxsame"); } gPad->SetLogz(); c1->cd(2); nt->Draw(Form("tkptsum:eetsum+hetsum>>h2(50,0,%f,50,0,%f)",axisrange,axisrange),(hadron+seltrk).Data(),"goff"); h2->SetTitle("PF candidate with p_{T}>10 GeV/c track element; PF calo cluster E_{T} sum (ECAL+HCAL); SELECTED Track p_{T} sum"); h2->Draw("colz"); if(isMC) { nt->Draw(Form("tkptsum:eetsum+hetsum>>h2f(50,0,%f,50,0,%f)",axisrange,axisrange),(fakehadron+seltrk).Data(),"goff"); h2f->Draw("boxsame"); } gPad->SetLogz(); c1->cd(3); nt->Draw(Form("tkptmax:eetsum+hetsum>>h3(50,0,%f,50,0,%f)",axisrange,axisrange),hadron.Data(),"goff"); h3->SetTitle("PF candidate with p_{T}>10 GeV/c track element; PF calo cluster E_{T} sum (ECAL+HCAL); Track with MAX p_{T}"); h3->Draw("colz"); if(isMC) { nt->Draw(Form("tkptmax:eetsum+hetsum>>h3f(50,0,%f,50,0,%f)",axisrange,axisrange),fakehadron.Data(),"goff"); h3f->Draw("boxsame"); } gPad->SetLogz(); c1->cd(4); nt->Draw(Form("tkptmax:eetsum+hetsum>>h4(50,0,%f,50,0,%f)",axisrange,axisrange),(hadron+seltrk).Data(),"goff"); h4->SetTitle("PF candidate with p_{T}>10 GeV/c track element; PF calo cluster E_{T} sum (ECAL+HCAL); SELECTED Track with MAX p_{T}"); h4->Draw("colz"); if(isMC) { nt->Draw(Form("tkptmax:eetsum+hetsum>>h4f(50,0,%f,50,0,%f)",axisrange,axisrange),(fakehadron+seltrk).Data(),"goff"); h4f->Draw("boxsame"); } gPad->SetLogz(); }
void parallelcoordtrans() { Double_t x,y,z,u,v,w,a,b,c; Double_t s1x, s1y, s1z; Double_t s2x, s2y, s2z; Double_t s3x, s3y, s3z; r = new TRandom();; TCanvas *c1 = new TCanvas("c1", "c1",0,0,900,1000); c1->Divide(1,2); if (gVirtualX && !gVirtualX->InheritsFrom("TGCocoa")) { std::cout<<"This macro works only on MacOS X with --enable-cocoa\n"; delete c1; delete r; return; } TNtuple *nt = new TNtuple("nt","Demo ntuple","x:y:z:u:v:w:a:b:c"); int n=0; for (Int_t i=0; i<1500; i++) { r->Sphere(s1x, s1y, s1z, 0.1); r->Sphere(s2x, s2y, s2z, 0.2); r->Sphere(s3x, s3y, s3z, 0.05); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, r7, r8, r9); n++; generate_random(i); nt->Fill(s1x, s1y, s1z, s2x, s2y, s2z, r7, r8, r9); n++; generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, r7, s3y, r9); n++; generate_random(i); nt->Fill(s2x-1, s2y-1, s2z, s1x+.5, s1y+.5, s1z+.5, r7, r8, r9); n++; generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, r7, r8, r9); n++; generate_random(i); nt->Fill(s1x+1, s1y+1, s1z+1, s3x-2, s3y-2, s3z-2, r7, r8, r9); n++; generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, s3x, r8, s3z ); n++; } TParallelCoordVar* pcv; c1->cd(1); // ||-Coord plot without transparency nt->Draw("x:y:z:u:v:w:a:b:c","","para"); TParallelCoord* para1 = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord"); para1->SetLineColor(25); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("x"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("y"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("z"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("a"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("b"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("c"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("u"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("v"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("w"); pcv->SetHistogramHeight(0.); // ||-Coord plot with transparency TColor *col26 = gROOT->GetColor(26); col26->SetAlpha(0.01); c1->cd(2); nt->Draw("x:y:z:u:v:w:a:b:c","","para"); TParallelCoord* para2 = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord"); para2->SetLineColor(26); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("x"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("y"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("z"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("a"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("b"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("c"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("u"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("v"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("w"); pcv->SetHistogramHeight(0.); }
void ntuple1() { //Small tree analysis script // To see the output of this macro, click begin_html <a href="gif/ntuple1.gif">here</a> end_html //Author:: Rene Brun //just in case this script is executed multiple times delete gROOT->GetListOfFiles()->FindObject("hsimple.root"); delete gROOT->GetListOfCanvases()->FindObject("c1"); gBenchmark->Start("ntuple1"); // // Connect ROOT histogram/ntuple demonstration file // generated by example $ROOTSYS/tutorials/hsimple.C. TFile *f1 = TFile::Open("hsimple.root"); if (!f1) return; // // Create a canvas, with 4 pads // TCanvas *c1 = new TCanvas("c1","The Ntuple canvas",200,10,700,780); TPad *pad1 = new TPad("pad1","This is pad1",0.02,0.52,0.48,0.98,21); TPad *pad2 = new TPad("pad2","This is pad2",0.52,0.52,0.98,0.98,21); TPad *pad3 = new TPad("pad3","This is pad3",0.02,0.02,0.48,0.48,21); TPad *pad4 = new TPad("pad4","This is pad4",0.52,0.02,0.98,0.48,1); pad1->Draw(); pad2->Draw(); pad3->Draw(); pad4->Draw(); // // Change default style for the statistics box gStyle->SetStatW(0.30); gStyle->SetStatH(0.20); gStyle->SetStatColor(42); // // Display a function of one ntuple column imposing a condition // on another column. pad1->cd(); pad1->SetGrid(); pad1->SetLogy(); pad1->GetFrame()->SetFillColor(15); TNtuple *ntuple = (TNtuple*)f1->Get("ntuple"); ntuple->SetLineColor(1); ntuple->SetFillStyle(1001); ntuple->SetFillColor(45); ntuple->Draw("3*px+2","px**2+py**2>1"); ntuple->SetFillColor(38); ntuple->Draw("2*px+2","pz>2","same"); ntuple->SetFillColor(5); ntuple->Draw("1.3*px+2","(px^2+py^2>4) && py>0","same"); pad1->RedrawAxis(); // // Display the profile of two columns // The profile histogram produced is saved in the current directory with // the name hprofs pad2->cd(); pad2->SetGrid(); pad2->GetFrame()->SetFillColor(32); ntuple->Draw("pz:px>>hprofs","","goffprofs"); TProfile *hprofs = (TProfile*)gDirectory->Get("hprofs"); hprofs->SetMarkerColor(5); hprofs->SetMarkerSize(0.7); hprofs->SetMarkerStyle(21); hprofs->Fit("pol2"); // Get pointer to fitted function and modify its attributes TF1 *fpol2 = hprofs->GetFunction("pol2"); fpol2->SetLineWidth(4); fpol2->SetLineColor(2); // // Display a scatter plot of two columns with a selection. // Superimpose the result of another cut with a different marker color pad3->cd(); pad3->GetFrame()->SetFillColor(38); pad3->GetFrame()->SetBorderSize(8); ntuple->SetMarkerColor(1); ntuple->Draw("py:px","pz>1"); ntuple->SetMarkerColor(2); ntuple->Draw("py:px","pz<1","same"); // // Display a 3-D scatter plot of 3 columns. Superimpose a different selection. pad4->cd(); ntuple->Draw("pz:py:px","(pz<10 && pz>6)+(pz<4 && pz>3)"); ntuple->SetMarkerColor(4); ntuple->Draw("pz:py:px","pz<6 && pz>4","same"); ntuple->SetMarkerColor(5); ntuple->Draw("pz:py:px","pz<4 && pz>3","same"); TPaveText *l4 = new TPaveText(-0.9,0.5,0.9,0.95); l4->SetFillColor(42); l4->SetTextAlign(12); l4->AddText("You can interactively rotate this view in 2 ways:"); l4->AddText(" - With the RotateCube in clicking in this pad"); l4->AddText(" - Selecting View with x3d in the View menu"); l4->Draw(); // c1->cd(); c1->Update(); gStyle->SetStatColor(19); gBenchmark->Show("ntuple1"); }
void doFit_asymptotic(int which = 2, int numCat = 5, /*double splitVal1 = 0.54, double splitVal2 = 0.92, double splitVal3 = 0.865, double splitVal4 = 0, double splitVal5 = 0.71,*/ /*double splitVal1 = 0.89, double splitVal2 = 0.72, double splitVal3 = 0.55, double splitVal4 = 0.05, double splitVal5 = -100,*/ double splitVal1 = 0.05, double splitVal2 = 0.55, double splitVal3 = 0.74, double splitVal4 = 0.89, double splitVal5 = -100, //TString fileName = "appOutput_SM_Oct14.root", //TString modelDir = "/afs/cern.ch/user/f/fabstoec/scratch0/optimizeMVACats/MVAmodel/" //TString fileName = "Tmva_AppOutput_SMDipho_2012Jan16_wrongBR.root", //TString fileName = "Tmva_AppOutput_SMDipho_2012Jan16.root", //TString fileName = "Tmva_AppOutput_SMDipho_2012Jan16_NewVBF.root", //TString fileName = "Tmva_AppOutput_SMDipho_2012Jan16_NewVBF_CorrScaleFactor.root", TString fileName = "Tmva_AppOutput_SMDipho_2012Jan16_NewVBF_120.root ", TString modelDir = "/afs/cern.ch/user/m/mingyang/optimizeMVACats/MVAmodel/" ) { if(numCat > 6) return;//set maximum number of categories //===============1.remove the printout from roofit========================= RooMsgService::instance().setSilentMode(true); RooMsgService::instance().getStream(1).removeTopic(RooFit::Caching); RooMsgService::instance().getStream(0).removeTopic(RooFit::Minimization); RooMsgService::instance().getStream(1).removeTopic(RooFit::Minimization); RooMsgService::instance().getStream(0).removeTopic(RooFit::Plotting); RooMsgService::instance().getStream(1).removeTopic(RooFit::Plotting); RooMsgService::instance().getStream(1).removeTopic(RooFit::Fitting); RooMsgService::instance().getStream(0).removeTopic(RooFit::Eval); RooMsgService::instance().getStream(1).removeTopic(RooFit::Eval); //============2.define nonfit variables========================== //--------input file------------------- TString modelName = modelDir+fileName; //--------cross section----- double theXS = 1.0; double maxXS = 10.0; //--------the signal strength modifier range ------ double muMin = 0.; double muMax = maxXS/theXS; double theMu = 0.;//set the initial value of Mu to 0 (background only hypothesis) //--------parameters-------------------------------- double nsig; double nbgini; double nbg; double exp; double nbg_update; double exp_update; //--------set up category bourndary variables-------- int startCat = 0; int endCat = numCat+1; double* catVals = new double[numCat+1];//ming:array of mva category cut values double allVals[7];//ming:all the boundary values allVals[0] = splitVal1; allVals[1] = splitVal2; allVals[2] = splitVal3; allVals[3] = splitVal4; allVals[4] = splitVal5; //allVals[5] = 1.; //allVals[6] = -0.5; allVals[5] = 1.; allVals[6] = -1; double allValsSorted[7]; for(int i=0; i<7; ++i) {//make allValsSorted increase with the order allValsSorted[i]=allVals[i]; int tSpot = i; for(int j = i-1; j>=0; --j) { if(allValsSorted[j] > allValsSorted[tSpot]) { // switch double tempVal = allValsSorted[j]; allValsSorted[j] = allValsSorted[tSpot]; allValsSorted[tSpot] = tempVal; tSpot--; } else break; } } for(int i=6-numCat; i<=6; ++i) catVals[i-6+numCat] = allValsSorted[i];//catVals from -1 to 1 increase with the order //==========3.read in the input tree============== TFile* modFile = new TFile(modelName.Data()); TNtuple* tup = (TNtuple*) modFile->FindObjectAny("MITMVAtuple"); //============fit============= //-----------set the independent variable---------------- RooRealVar* mass = new RooRealVar("mass","",100.,180.); mass->setRange(100.,180.); mass->setBins(10000,"cache");//bins for numrical integration mass->setBins(320);//bins for fitting and plotting //-----------set the variable to make dataset------------- RooRealVar* weight = new RooRealVar("weight","",0.,100.); RooRealVar* proc = new RooRealVar("proc" ,"",0.,10.); RooRealVar* mva = new RooRealVar("mva" ,"",-10.,10.); RooRealVar* vbftag = new RooRealVar("vbftag" ,"",0.,1.); //----------prepare the dataset--------------------------- TString* dataNames = new TString[numCat+1]; TString* sigNames = new TString[numCat+1]; RooDataHist** sigCat = new RooDataHist*[numCat+1]; RooDataSet** dataCat = new RooDataSet*[numCat+1]; RooDataHist** dataHCat = new RooDataHist*[numCat+1]; TString baseCut = "mass > 100 && mass < 180 "; TString baseBG = baseCut + TString(" && proc > 3 && proc < 11");//MC background TString baseSIG = baseCut + TString(" && proc < 4 ");//MC signal TString baseObsData = baseCut + TString(" && proc==11");//obs data for count int* numObsData= new int[numCat+1]; //----------prepare the pdf------------------------------- //signal model RooAbsPdf** sigpdfcat_part1 = new RooAbsPdf*[numCat+1]; RooAbsPdf** sigpdfcat_part2 = new RooAbsPdf*[numCat+1]; RooAbsPdf** sigpdfcat = new RooAbsPdf*[numCat+1]; RooRealVar** sigMean_part1 = new RooRealVar*[numCat+1]; RooRealVar** sigWidth_part1 = new RooRealVar*[numCat+1]; RooRealVar** sigMean_part2 = new RooRealVar*[numCat+1]; RooRealVar** sigWidth_part2 = new RooRealVar*[numCat+1]; RooRealVar** sigRatio = new RooRealVar*[numCat+1]; double* nominalSignal = new double[numCat+1]; TH1D** sigH = new TH1D*[numCat+1];//ming:used to get nominalSignal and input to RooDataHist TH1D** ObsDataH = new TH1D*[numCat+1];//obs data for count //background model //exp RooExponential** bgpdfcat_exp = new RooExponential*[numCat+1]; RooRealVar** bgpdfval_exp = new RooRealVar*[numCat+1]; //bs RooBernstein** bgpdfcat_bs = new RooBernstein*[numCat+1]; RooConstVar* bgpdfval0_bs = new RooConstVar; RooRealVar** bgpdfval1_bs = new RooRealVar*[numCat+1]; RooRealVar** bgpdfval2_bs = new RooRealVar*[numCat+1]; RooRealVar** bgpdfval3_bs = new RooRealVar*[numCat+1]; RooRealVar** bgpdfval4_bs = new RooRealVar*[numCat+1]; //total model RooAddPdf** totpdfcat = new RooAddPdf*[numCat+1]; RooRealVar** nsigcat = new RooRealVar*[numCat+1]; RooRealVar** nbgcat = new RooRealVar*[numCat+1]; //----------nll for the mu given the dataset--------------- RooNLLVar** totNllExt = new RooNLLVar*[numCat+1];//total Nll //--------draw option------------------ /*bool drawSigModel = false; bool drawBkgModel = false; bool draw95CLlimitModel = false; bool drawcan = false;*/ bool drawSigModel = true; bool drawBkgModel = true; bool draw95CLlimitModel = true; bool drawcan = false; RooPlot** frame = new RooPlot*[20];//define an array of pointer;frame[i] is a pointer TCanvas* thisCan = new TCanvas("thisCan","MyCanvas",1200,(numCat+1)*300); TCanvas* extraCan = new TCanvas("extraCan","extraCan",800,600); thisCan->Divide(3,numCat+1); gStyle->SetMarkerSize(0.5); //---------count option------------------ bool enableCount = true; //============category boundaries=============== std::stringstream mvaCut; std::stringstream mvaCutLabel; TString SIGstring; TString BGstring; TString ObsDatastring; for(int i=0; i<numCat+1; ++i) { if(i!= numCat) { mvaCut.str(""); mvaCut << " && mva > "<<catVals[i]<<" && mva < "<<catVals[i+1];//cut values for cat i std::cout<<mvaCut.str().c_str()<<std::endl; mvaCutLabel.str(""); mvaCutLabel << " mva > "<<catVals[i]<<" && mva < "<<catVals[i+1];//cut values for cat i } if(i== numCat) { mvaCutLabel.str(""); mvaCutLabel << " Dijet-TAG "; } //-----obsData for count----- //read in the obsdata mass hist for category i std::stringstream pSS; pSS.str(""); pSS << "ObsDataH" <<i; ObsDataH[i] = new TH1D(pSS.str().c_str(),"",320,100.,180.);//0.25 GeV per bin TString theDrawString0 = TString("mass>>")+TString(pSS.str().c_str()); if(i!=numCat){ ObsDatastring = baseObsData+TString(mvaCut.str().c_str())+TString(" && vbftag==0"); } if(i==numCat){ ObsDatastring = baseObsData+TString(" && vbftag==1 && mva>0.05"); } extraCan->cd(); tup->Draw(theDrawString0.Data(),ObsDatastring.Data()); numObsData[i] = ObsDataH[i]->GetEntries();//number of events in the signal mass hist //-----signal model----- //read in the signal mass hist for category i pSS.str(""); pSS << "sigH" <<i; sigH[i] = new TH1D(pSS.str().c_str(),"",320,100.,180.);//0.25 GeV per bin TString theDrawString = TString("mass>>")+TString(pSS.str().c_str()); //TString SIGstring = TString("weight*(")+baseSIG+TString(mvaCut.str().c_str())+TString(")");//signal cut along with cat cut if(i!=numCat){ SIGstring = TString("weight*(")+baseSIG+TString(mvaCut.str().c_str())+TString(" && vbftag==0")+TString(")"); } if(i==numCat){ SIGstring = TString("weight*(")+baseSIG+TString(" && vbftag==1")+TString(" && mva>0.05")+TString(")"); } extraCan->cd(); tup->Draw(theDrawString.Data(),SIGstring.Data()); //sigH[i] = (TH1D*)gPad->GetPrimitive(pSS.str().c_str()); nominalSignal[i] = sigH[i]->GetSumOfWeights();//number of events in the signal mass hist //obtain the signal RooDataHist to be fit for category i pSS.str(""); pSS << "sigdata" << i; sigNames[i] = TString(pSS.str().c_str()); sigCat[i] = new RooDataHist( sigNames[i].Data(),"",*mass,sigH[i]);//hist used to extract signal model for category i //set fit parameter pSS.str(""); pSS << "nsigcat" << i; nsigcat[i] = new RooRealVar(pSS.str().c_str(),"",0.);//initialize number of signal events nsigcat[i]->setVal(nominalSignal[i]*theMu);//set nsigcat[i] to constant pSS.str(""); pSS<<"sigMean_part1"<<i; sigMean_part1[i] = new RooRealVar(pSS.str().c_str(),"",125.,100.,180.); sigMean_part1[i] ->removeRange(); pSS.str(""); pSS<<"sigWidth_part1"<<i; sigWidth_part1[i] = new RooRealVar(pSS.str().c_str(),"",1.5,-5.,5.); sigWidth_part1[i] ->removeRange(); pSS.str(""); pSS<<"sigMean_part2"<<i; sigMean_part2[i] = new RooRealVar(pSS.str().c_str(),"",125.,100.,180.); sigMean_part2[i] ->removeRange(); pSS.str(""); pSS<<"sigWidth_part2"<<i; sigWidth_part2[i] = new RooRealVar(pSS.str().c_str(),"",2.5,-5.,5.); sigWidth_part2[i] ->removeRange(); pSS.str(""); pSS<<"sigRatio"<<i; sigRatio[i] = new RooRealVar(pSS.str().c_str(),"",0.5,0.1,2.); sigRatio[i]->removeRange(); //signal pdf pSS.str(""); pSS << "sigpdfcat_part1" << i; sigpdfcat_part1[i] = new RooGaussian ( pSS.str().c_str(),"",*mass,*sigMean_part1[i],*sigWidth_part1[i]); pSS.str(""); pSS << "sigpdfcat_part2" << i; sigpdfcat_part2[i] = new RooGaussian ( pSS.str().c_str(),"",*mass,*sigMean_part2[i],*sigWidth_part2[i]); pSS.str(""); pSS << "sigpdfcat" << i; sigpdfcat[i] = new RooAddPdf(pSS.str().c_str(),"",*sigpdfcat_part1[i],*sigpdfcat_part2[i],*sigRatio[i]);//ratio*s1+(1-ratio)*s2 //fit sigpdfcat[i]->fitTo(*sigCat[i]); //fix signal model parameters sigMean_part1[i] ->setConstant(); sigWidth_part1[i] ->setConstant(); sigMean_part2[i] ->setConstant(); sigWidth_part2[i] ->setConstant(); sigRatio[i] ->setConstant(); if( drawSigModel ) { frame[3*i+1]= mass->frame(); pSS.str(""); pSS << "125 GeV Higgs MC and Model (5.089 fb-1) "; frame[3*i+1]->SetTitle(pSS.str().c_str()); sigCat[i]->plotOn(frame[3*i+1]); sigpdfcat[i]->plotOn(frame[3*i+1]); thisCan->cd(3*i+1); frame[3*i+1]->Draw(); TLatex* text1=new TLatex(3.5,23.5,mvaCutLabel.str().c_str()); text1->SetNDC(); text1->SetTextAlign(13); text1->SetX(0.4);//(0.940); text1->SetY(0.8); text1->SetTextFont(42); text1->SetTextSize(0.065);// dflt=28 text1->Draw(); std::stringstream NSigLabel; NSigLabel.str(""); NSigLabel <<"NSig = "<<nominalSignal[i]; printf("nsig:%d:\n",nominalSignal[i]); TLatex* text2=new TLatex(3.5,23.5,NSigLabel.str().c_str()); text2->SetNDC(); text2->SetTextAlign(13); text2->SetX(0.4);//(0.940); text2->SetY(0.7); text2->SetTextFont(42); text2->SetTextSize(0.065);// dflt=28 text2->Draw(); } //-----background model----- //obtain the backgroud RooDataHist to be fit for category i pSS.str(""); pSS << "data_cat" << i; dataNames[i] = TString(pSS.str().c_str()); if(i!=numCat){ BGstring = baseBG +TString(mvaCut.str().c_str())+TString(" && vbftag==0"); } if(i==numCat){ BGstring = baseBG +TString(" && vbftag==1"); } dataCat[i] = new RooDataSet (dataNames[i].Data(),"",tup,RooArgSet(*mass,*weight,*proc,*mva,*vbftag),BGstring.Data(), "weight");//MC bkg dataset used to extract background model for cat i //set fit parameter and pdf pSS.str(""); pSS << "nbgcat" << i; nbgini=dataCat[i]->sumEntries(); nbgcat[i] = new RooRealVar(pSS.str().c_str(),"",nbgini,0,50000);//number of background events;initial value total number of events in the mc background dataset nbgcat[i]->removeRange(); switch(which){ case 1: { pSS.str(""); pSS << "e" <<i; bgpdfval_exp[i] = new RooRealVar(pSS.str().c_str(),"",0.,-100.,100.);//exponet parameter bgpdfval_exp[i]->removeRange(); pSS.str(""); pSS << "bgpdfcat_exp" << i; bgpdfcat_exp[i] = new RooExponential(pSS.str().c_str(),"",*mass,*bgpdfval_exp[i]); bgpdfcat_exp[i]->fitTo(*dataCat[i]); if( drawBkgModel ) { frame[3*i+2]= mass->frame(); pSS.str(""); //pSS << "MC Bkg Data And Model 4thBSPol (5.089 fb-1) "<<mvaCut.str().c_str(); pSS << "MC Bkg Data And Model exp"; frame[3*i+2]->SetTitle(pSS.str().c_str()); dataCat[i]->plotOn(frame[3*i+2]); bgpdfcat_exp[i]->plotOn(frame[3*i+2]); thisCan->cd(3*i+2); frame[3*i+2]->Draw(); std::stringstream NBkgLabel; NBkgLabel.str(""); NBkgLabel <<"NBkg = "<<nbgini; TLatex* text3=new TLatex(3.5,23.5,NBkgLabel.str().c_str()); text3->SetNDC(); text3->SetTextAlign(13); text3->SetX(0.6);//(0.940); text3->SetY(0.7); text3->SetTextFont(42); text3->SetTextSize(0.065);// dflt=28 text3->Draw(); } //-----geneate asimov dataset from background model----- pSS.str(""); pSS << "dataHCat" << i; dataHCat[i] = bgpdfcat_exp[i]->generateBinned(*mass,dataCat[i]->sumEntries(),RooFit::Asimov(),RooFit::Name(pSS.str().c_str())); //---to get the total pdf--- pSS.str(""); pSS << "totpdfcat" <<i; totpdfcat[i] = new RooAddPdf(pSS.str().c_str(),"",RooArgList(*sigpdfcat[i],*bgpdfcat_exp[i]),RooArgList(*nsigcat[i],*nbgcat[i]));//build the sig plus bkg model totpdfcat[i]->fitTo(*dataHCat[i],RooFit::Extended(true)); break; } case 2: { pSS.str(""); pSS << "c0"; bgpdfval0_bs= new RooConstVar(pSS.str().c_str(),"",1.0);//exponet parameter pSS.str(""); pSS << "c1" <<i; bgpdfval1_bs[i] = new RooRealVar(pSS.str().c_str(),"",0.,0,10000.);//exponet parameter //bgpdfval1_bs[i]->removeRange(); pSS.str(""); pSS << "c2" <<i; bgpdfval2_bs[i] = new RooRealVar(pSS.str().c_str(),"",0.,0,10000.);//exponet parameter //bgpdfval2_bs[i]->removeRange(); pSS.str(""); pSS << "c3" <<i; bgpdfval3_bs[i] = new RooRealVar(pSS.str().c_str(),"",0.,0.,10000.);//exponet parameter //bgpdfval3_bs[i]->removeRange(); pSS.str(""); pSS << "c4" <<i; bgpdfval4_bs[i] = new RooRealVar(pSS.str().c_str(),"",0.,0.,10000.);//exponet parameter //bgpdfval4_bs[i]->removeRange(); pSS.str(""); pSS << "bgpdfcat_bs" << i; bgpdfcat_bs[i] = new RooBernstein(pSS.str().c_str(),"",*mass,RooArgList(*bgpdfval0_bs,*bgpdfval1_bs[i],*bgpdfval2_bs[i],*bgpdfval3_bs[i],*bgpdfval4_bs[i])); bgpdfcat_bs[i]->fitTo(*dataCat[i]); //draw the sig RooDataHist and sig model if( drawBkgModel ) { frame[3*i+2]= mass->frame(); pSS.str(""); //pSS << "MC Bkg Data And Model 4thBSPol (5.089 fb-1) "<<mvaCut.str().c_str(); pSS << "MC Bkg Data And Model 4thBSPol"; frame[3*i+2]->SetTitle(pSS.str().c_str()); dataCat[i]->plotOn(frame[3*i+2]); bgpdfcat_bs[i]->plotOn(frame[3*i+2]); thisCan->cd(3*i+2); frame[3*i+2]->Draw(); std::stringstream NBkgLabel; NBkgLabel.str(""); NBkgLabel <<"NBkg = "<<nbgini; TLatex* text3=new TLatex(3.5,23.5,NBkgLabel.str().c_str()); text3->SetNDC(); text3->SetTextAlign(13); text3->SetX(0.6);//(0.940); text3->SetY(0.7); text3->SetTextFont(42); text3->SetTextSize(0.065);// dflt=28 text3->Draw(); } //-----geneate asimov dataset from background model----- pSS.str(""); pSS << "dataHCat" << i; dataHCat[i] = bgpdfcat_bs[i]->generateBinned(*mass,dataCat[i]->sumEntries(),RooFit::Asimov(),RooFit::Name(pSS.str().c_str())); //---to get the total pdf--- pSS.str(""); pSS << "totpdfcat" <<i; totpdfcat[i] = new RooAddPdf(pSS.str().c_str(),"",RooArgList(*sigpdfcat[i],*bgpdfcat_bs[i]),RooArgList(*nsigcat[i],*nbgcat[i]));//build the sig plus bkg model totpdfcat[i]->fitTo(*dataHCat[i],RooFit::Extended(true)); break; } } totNllExt[i] = (RooNLLVar*) totpdfcat[i]->createNLL(*dataHCat[i],RooFit::Extended(true));//calculate nll for each category } // ===========95% C.L.upper limit on theMu=========== //-----NLL for background only model theMu=0----- double minNll = 0.; for(int i=startCat; i<endCat; ++i) minNll += totNllExt[i]->getVal();//ming:the total Nll for theMu=0 (background only hypothesis) std::cout<<" start = "<<minNll<<std::endl; //-----Target NLL for 95% C.L.upper limit on theMu----- //double cl = 0.95; double targetNll = minNll + 1.92 ; //0.5*pow(ROOT::Math::normal_quantile(1.-0.5*(1.-cl),1.0), 2.); //-----set the tolerance for the 95% C.L.upper limit on theMu----- double tRelAcc = 0.001; double tAbsAcc = 0.0005; //-----initial value for the eErr and theMu----- double rErr = 0.5*(muMax - muMin); theMu = 0.5*(muMax + muMin); //-----interate theMu till the rErr is less than either absolute value 0.0005 or the relative error 0.001 while ( rErr > std::max(tRelAcc * theMu, tAbsAcc) ) { double nextNll = 0.; for(int i=startCat; i<endCat; ++i) { nsigcat[i]->setVal(nominalSignal[i]*theMu);//update nsigcat with new theMu totpdfcat[i]->fitTo(*dataHCat[i],RooFit::Extended(true));//refit the totpdfcat with updated theMu nextNll += totNllExt[i]->getVal();//totNllExt update with the totpdfcat std::cout<<" for mu="<<theMu<<" nll = "<<nextNll<<" ( "<<targetNll<<" )"<<std::endl; } if(nextNll < targetNll) muMin = theMu; else muMax = theMu; rErr = 0.5*(muMax - muMin); theMu = 0.5*(muMax + muMin); } double tR_XS = theMu *theXS;//ming: the 95% C.L.limit on signal strength modifier double tR_Er = rErr *theXS;//ming: the error on the limit std::cout<<std::endl<<"95% C.L. Limit Mu="<<setprecision(5)<<" [ RES ] ( "<<tR_XS<<" +- "<<tR_Er<<" ) x sigma (FP/SM)"<<std::endl; std::stringstream label95Mu; label95Mu.str(""); label95Mu << "95% C.L. Limit Mu="<<setprecision(5)<<tR_XS<<" +- "<<tR_Er; if(draw95CLlimitModel){ for(int i=startCat; i<endCat; ++i) { frame[3*i+3]= mass->frame(); std::stringstream pSS; pSS.str(""); pSS << "Asimov Data and 95CL limit Mu Model"; frame[3*i+3]->SetTitle(pSS.str().c_str()); dataHCat[i]->plotOn(frame[3*i+3]); totpdfcat[i]->plotOn(frame[3*i+3]); thisCan->cd(3*i+3); frame[3*i+3]->Draw(); TLatex* text4=new TLatex(3.5,23.5,label95Mu.str().c_str()); text4->SetNDC(); text4->SetTextAlign(13); text4->SetX(0.2);//(0.940); text4->SetY(0.8); text4->SetTextFont(42); text4->SetTextSize(0.065);// dflt=28 text4->Draw(); } } if(drawcan){ std::stringstream CanName; CanName.str(""); CanName << "/afs/cern.ch/user/m/mingyang/optimizeMVACats/plot/"<<numCat<<"cat_95CLlimitMu_"<<setprecision(5)<<tR_XS<<".eps"; thisCan->SaveAs(CanName.str().c_str()); } for(int i=0; i<numCat+1; ++i){ if(enableCount){ printf("cat:%d NumObsData:%d\n",i,numObsData[i]); } } return; }
void fragmentYieldsPlot() { gStyle->SetOptStat(0000000000); //remove the for this graphs totally redundant statbox int ZNumGiven; cout << "Enter fragment Z-number (eg. 1): "; cin >> ZNumGiven; TCanvas *c1 = new TCanvas("fragmentYieldsPlot", "Total yield of fragments zero to ten degrees as function of depth"); TString fragmentNameChoices[6] = {"H","He","Li","Be","B","C"}; TString fragmentName = fragmentNameChoices[ZNumGiven-1]; std::cout << fragmentName << endl; TH1F* dummyHisto = new TH1F("dummyHisto", fragmentName + " yields 0-10 degrees" ,100, 0.0,40); //Dummyhisto fix for missing TNtuple methods. dummyHisto->SetXTitle("Depth (cm)"); dummyHisto->SetYTitle("N/N0"); ifstream in; TString experimentalDataPath = "experimentalData/iaeaBenchmark/yields/TDK" + fragmentName + ".dat"; ifstream in; //Pull in ascii/exfor-style data in.open(experimentalDataPath); Float_t f1,f2; Int_t nlines = 0; TFile *f = new TFile("fragmentAngularDistribution.root","RECREATE"); TNtuple *ntuple = new TNtuple("ntuple","Data from ascii file","x:y"); Char_t DATAFLAG[4]; Int_t NDATA; Char_t n1[15], n2[15]; in >> DATAFLAG >> NDATA ; // Read EXFOR line: 'DATA 6' in >> n1 >> n2; // Read column titles: 'Energy He B [...]' cout <<n1<<" "<<n2<<"\n"; while (1) { in >> f1 >> f2; if (!in.good()) break; if (nlines < 500 ) printf("%f %f\n",f1,f2); ntuple->Fill(f1,f2); nlines++; } std::cout << "Imported " << nlines << " lines from data-file" << endl; TNtuple *simData = new TNtuple("ntuple","Data from ascii file","depth:H:He:Li:Be:B:C"); // gROOT->SetStyle("clearRetro"); //this will be used as base for pulling the experimental data TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName()); dir.ReplaceAll("fragmentAngularDistribution.C",""); dir.ReplaceAll("/./","/"); ifstream in; simData->Fill(0.0,0.0,0.0,0.0,0.0,0.0,1.0); for(int j = 1; j <= 40;j=j=j+1){ TString pDepth, fragment, Znum, normToOneAtZeroAngle; pDepth = Form("%i",j); /* cout << "Enter phantom depth (eg. 27.9, see experimentalData directory for choices): "; cin >> pDepth; */ TString simulationDataPath = "IAEA_" + pDepth + ".root"; //Let's pull in the simulation-data //TFile *MCData = TFile::Open("IAEA_" + pDepth + ".root"); TFile *MCData = TFile::Open(simulationDataPath); TNtuple *fragments = (TNtuple*) MCData->Get("fragmentNtuple"); //Block bellow pulls out the simulation's metadata from the metadata ntuple. TNtuple *metadata = (TNtuple*) MCData->Get("metaData"); Float_t events, detectorDistance,waterThickness,beamEnergy,energyError,phantomCenterDistance; metadata->SetBranchAddress("events",&events); metadata->SetBranchAddress("waterThickness",&waterThickness); metadata->SetBranchAddress("detectorDistance",&detectorDistance); metadata->SetBranchAddress("beamEnergy",&beamEnergy); metadata->SetBranchAddress("energyError",&energyError); metadata->SetBranchAddress("phantomCenterDistance",&phantomCenterDistance); metadata->GetEntry(0); //there is just one row to consider. //ALL UNITS ARE cm! Double_t scatteringDistance = detectorDistance - phantomCenterDistance; //temporarily hard-coded, should be distance from target-center to detector Double_t degrees = 10.0; Double_t r, rMin, rMax, graphMaximum = 0.0; Double_t norming = events*.999; TString rMinString; TString rMaxString; rMinString = "0.00"; rMaxString = Form("%f", scatteringDistance*TMath::ATan(degrees*TMath::DegToRad())); Double_t H = ((Double_t*) fragments->GetEntries("(Z == " + TString::Format("%i",1) + " && sqrt(posY^2 + posZ^2) < " + rMaxString + "&& sqrt(posY*posY + posZ*posZ) > " + rMinString + ")")) / norming; Double_t He = ((Double_t*) fragments->GetEntries("(Z == " + TString::Format("%i",2) + " && sqrt(posY^2 + posZ^2) < " + rMaxString + "&& sqrt(posY*posY + posZ*posZ) > " + rMinString + ")")) / norming; Double_t Li = ((Double_t*) fragments->GetEntries("(Z == " + TString::Format("%i",3) + " && sqrt(posY^2 + posZ^2) < " + rMaxString + "&& sqrt(posY*posY + posZ*posZ) > " + rMinString + ")")) / norming; Double_t Be = ((Double_t*) fragments->GetEntries("(Z == " + TString::Format("%i",4) + " && sqrt(posY^2 + posZ^2) < " + rMaxString + "&& sqrt(posY*posY + posZ*posZ) > " + rMinString + ")")) / norming; Double_t B = ((Double_t*) fragments->GetEntries("(Z == " + TString::Format("%i",5) + " && sqrt(posY^2 + posZ^2) < " + rMaxString + "&& sqrt(posY*posY + posZ*posZ) > " + rMinString + ")")) / norming; Double_t C = ((Double_t*) fragments->GetEntries("(Z == " + TString::Format("%i",6) + " && sqrt(posY^2 + posZ^2) < " + rMaxString + "&& sqrt(posY*posY + posZ*posZ) > " + rMinString + ")")) / norming; simData->Fill(waterThickness,H,He,Li,Be,B,C); } simData->Scan(); simData->SetMarkerStyle(2); //filled dot simData->SetMarkerColor(kBlue); graphMaximum = TMath::Max(graphMaximum, simData->GetMaximum(fragmentName)); graphMaximum = TMath::Max(graphMaximum, ntuple->GetMaximum("y")); dummyHisto->SetMaximum(graphMaximum + .05*graphMaximum); dummyHisto->Draw(); simData->Draw(fragmentName + ":depth","","p,same"); ntuple->SetMarkerStyle(22); //triangle ntuple->SetMarkerColor(kRed); ntuple->Draw("y:x","","p,same"); c1->SaveAs("fragmentYieldsFor" + fragmentName + ".png"); }