ATLAS Offline Software
Loading...
Searching...
No Matches
graph_to_function.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
3*/
4// utility to take a root file full of TGraph2DErrors and create a root file with TF2s.
5#include <iostream>
6#include <memory>
7#include <string>
8#include <vector>
9#include <cmath>
10
11#include "TFile.h"
12#include "TGraph2DErrors.h"
13#include "TF2.h"
14#include "TFitResult.h"
15
16using std::make_unique;
17using std::cout;
18using std::cerr;
19using std::endl;
20using std::string;
21using std::vector;
22
23int main(int argc, char** argv) {
24 if (argc !=3) {
25 cout << "Usage: " << argv[0] << " input.root output.root" << endl;
26 return 1;
27 }
28
29 auto fin = make_unique<TFile>(argv[1], "READ");
30 if (fin == nullptr) {
31 cerr << "Could not open input file " << argv[1] << endl;
32 return 2;
33 }
34 auto fout = make_unique<TFile>(argv[2], "RECREATE");
35 if (fout == nullptr) {
36 cerr << "Could not open output file " << argv[2] << endl;
37 return 2;
38 }
39
40 auto etaLegFunc = [](double* x, double* par){
41 double tanhEtaSq = std::tanh(x[0]);
42 tanhEtaSq = tanhEtaSq*tanhEtaSq;
43 // tanhEtaSq = x[0]*x[0]/6.25; // try just eta
44 // double lp0 = 1.
45 double lp2 = 1.5*tanhEtaSq - 0.5;// 2nd order legendre poly
46 double lp4 = 0.125*(35.*tanhEtaSq*tanhEtaSq - 30.*tanhEtaSq + 3.);
47 double lp6 = 0.0625*(231*tanhEtaSq*tanhEtaSq*tanhEtaSq - 315*tanhEtaSq*tanhEtaSq + 105*tanhEtaSq - 5);
48 return par[0]*(1. + par[2]*(lp2-1) + par[4]*(lp4-1) + par[6]*(lp6-1)) +
49 par[1]*(1. + par[3]*(lp2-1) + par[5]*(lp4-1) + par[7]*(lp6-1))/x[1];
50 };
51
52 // loop through histograms in infile
53 TIter next(fin->GetListOfKeys());
54 while (TObject* obj = next()) {
55 string objName = obj->GetName();
56 cout << "Fitting " << objName << endl;
57 TGraph2DErrors* gr = nullptr;
58 fin->GetObject(obj->GetName(), gr);
59 if (gr == nullptr) {
60 cerr << "Could not retrieve " << obj->GetName()
61 << " as a TGraph2DErrors." << endl;
62 continue;
63 }
64 TF2* func = new TF2(objName.data(), etaLegFunc, -2.5, 2.5, 0.1, 100.0, 8);
65 // func->SetNpx(200);
66 func->SetNpy(200);
67 func->SetParameters(0.02, 0.1, 0.1, 0.1, 0., 0., 0., 0.);
68 func->SetParLimits(0, 0., 5.);
69 func->SetParLimits(1, 0., 5.);
70 double ext = 0.7;
71 func->SetParLimits(2, -ext, ext);
72 func->SetParLimits(3, -ext, ext);
73 func->SetParLimits(4, -ext, ext);
74 func->SetParLimits(5, -ext, ext);
75 func->SetParLimits(6, -ext, ext);
76 func->SetParLimits(7, -ext, ext);
77
78 // func->FixParameter(4, 0.);
79 // func->FixParameter(5, 0.);
80 func->FixParameter(6, 0.);
81 func->FixParameter(7, 0.);
82 auto result = gr->Fit(func, "S"); // "R" to use function range
83 cout << "ndf, g.N = " << result->Ndf() << ", " << gr->GetN() << endl;
84 func->Write();
85 }
86
87
88 return 0;
89}
#define gr
#define x
int main()
Definition hello.cxx:18
static TFile * fout
Definition listroot.cxx:40