GRSISort "v4.0.0.5"
An extension of the ROOT analysis Framework
Loading...
Searching...
No Matches
AngularCorrelations.cxx
Go to the documentation of this file.
1#include <iostream>
2#include <iomanip>
3#include <vector>
4#include <string>
5#include <cassert>
6
7#include "TFile.h"
8#include "TH2.h"
9#include "TH1.h"
10#include "TGraphErrors.h"
11#include "TMultiGraph.h"
12#include "TCanvas.h"
13#include "TLine.h"
14#include "TLegend.h"
15#include "Fit/Fitter.h"
16#include "TMatrixD.h"
17#include "TPaveText.h"
18
19#include "ArgParser.h"
20#include "TUserSettings.h"
21#include "TGriffinAngles.h"
22#include "TPeakFitter.h"
23#include "TRWPeak.h"
24
25TGraph* MixingMethod(TGraphErrors* data, TGraphErrors* z0, TGraphErrors* z2, TGraphErrors* z4, int twoJhigh, int twoJmid, int twoJlow, std::vector<double>& bestParameters);
26std::vector<double> A2a4Method(TGraphErrors* data, TGraphErrors* z0, TGraphErrors* z2, TGraphErrors* z4);
27
28double GetYError(TGraphErrors* graph, const double& x)
29{
30 /// general function to get the error of a graph at point x (takes the maximum of the errors of the bracketing points)
31 for(int i = 0; i < graph->GetN(); ++i) {
32#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 20, 0)
33 // exact match: return the error at this point
34 if(graph->GetPointX(i) == x) { return graph->GetErrorY(i); }
35 // first point with larger x: take maximum of this point and previous point
36 // TGraphErrors::GetErrorY returns -1 if index is negative, so we don't need to check for this
37 if(graph->GetPointX(i) > x) { return std::max(graph->GetErrorY(i - 1), graph->GetErrorY(i)); }
38#else
39 double px, py;
40 graph->GetPoint(i, px, py);
41 // exact match: return the error at this point
42 if(px == x) { return graph->GetErrorY(i); }
43 // first point with larger x: take maximum of this point and previous point
44 // TGraphErrors::GetErrorY returns -1 if index is negative, so we don't need to check for this
45 if(px > x) { return std::max(graph->GetErrorY(i - 1), graph->GetErrorY(i)); }
46#endif
47 }
48 return 0.;
49}
50
51/// program to read in 2D matrices from AngularCorrelationHelper
52/// project and fit peaks to create angular correlation plots
53/// and to create chi-square plots
54int main(int argc, char** argv)
55{
56 // --------------------------------------------------------------------------------
57 // Reading and verifying inputs and settings.
58 // --------------------------------------------------------------------------------
59
60 // input parameters
61 bool help = false;
62 double projGateLow = -1.;
63 double projGateHigh = -1.;
64 double projBgLow = -1.;
65 double projBgHigh = -1.;
66 double timeRandomNorm = -1.;
67 double peakPos = -1.;
68 double peakLow = -1.;
69 double peakHigh = -1.;
70 std::string baseName = "AngularCorrelation";
71 std::string inputFile;
72 std::string theoryFile;
73 std::string outputFile = "AngularCorrelations.root";
74 std::string settingsFile;
75
76 // set up the argument parser
77 ArgParser parser;
78 parser.option("h help ?", &help, true).description("Show this help message.");
79 parser.option("projection-low proj-low", &projGateLow, true).description("Low edge of projection gate.");
80 parser.option("projection-high proj-high", &projGateHigh, true).description("High edge of projection gate.");
81 parser.option("background-low bg-low", &projBgLow, true).description("Low edge of background gate (for multiple gates use settings file).");
82 parser.option("background-high bg-high", &projBgHigh, true).description("High edge of background gate (for multiple gates use settings file).");
83 parser.option("time-random-normalization", &timeRandomNorm, true).description("Normalization factor for subtraction of time-random matrix. If negative (default) it will be calculated automatically.");
84 parser.option("base-name", &baseName, true).description("Base name of matrices.").default_value("AngularCorrelation");
85 parser.option("peak-pos peak", &peakPos, true).description("Peak position (for multiple peaks use settings file).");
86 parser.option("peak-low", &peakLow, true).description("Low edge of peak fit.");
87 parser.option("peak-high", &peakHigh, true).description("High edge of peak fit.");
88 parser.option("settings", &settingsFile, true).description("Settings file with user settings, these do not overwrite anything provided on command line!");
89 parser.option("input", &inputFile, true).description("Input file with gamma-gamma matrices for each angle (coincident, time-random, and event mixed).");
90 parser.option("theory", &theoryFile, true).description("File with simulated z0-, z2-, and z4-graphs.");
91 parser.option("output", &outputFile, true).description("Name of output file, default is \"AngularCorrelations.root\".");
92
93 parser.parse(argc, argv, true);
94
95 if(help) {
96 std::cout << parser << std::endl;
97 return 1;
98 }
99
100 // open the input root file and read any settings stored there, then add the ones potentially read in from command line
101 if(inputFile.empty()) {
102 std::cerr << "Need an input file!" << std::endl;
103 return 1;
104 }
105
106 TFile input(inputFile.c_str());
107
108 if(!input.IsOpen()) {
109 std::cerr << "Failed to open input file " << inputFile << std::endl;
110 return 1;
111 }
112
113 auto* settings = static_cast<TUserSettings*>(input.Get("UserSettings"));
114
115 // if we have a path for a settings file provided on command line, we either add it to the ones read
116 // from the root file or (if there weren't any) create a new instance from it
117 if(!settingsFile.empty()) {
118 if(settings == nullptr) {
119 settings = new TUserSettings(settingsFile);
120 } else {
121 settings->ReadSettings(settingsFile);
122 }
123 }
124
125 // check that we got settings either from the root file or a path provided on command line
126 if(settings == nullptr || settings->empty()) {
127 std::cerr << "Failed to get user settings from input file." << std::endl;
128 return 1;
129 }
130
131 // set all variables from settings if they haven't been set from command line
132 if(projGateLow == -1.) { projGateLow = settings->GetDouble("Projection.Low"); }
133 if(projGateHigh == -1.) { projGateHigh = settings->GetDouble("Projection.High"); }
134 if(timeRandomNorm == -1.) { timeRandomNorm = settings->GetDouble("TimeRandomNormalization"); }
135 if(peakPos == -1.) { peakPos = settings->GetDouble("Peak.Position"); }
136 if(peakLow == -1.) { peakLow = settings->GetDouble("Peak.Low"); }
137 if(peakHigh == -1.) { peakHigh = settings->GetDouble("Peak.High"); }
138 // for the background-peak positions and background gates we could have multiple, so we create vectors for them
139 std::vector<double> bgPeakPos;
140 std::vector<double> bgLow;
141 std::vector<double> bgHigh;
142 // we only fill the background gates from the settings if there were none provided on the command line
143 if(projBgLow == -1. || projBgHigh == -1. || projBgLow >= projBgHigh) {
144 for(int i = 1;; ++i) {
145 try {
146 auto low = settings->GetDouble(Form("Background.%d.Low", i), true);
147 auto high = settings->GetDouble(Form("Background.%d.High", i), true);
148 if(low >= high) {
149 std::cout << i << ". background gate, low edge not lower than the high edge: " << low << " >= " << high << std::endl;
150 break;
151 }
152 bgLow.push_back(low);
153 bgHigh.push_back(high);
154 } catch(std::out_of_range& e) {
155 break;
156 }
157 }
158 } else {
159 bgLow.push_back(projBgLow);
160 bgHigh.push_back(projBgHigh);
161 }
162 // background-peak positions can only be set via settings file
163 // we loop until we fail to find an entry
164 for(int i = 1;; ++i) {
165 try {
166 auto pos = settings->GetDouble(Form("BackgroundPeak.Position.%d", i), true);
167 if(pos <= peakLow || pos >= peakHigh) {
168 std::cout << i << ". background peak outside of fit range: " << pos << " <= " << peakLow << " or " << pos << " >= " << peakHigh << std::endl;
169 break;
170 }
171 bgPeakPos.push_back(pos);
172 } catch(std::out_of_range& e) {
173 break;
174 }
175 }
176
177 // parameter limits and fixed parameters for the peak and the background peaks
178 // if the limits are the same, the parameter is fixed to that value, if the high limit is lower than the low limit there is no limit
179 // right now we are hard coded to use TRWPeaks which have 6 parameters
180 std::vector<double> peakParameter(6, -2.);
181 std::vector<double> peakParameterLow(6, 0.);
182 std::vector<double> peakParameterHigh(6, -1.);
183 std::vector<double> bgPeakParameter(6, -2.);
184 std::vector<double> bgPeakParameterLow(6, 0.);
185 std::vector<double> bgPeakParameterHigh(6, -1.);
186 for(size_t i = 0; i < peakParameterLow.size(); ++i) {
187 peakParameter[i] = settings->GetDouble(Form("Peak.Parameter.%d", static_cast<int>(i)), -2.);
188 peakParameterLow[i] = settings->GetDouble(Form("Peak.Parameter.%d.Low", static_cast<int>(i)), 0.);
189 peakParameterHigh[i] = settings->GetDouble(Form("Peak.Parameter.%d.High", static_cast<int>(i)), -1.);
190 bgPeakParameter[i] = settings->GetDouble(Form("BackgroundPeak.Parameter.%d", static_cast<int>(i)), -2.);
191 bgPeakParameterLow[i] = settings->GetDouble(Form("BackgroundPeak.Parameter.%d.Low", static_cast<int>(i)), 0.);
192 bgPeakParameterHigh[i] = settings->GetDouble(Form("BackgroundPeak.Parameter.%d.High", static_cast<int>(i)), -1.);
193 // check that the result makes sense, i.e. if the limits are in the righ order that the parameter itself is within the limits
194 // only output a warning that the parameter is changed if it's not the default value
195 if(peakParameterLow[i] <= peakParameterHigh[i] && (peakParameter[i] < peakParameterLow[i] || peakParameterHigh[i] < peakParameter[i])) {
196 bool output = peakParameter[i] != -2.;
197 if(output) { std::cout << "Warning, " << i << ". peak parameter (" << peakParameter[i] << ") is out of range " << peakParameterLow[i] << " - " << peakParameterHigh[i] << ", resetting it to "; }
198 peakParameter[i] = (peakParameterHigh[i] + peakParameterLow[i]) / 2.;
199 if(output) { std::cout << peakParameter[i] << std::endl; }
200 }
201 if(bgPeakParameterLow[i] <= bgPeakParameterHigh[i] && (bgPeakParameter[i] < bgPeakParameterLow[i] || bgPeakParameterHigh[i] < bgPeakParameter[i])) {
202 bool output = bgPeakParameter[i] != -2.;
203 if(output) { std::cout << "Warning, " << i << ". background peak parameter (" << bgPeakParameter[i] << ") is out of range " << bgPeakParameterLow[i] << " - " << bgPeakParameterHigh[i] << ", resetting it to "; }
204 bgPeakParameter[i] = (bgPeakParameterHigh[i] + bgPeakParameterLow[i]) / 2.;
205 if(output) { std::cout << bgPeakParameter[i] << std::endl; }
206 }
207 }
208 // parameter limits for the background (A + B*(x-o) + C*(x-o)^2)
209 // same idea as above, lower limit = higher limit means fixed parameter, higher limit < lower limit means parameter not set
210 std::vector<double> backgroundParameter(4, -2.);
211 std::vector<double> backgroundParameterLow(4, 0.);
212 std::vector<double> backgroundParameterHigh(4, -1.);
213 backgroundParameter[0] = settings->GetDouble("Background.Offset", -2.);
214 backgroundParameterLow[0] = settings->GetDouble("Background.Offset.Low", 0.);
215 backgroundParameterHigh[0] = settings->GetDouble("Background.Offset.High", -1.);
216 backgroundParameter[1] = settings->GetDouble("Background.Linear", -2.);
217 backgroundParameterLow[1] = settings->GetDouble("Background.Linear.Low", 0.);
218 backgroundParameterHigh[1] = settings->GetDouble("Background.Linear.High", -1.);
219 backgroundParameter[2] = settings->GetDouble("Background.Quadratic", -2.);
220 backgroundParameterLow[2] = settings->GetDouble("Background.Quadratic.Low", 0.);
221 backgroundParameterHigh[2] = settings->GetDouble("Background.Quadratic.High", -1.);
222 backgroundParameter[3] = settings->GetDouble("Background.Xoffset", -2.);
223 backgroundParameterLow[3] = settings->GetDouble("Background.Xoffset.Low", 0.);
224 backgroundParameterHigh[3] = settings->GetDouble("Background.Xoffset.High", -1.);
225 for(size_t i = 0; i < backgroundParameter.size(); ++i) {
226 if(backgroundParameterLow[i] <= backgroundParameterHigh[i] && (backgroundParameter[i] < backgroundParameterLow[i] || backgroundParameterHigh[i] < backgroundParameter[i])) {
227 bool output = backgroundParameter[i] != -2.;
228 if(output) { std::cout << "Warning, " << i << ". background parameter (" << backgroundParameter[i] << ") is out of range " << backgroundParameterLow[i] << " - " << backgroundParameterHigh[i] << ", resetting it to "; }
229 backgroundParameter[i] = (backgroundParameterHigh[i] + backgroundParameterLow[i]) / 2.;
230 if(output) { std::cout << backgroundParameter[i] << std::endl; }
231 }
232 }
233
234 // the spins of the low, middle, and high levels, to be used for the mixing method
235 // two of these need to be vectors of length one (meaning the settings file should have an entry with "name: <value>,"), the third can have a length larger than 1
236 std::vector<int> twoJLow = settings->GetIntVector("TwoJ.Low");
237 std::vector<int> twoJMiddle = settings->GetIntVector("TwoJ.Middle");
238 std::vector<int> twoJHigh = settings->GetIntVector("TwoJ.High");
239
240 // confidence level (this value is used to draw a line at the confidence level for the mixing method)
241 double confidenceLevel = settings->GetDouble("ConfidenceLevel", 1.535); // 1.535 is 99% confidence level for 48 degrees of freedom
242
243 // check if all necessary settings have been provided
244 if(projGateLow >= projGateHigh) {
245 std::cerr << "Need a projection gate with a low edge that is smaller than the high edge, " << projGateLow << " >= " << projGateHigh << std::endl;
246 return 1;
247 }
248
249 if(peakLow >= peakHigh) {
250 std::cerr << "Need a fit range with a low edge that is smaller than the high edge, " << peakLow << " >= " << peakHigh << std::endl;
251 return 1;
252 }
253
254 if(peakPos >= peakHigh || peakPos <= peakLow) {
255 std::cerr << "Need a peak within the fit range, " << peakPos << " not within " << peakLow << " - " << peakHigh << std::endl;
256 return 1;
257 }
258
259 if(timeRandomNorm <= 0.) {
260 std::cerr << "Need a positive normalization factor for time random subtraction" << std::endl;
261 return 1;
262 }
263
264 // for the background gates we checked that the low edge is below the high edge before adding them to the vector
265 // so we only need to check that the vectors aren't empty (sizes should always be the same, but we check anyway)
266 if(bgLow.empty() || bgLow.size() != bgHigh.size()) {
267 std::cerr << "Background gate information missing, either no low/high edges or a mismatching amount of low and high edges: " << bgLow.size() << " low edges, and " << bgHigh.size() << " high edges" << std::endl;
268 return 1;
269 }
270
271 // get the angles from the input file
272 auto* angles = static_cast<TGriffinAngles*>(input.Get("GriffinAngles"));
273
274 if(angles == nullptr) {
275 std::cerr << "Failed to find 'GriffinAngles' in '" << inputFile << "'" << std::endl;
276 return 1;
277 }
278
279 // --------------------------------------------------------------------------------
280 // Create the angular distribution.
281 // --------------------------------------------------------------------------------
282
283 // open output file and create graphs
284 TFile output(outputFile.c_str(), "recreate");
285
286 auto* rawAngularDistribution = new TGraphErrors(angles->NumberOfAngles());
287 rawAngularDistribution->SetName("RawAngularDistribution");
288 auto* angularDistribution = new TGraphErrors(angles->NumberOfAngles());
289 angularDistribution->SetName("AngularDistribution");
290 auto* mixedAngularDistribution = new TGraphErrors(angles->NumberOfAngles());
291 mixedAngularDistribution->SetName("MixedAngularDistribution");
292 auto* rawChiSquares = new TGraph(angles->NumberOfAngles());
293 rawChiSquares->SetName("RawChiSquares");
294 auto* mixedChiSquares = new TGraph(angles->NumberOfAngles());
295 mixedChiSquares->SetName("MixedChiSquares");
296
297 // write the user settings to the output file
298 settings->Write();
299
300#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 20, 0)
301 auto* fitDir = output.mkdir("fits", "Projections with fits", true);
302#else
303 auto* fitDir = output.mkdir("fits", "Projections with fits");
304#endif
305
306 // loop over all matrices
307 for(int i = 0; i < angles->NumberOfAngles(); ++i) {
308 // get the three histograms we need: prompt, time random, and event mixed
309 auto* prompt = static_cast<TH2*>(input.Get(Form("AngularCorrelation%d", i)));
310 if(prompt == nullptr) {
311 std::cerr << "Failed to find histogram '" << Form("AngularCorrelation%d", i) << "', should have " << angles->NumberOfAngles() << " angles in total!" << std::endl;
312 return 1;
313 }
314 auto* bg = static_cast<TH2*>(input.Get(Form("AngularCorrelationBG%d", i)));
315 if(bg == nullptr) {
316 std::cerr << "Failed to find histogram '" << Form("AngularCorrelationBG%d", i) << "', should have " << angles->NumberOfAngles() << " angles in total!" << std::endl;
317 return 1;
318 }
319 auto* mixed = static_cast<TH2*>(input.Get(Form("AngularCorrelationMixed%d", i)));
320 if(mixed == nullptr) {
321 std::cerr << "Failed to find histogram '" << Form("AngularCorrelationMixed%d", i) << "', should have " << angles->NumberOfAngles() << " angles in total!" << std::endl;
322 return 1;
323 }
324
325 // first subtract time random background from prompt data and enable proper error propagation for prompt and mixed data
326 prompt->Sumw2();
327 prompt->Add(bg, -timeRandomNorm);
328 mixed->Sumw2();
329
330 // project onto x-axis
331 auto* proj = prompt->ProjectionX(Form("proj%d", i), prompt->GetYaxis()->FindBin(projGateLow), prompt->GetYaxis()->FindBin(projGateHigh));
332 auto* projMixed = mixed->ProjectionX(Form("projMixed%d", i), mixed->GetYaxis()->FindBin(projGateLow), mixed->GetYaxis()->FindBin(projGateHigh));
333 // project background gate(s) onto x-axis
334 auto* projBg = prompt->ProjectionX(Form("projBg%d", i), prompt->GetYaxis()->FindBin(bgLow[0]), prompt->GetYaxis()->FindBin(bgHigh[0]));
335 auto* projMixedBg = mixed->ProjectionX(Form("projMixedBg%d", i), mixed->GetYaxis()->FindBin(bgLow[0]), mixed->GetYaxis()->FindBin(bgHigh[0]));
336 double bgGateWidth = prompt->GetYaxis()->FindBin(bgHigh[0]) - prompt->GetYaxis()->FindBin(bgLow[0]) + 1;
337 double mixedBgGateWidth = mixed->GetYaxis()->FindBin(bgHigh[0]) - mixed->GetYaxis()->FindBin(bgLow[0]) + 1;
338 for(size_t g = 1; g < bgLow.size(); ++g) {
339 projBg->Add(prompt->ProjectionX(Form("projBg%d", i), prompt->GetYaxis()->FindBin(bgLow[g]), prompt->GetYaxis()->FindBin(bgHigh[g])));
340 projMixedBg->Add(mixed->ProjectionX(Form("projMixedBg%d", i), mixed->GetYaxis()->FindBin(bgLow[g]), mixed->GetYaxis()->FindBin(bgHigh[g])));
341 bgGateWidth += prompt->GetYaxis()->FindBin(bgHigh[g]) - prompt->GetYaxis()->FindBin(bgLow[g]) + 1;
342 mixedBgGateWidth += mixed->GetYaxis()->FindBin(bgHigh[g]) - mixed->GetYaxis()->FindBin(bgLow[g]) + 1;
343 }
344
345 // subtract background gate (+1 because the projection includes first and last bin)
346 proj->Add(projBg, -(prompt->GetYaxis()->FindBin(projGateHigh) - prompt->GetYaxis()->FindBin(projGateLow) + 1) / bgGateWidth);
347 projMixed->Add(projMixedBg, -(mixed->GetYaxis()->FindBin(projGateHigh) - mixed->GetYaxis()->FindBin(projGateLow) + 1) / mixedBgGateWidth);
348
349 // fit the projections, we create separate peak fitters and peaks for the prompt and mixed histograms
350 TPeakFitter pf(peakLow, peakHigh);
351 TRWPeak peak(peakPos);
352 for(size_t p = 0; p < peakParameterLow.size(); ++p) {
353 if(peakParameterLow[p] == peakParameterHigh[p]) {
354 peak.GetFitFunction()->FixParameter(p, peakParameter[p]);
355 } else if(peakParameterLow[p] < peakParameterHigh[p]) {
356 peak.GetFitFunction()->SetParameter(p, peakParameter[p]);
357 peak.GetFitFunction()->SetParLimits(p, peakParameterLow[p], peakParameterHigh[p]);
358 }
359 }
360 pf.AddPeak(&peak);
361 for(auto bgPeak : bgPeakPos) {
362 auto* bgP = new TRWPeak(bgPeak);
363 for(size_t p = 0; p < bgPeakParameterLow.size(); ++p) {
364 if(bgPeakParameterLow[p] == bgPeakParameterHigh[p]) {
365 bgP->GetFitFunction()->FixParameter(p, bgPeakParameter[p]);
366 } else if(bgPeakParameterLow[p] < bgPeakParameterHigh[p]) {
367 bgP->GetFitFunction()->SetParameter(p, bgPeakParameter[p]);
368 bgP->GetFitFunction()->SetParLimits(p, bgPeakParameterLow[p], bgPeakParameterHigh[p]);
369 }
370 }
371 pf.AddPeak(bgP);
372 }
373 for(size_t p = 0; p < backgroundParameterLow.size(); ++p) {
374 if(backgroundParameterLow[p] == backgroundParameterHigh[p]) {
375 pf.GetBackground()->FixParameter(p, backgroundParameter[p]);
376 } else if(backgroundParameterLow[p] < backgroundParameterHigh[p]) {
377 pf.GetBackground()->SetParameter(p, backgroundParameter[p]);
378 pf.GetBackground()->SetParLimits(p, backgroundParameterLow[p], backgroundParameterHigh[p]);
379 }
380 }
381 pf.Fit(proj, "qretryfit");
382
383 TPeakFitter pfMixed(peakLow, peakHigh);
384 TRWPeak peakMixed(peakPos);
385 for(size_t p = 0; p < peakParameterLow.size(); ++p) {
386 if(peakParameterLow[p] == peakParameterHigh[p]) {
387 peakMixed.GetFitFunction()->FixParameter(p, peakParameter[p]);
388 } else if(peakParameterLow[p] < peakParameterHigh[p]) {
389 peakMixed.GetFitFunction()->SetParameter(p, peakParameter[p]);
390 peakMixed.GetFitFunction()->SetParLimits(p, peakParameterLow[p], peakParameterHigh[p]);
391 }
392 }
393 pfMixed.AddPeak(&peakMixed);
394 for(auto bgPeak : bgPeakPos) {
395 auto* bgP = new TRWPeak(bgPeak);
396 for(size_t p = 0; p < bgPeakParameterLow.size(); ++p) {
397 if(bgPeakParameterLow[p] == bgPeakParameterHigh[p]) {
398 bgP->GetFitFunction()->FixParameter(p, bgPeakParameter[p]);
399 } else if(bgPeakParameterLow[p] < bgPeakParameterHigh[p]) {
400 bgP->GetFitFunction()->SetParameter(p, bgPeakParameter[p]);
401 bgP->GetFitFunction()->SetParLimits(p, bgPeakParameterLow[p], bgPeakParameterHigh[p]);
402 }
403 }
404 pfMixed.AddPeak(bgP);
405 }
406 for(size_t p = 0; p < backgroundParameterLow.size(); ++p) {
407 if(backgroundParameterLow[p] == backgroundParameterHigh[p]) {
408 pfMixed.GetBackground()->FixParameter(p, backgroundParameter[p]);
409 } else if(backgroundParameterLow[p] < backgroundParameterHigh[p]) {
410 pfMixed.GetBackground()->SetParameter(p, backgroundParameter[p]);
411 pfMixed.GetBackground()->SetParLimits(p, backgroundParameterLow[p], backgroundParameterHigh[p]);
412 }
413 }
414 pfMixed.Fit(projMixed, "qretryfit");
415
416 // save the fitted histograms to the output file and the areas of the peaks
417 fitDir->cd();
418 proj->Write();
419 projMixed->Write();
420
421 // TODO: set an error for the angles?
422 rawAngularDistribution->SetPoint(i, angles->AverageAngle(i), peak.Area());
423 rawAngularDistribution->SetPointError(i, 0., peak.AreaErr());
424 mixedAngularDistribution->SetPoint(i, angles->AverageAngle(i), peakMixed.Area());
425 mixedAngularDistribution->SetPointError(i, 0., peakMixed.AreaErr());
426 angularDistribution->SetPoint(i, angles->AverageAngle(i), peak.Area() / peakMixed.Area());
427 angularDistribution->SetPointError(i, 0., peak.Area() / peakMixed.Area() * TMath::Sqrt(TMath::Power(peak.AreaErr() / peak.Area(), 2) + TMath::Power(peakMixed.AreaErr() / peakMixed.Area(), 2)));
428
429 rawChiSquares->SetPoint(i, angles->AverageAngle(i), peak.GetReducedChi2());
430 mixedChiSquares->SetPoint(i, angles->AverageAngle(i), peakMixed.GetReducedChi2());
431
432 std::cout << std::setw(3) << i << " of " << angles->NumberOfAngles() << " done\r" << std::flush;
433 }
434 std::cout << "Fitting of projections done." << std::endl;
435
436 // correct the raw and mixed graphs for the number of combinations that contribute to each angle
437 auto* rawAngularDistributionCorr = static_cast<TGraphErrors*>(rawAngularDistribution->Clone("RawAngularDistributionCorrected"));
438 for(int i = 0; i < rawAngularDistributionCorr->GetN(); ++i) {
439#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 20, 0)
440 if(angles->Count(rawAngularDistributionCorr->GetPointX(i)) != 0) {
441 rawAngularDistributionCorr->SetPointY(i, rawAngularDistributionCorr->GetPointY(i) / angles->Count(rawAngularDistributionCorr->GetPointX(i)));
442 rawAngularDistributionCorr->SetPointError(i, rawAngularDistributionCorr->GetErrorX(i), rawAngularDistributionCorr->GetErrorY(i) / angles->Count(rawAngularDistributionCorr->GetPointX(i)));
443 } else {
444 rawAngularDistributionCorr->SetPointY(i, 0);
445 }
446#else
447 double px, py;
448 rawAngularDistributionCorr->GetPoint(i, px, py);
449 if(angles->Count(px) != 0) {
450 rawAngularDistributionCorr->SetPoint(i, px, py / angles->Count(px));
451 rawAngularDistributionCorr->SetPointError(i, rawAngularDistributionCorr->GetErrorX(i), rawAngularDistributionCorr->GetErrorY(i) / angles->Count(px));
452 } else {
453 rawAngularDistributionCorr->SetPoint(i, px, 0);
454 }
455#endif
456 }
457 auto* mixedAngularDistributionCorr = static_cast<TGraphErrors*>(mixedAngularDistribution->Clone("MixedAngularDistributionCorrected"));
458 for(int i = 0; i < mixedAngularDistributionCorr->GetN(); ++i) {
459#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 20, 0)
460 if(angles->Count(mixedAngularDistributionCorr->GetPointX(i)) != 0) {
461 mixedAngularDistributionCorr->SetPointY(i, mixedAngularDistributionCorr->GetPointY(i) / angles->Count(mixedAngularDistributionCorr->GetPointX(i)));
462 mixedAngularDistributionCorr->SetPointError(i, mixedAngularDistributionCorr->GetErrorX(i), mixedAngularDistributionCorr->GetErrorY(i) / angles->Count(mixedAngularDistributionCorr->GetPointX(i)));
463 } else {
464 mixedAngularDistributionCorr->SetPointY(i, 0);
465 }
466#else
467 double px, py;
468 mixedAngularDistributionCorr->GetPoint(i, px, py);
469 if(angles->Count(px) != 0) {
470 mixedAngularDistributionCorr->SetPoint(i, px, py / angles->Count(px));
471 mixedAngularDistributionCorr->SetPointError(i, mixedAngularDistributionCorr->GetErrorX(i), mixedAngularDistributionCorr->GetErrorY(i) / angles->Count(px));
472 } else {
473 mixedAngularDistributionCorr->SetPoint(i, px, 0);
474 }
475#endif
476 }
477
478 // --------------------------------------------------------------------------------
479 // If a theory/simulation file has been provided, we use the a2/a4 and mixing
480 // methods to fit the angular distribution.
481 // --------------------------------------------------------------------------------
482
483 // check if we have a theory file
484 if(!theoryFile.empty()) {
485 TFile theory(theoryFile.c_str());
486
487 if(theory.IsOpen()) {
488 // read graphs from file
489 auto* z0 = static_cast<TGraphErrors*>(theory.Get("graph000"));
490 auto* z2 = static_cast<TGraphErrors*>(theory.Get("graph010"));
491 auto* z4 = static_cast<TGraphErrors*>(theory.Get("graph100"));
492
493 if(z0 != nullptr && z2 != nullptr && z4 != nullptr && z0->GetN() == z2->GetN() && z0->GetN() == z4->GetN()) {
494 // check if the sizes of the provided graphs match what we expect:
495 // if we have folding and grouping enabled we either need the graphs to match the angular distribution or have a size of either 51 (singles) or 49 (addback)
496 // otherwise the size needs to match the angular distribution
497 if(z0->GetN() == angularDistribution->GetN() || ((angles->Grouping() || angles->Folding()) && z0->GetN() == (angles->Addback() ? 49 : 51))) {
498 // if the theory needs to be folded and/or grouped, do so now
499 if(z0->GetN() != angularDistribution->GetN()) {
500 angles->FoldOrGroup(z0, z2, z4);
501 }
502 // calculate chi2 vs mixing graphs
503 std::vector<TGraph*> spin;
504 std::vector<double> spinLabel;
505 std::vector<std::vector<double>> parameters;
506 // first check which of the vectors we iterate over
507 if(twoJLow.size() > 1 && twoJMiddle.size() == 1 && twoJHigh.size() == 1) {
508 for(auto twoJ : twoJLow) {
509 parameters.emplace_back();
510 spin.push_back(MixingMethod(angularDistribution, z0, z2, z4, twoJHigh.at(0), twoJMiddle.at(0), twoJ, parameters.back()));
511 spinLabel.push_back(twoJ / 2.);
512 }
513 } else if(twoJLow.size() == 1 && twoJMiddle.size() > 1 && twoJHigh.size() == 1) {
514 for(auto twoJ : twoJMiddle) {
515 parameters.emplace_back();
516 spin.push_back(MixingMethod(angularDistribution, z0, z2, z4, twoJHigh.at(0), twoJ, twoJLow.at(0), parameters.back()));
517 spinLabel.push_back(twoJ / 2.);
518 }
519 } else if(twoJLow.size() == 1 && twoJMiddle.size() == 1 && twoJHigh.size() > 1) {
520 for(auto twoJ : twoJHigh) {
521 parameters.emplace_back();
522 spin.push_back(MixingMethod(angularDistribution, z0, z2, z4, twoJ, twoJMiddle.at(0), twoJLow.at(0), parameters.back()));
523 spinLabel.push_back(twoJ / 2.);
524 }
525 } else {
526 parameters.emplace_back();
527 spin.push_back(MixingMethod(angularDistribution, z0, z2, z4, twoJHigh.at(0), twoJMiddle.at(0), twoJLow.at(0), parameters.back()));
528 spinLabel.push_back(twoJHigh.at(0) / 2.);
529 }
530
531 // create canvas and plot graphs on it
532 auto* canvas = new TCanvas;
533
534 // determine minimum and maximum y-value
535 double min = TMath::MinElement(spin.at(0)->GetN(), spin.at(0)->GetY());
536 double max = TMath::MaxElement(spin.at(0)->GetN(), spin.at(0)->GetY());
537 for(size_t i = 1; i < spin.size(); ++i) {
538 min = TMath::Min(min, TMath::MinElement(spin.at(i)->GetN(), spin.at(i)->GetY()));
539 max = TMath::Max(max, TMath::MaxElement(spin.at(i)->GetN(), spin.at(i)->GetY()));
540 }
541 min = TMath::Min(min, confidenceLevel);
542
543 // find first graph with more than one data point
544 size_t first = 0;
545 for(first = 0; first < spin.size(); ++first) {
546 if(spin[first]->GetN() > 1) { break; }
547 }
548
549 spin[first]->SetTitle("");
550 spin[first]->SetMinimum(0.9 * min);
551 spin[first]->SetMaximum(1.1 * max);
552
553 for(size_t i = 0; i < spin.size(); ++i) {
554 spin[i]->SetLineColor(i + 1);
555 spin[i]->SetMarkerColor(i + 1);
556 spin[i]->SetLineWidth(2);
557 }
558
559 spin[first]->Draw("ac");
560 for(size_t i = 0; i < spin.size(); ++i) {
561 if(i == first) { continue; }
562 if(spin[i]->GetN() > 1) {
563 spin[i]->Draw("c");
564 } else {
565 spin[i]->Draw("*");
566 }
567 }
568
569 auto* confidenceLevelLine = new TLine(-1.5, confidenceLevel, 1.5, confidenceLevel);
570
571 confidenceLevelLine->Draw();
572
573#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 20, 0)
574 auto* legend = new TLegend(0.1, 0.3);
575#else
576 auto* legend = new TLegend(0.7, 0.6, 0.8, 0.9);
577#endif
578 for(size_t i = 0; i < spin.size(); ++i) {
579 if(spin[i]->GetN() == 1) {
580 legend->AddEntry(spin[i], Form("J = %.1f", spinLabel[i]), "p");
581 } else {
582 legend->AddEntry(spin[i], Form("J = %.1f", spinLabel[i]), "l");
583 }
584 }
585
586 legend->Draw();
587
588 canvas->SetLogy();
589
590 spin[first]->GetHistogram()->GetXaxis()->SetRangeUser(-1.5, 1.5);
591 spin[first]->GetHistogram()->GetXaxis()->SetTitle("atan(#delta) [rad]");
592 spin[first]->GetHistogram()->GetXaxis()->CenterTitle();
593 spin[first]->GetHistogram()->GetYaxis()->SetTitle("red. #chi^{2}");
594 spin[first]->GetHistogram()->GetYaxis()->CenterTitle();
595
596 // write graphs and canvas to output file
597 output.cd();
598 z0->Write("graph000");
599 z2->Write("graph010");
600 z4->Write("graph100");
601 for(size_t i = 0; i < spin.size(); ++i) {
602 spin[i]->Write(Form("spin%d", static_cast<int>(i)));
603 }
604 canvas->Write("MixingCanvas");
605
606 // create theory graphs with best fit for each spin, and write them to file
607 std::vector<TGraphErrors*> spinFit(spin.size(), new TGraphErrors(angularDistribution->GetN()));
608 auto* x = angularDistribution->GetX();
609 for(int p = 0; p < angularDistribution->GetN(); ++p) {
610 for(size_t i = 0; i < spinFit.size(); ++i) {
611 spinFit[i]->SetPoint(p, x[p], parameters[i][0] * ((1. - parameters[i][1] - parameters[i][2]) * z0->Eval(x[p]) + parameters[i][1] * z2->Eval(x[p]) + parameters[i][2] * z4->Eval(x[p])));
612 spinFit[i]->SetPointError(p, 0., TMath::Sqrt(parameters[i][0] * (TMath::Power((1. - parameters[i][1] - parameters[i][2]) * GetYError(z0, x[p]), 2) + TMath::Power(parameters[i][1] * GetYError(z2, x[p]), 2) + TMath::Power(parameters[i][2] * GetYError(z4, x[p]), 2))));
613 }
614 }
615 for(size_t i = 0; i < spin.size(); ++i) {
616 spinFit[i]->SetLineColor(i + 1);
617 spinFit[i]->SetMarkerColor(i + 1);
618 spinFit[i]->SetLineWidth(2);
619 spinFit[i]->Write(Form("SpinFit%d", static_cast<int>(i)));
620 output.WriteObject(&parameters[i], Form("Parameters%d", static_cast<int>(i)));
621 }
622
623 auto a2a4Parameters = A2a4Method(angularDistribution, z0, z2, z4);
624 output.WriteObject(&a2a4Parameters, "ParametersA2a4Fit");
625 } else { // if(z0->GetN() == angularDistribution->GetN() || ((angles->Grouping() || angles->Folding) && z0->GetN() == (angles->Addback() ? 49:51)))
626 std::cerr << "Mismatch between theory and data (" << z0->GetN() << " != " << angularDistribution->GetN() << "?) or neither grouping and folding are enabled (" << std::boolalpha << angles->Grouping() << ", " << angles->Folding() << ") or the ungrouped/folded theory doesn't match the required size for " << (angles->Addback() ? "addback" : "singles") << " data (" << (angles->Addback() ? 49 : 51) << ")" << std::endl;
627 }
628 } else { // if(z0 != nullptr && z2 != nullptr && z4 != nullptr && z0->GetN() == z2->GetN() && z0->GetN() == z4->GetN())
629 std::cerr << "Failed to find z0 (" << z0 << ", \"graph000\"), z2 (" << z2 << ", \"graph010\"), or z4 (" << z4 << ", \"graph100\") in " << theoryFile << ", or they had mismatched sizes" << std::endl;
630 }
631 } else { // if(theory.IsOpen())
632 std::cerr << "Failed to open " << theoryFile << std::endl;
633 }
634 } else { // if(!theoryFile.empty())
635 std::cout << "No file with simulation results (--theory flag), so we won't produce chi2 vs mixing angle plot." << std::endl;
636 }
637 output.cd();
638
639 rawAngularDistribution->Write();
640 angularDistribution->Write();
641 mixedAngularDistribution->Write();
642 rawChiSquares->Write();
643 mixedChiSquares->Write();
644 rawAngularDistributionCorr->Write();
645 mixedAngularDistributionCorr->Write();
646
647 angles->Write();
648
649 output.Close();
650 input.Close();
651
652 return 0;
653}
654
655class Ac {
656public:
657 explicit Ac(TGraphErrors* data = nullptr, TGraphErrors* z0 = nullptr, TGraphErrors* z2 = nullptr, TGraphErrors* z4 = nullptr)
658 : fData(data), fZ0(z0), fZ2(z2), fZ4(z4) {}
659
660 void Data(TGraphErrors* data) { fData = data; }
661 void Z0(TGraphErrors* z0) { fZ0 = z0; }
662 void Z2(TGraphErrors* z2) { fZ2 = z2; }
663 void Z4(TGraphErrors* z4) { fZ4 = z4; }
664 void SetZ(TGraphErrors* z0, TGraphErrors* z2, TGraphErrors* z4)
665 {
666 fZ0 = z0;
667 fZ2 = z2;
668 fZ4 = z4;
669 }
670
671 int Np() { return fData->GetN(); }
672
673 double operator()(const double* p)
674 {
675 double chi2 = 0;
676 for(int point = 0; point < fData->GetN(); ++point) {
677 // get data values
678 double x = 0.;
679 double y = 0.;
680 fData->GetPoint(point, x, y);
681 double yError = fData->GetErrorY(point);
682
683 // get simulation values
684 // for the y-values we can use Eval (uses linear interpolation)
685 double functionValue = p[0] * ((1. - p[1] - p[2]) * fZ0->Eval(x) + p[1] * fZ2->Eval(x) + p[2] * fZ4->Eval(x));
686 // for the y uncertainties we need to find the index (for each graph)
687 double errorSquare = TMath::Power(yError, 2) + TMath::Power(p[0], 2) * (TMath::Power((1. - p[1] - p[2]) * GetYError(fZ0, x), 2) + TMath::Power(p[1] * GetYError(fZ2, x), 2) + TMath::Power(p[2] * GetYError(fZ4, x), 2));
688
689 // calculate chi^2
690 chi2 += TMath::Power((y - functionValue), 2) / errorSquare;
691 }
692 return chi2;
693 }
694
695private:
696 TGraphErrors* fData{nullptr};
697 TGraphErrors* fZ0{nullptr};
698 TGraphErrors* fZ2{nullptr};
699 TGraphErrors* fZ4{nullptr};
700};
701
702TGraph* MixingMethod(TGraphErrors* data, TGraphErrors* z0, TGraphErrors* z2, TGraphErrors* z4, int twoJhigh, int twoJmid, int twoJlow, std::vector<double>& bestParameters)
703{
704 TGraph* result = nullptr;
705 Ac ac(data, z0, z2, z4);
706 ROOT::Fit::Fitter fitter;
707 int nPar = 3;
708 fitter.SetFCN(nPar, ac);
709 for(int i = 0; i < nPar; ++i) {
710 // parameter settings arguments are parameter name, initial value, step size, minimum, and maximum
711 fitter.Config().ParSettings(i) = ROOT::Fit::ParameterSettings(Form("a_{%d}", 2 * i), 0.5, 0.0001, -10., 10.);
712 }
713 fitter.Config().MinimizerOptions().SetPrintLevel(0);
714 fitter.Config().SetMinimizer("Minuit2", "Migrad"); // or simplex?
715
716 // j1 is the spin of the highest level
717 // j2 is the spin of the middle level
718 // j3 is the spin of the bottom level
719 double j1 = 0.5 * twoJhigh;
720 double j2 = 0.5 * twoJmid;
721 double j3 = 0.5 * twoJlow;
722 // l1 is the transition between j1 and j2
723 // a is the lowest allowed spin
724 // b is the mixing spin
725 int l1a = TMath::Abs(twoJhigh - twoJmid) / 2;
726 if(l1a == 0) { l1a = 1; }
727 int l1b = l1a + 1;
728 // l2 is the transition between j2 and j3
729 // a is the lowest allowed spin
730 // b is the mixing spin
731 int l2a = TMath::Abs(twoJmid - twoJlow) / 2;
732 if(l2a == 0) { l2a = 1; }
733 int l2b = l2a + 1;
734
735 // run some quick checks on the mixing ratios
736 if((twoJhigh == 0 && twoJmid == 0) || (twoJmid == 0 && twoJlow == 0)) {
737 std::cout << "!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!" << std::endl
738 << "Can't have gamma transition between J=0 states (high " << twoJhigh << ", mid " << twoJmid << ", low " << twoJlow << ")." << std::endl
739 << "Aborting..." << std::endl;
740 return result;
741 }
742 if(l1a == TMath::Abs(twoJhigh + twoJmid) / 2) {
743 //std::cout<<"!!!!!!!!!!!!!!! ALERT !!!!!!!!!!!!!!!"<<std::endl
744 // <<"Only one angular momentum allowed for high->middle transition (l1a "<<l1a<<" == "<<TMath::Abs(twoJhigh+twoJmid)/2<<")."<<std::endl
745 // <<"That mixing ratio (delta1) will be fixed at zero."<<std::endl
746 // <<"!!!!!!!!!!!!! END ALERT !!!!!!!!!!!!!"<<std::endl;
747 l1b = l1a;
748 }
749 if(l2a == TMath::Abs(twoJmid + twoJlow) / 2) {
750 //std::cout<<"!!!!!!!!!!!!!!! ALERT !!!!!!!!!!!!!!!"<<std::endl
751 // <<"Only one angular momentum allowed for middle->low transition (l2a "<<l2a<<" == "<<TMath::Abs(twoJmid+twoJlow)/2<<")."<<std::endl
752 // <<"That mixing ratio (delta2) will be fixed at zero."<<std::endl
753 // <<"!!!!!!!!!!!!! END ALERT !!!!!!!!!!!!!"<<std::endl;
754 l2b = l2a;
755 }
756
757 // -------------------------------------------------------------------//
758 // Constrained fitting
759 // -------------------------------------------------------------------//
760 // The basic idea is to select a particular set of physical quantities,
761 // calculate a2/a4, fix the a2/a4 parameters, and fit the scaling
762 // factor a0. Then output the specifications for that set of physical
763 // quantities and the chi^2 for further analysis.
764 // -------------------------------------------------------------------//
765
766 // delta runs from -infinity to infinity (unless constrained by known physics)
767 // in this case, it then makes more sense to sample evenly from tan^{-1}(delta)
768 // The next few lines are where you may want to include limits to significantly speed up calculations
769 // mixing for the high-middle transition
770 double mixingAngle1Minimum = -TMath::Pi() / 2;
771 double mixingAngle1Maximum = TMath::Pi() / 2;
772 int steps1 = 100;
773 double stepSize1 = (mixingAngle1Maximum - mixingAngle1Minimum) / steps1;
774 // mixing for the middle-low transition
775 double mixingAngle2Minimum = -TMath::Pi() / 2;
776 double mixingAngle2Maximum = TMath::Pi() / 2;
777 int steps2 = 100;
778 double stepSize2 = (mixingAngle2Maximum - mixingAngle2Minimum) / steps2;
779
780 // if appropriate, constrain the delta values
781 if(l1a == l1b) {
782 mixingAngle1Minimum = 0;
783 steps1 = 1;
784 }
785 if(l2a == l2b) {
786 mixingAngle2Minimum = 0;
787 steps2 = 1;
788 }
789
790 result = new TGraph(steps1);
791 double minChi2 = 1e6;
792 for(int i = 0; i < steps1; i++) {
793 double mixangle1 = mixingAngle1Minimum + i * stepSize1;
794 double delta1 = TMath::Tan(mixangle1);
795 for(int j = 0; j < steps2; j++) {
796 double mixangle2 = mixingAngle2Minimum + j * stepSize2;
797 double delta2 = TMath::Tan(mixangle2);
798 // calculate a2
799 double a2 = TGRSIFunctions::CalculateA2(j1, j2, j3, l1a, l1b, l2a, l2b, delta1, delta2);
800 // fix a2
801 fitter.Config().ParSettings(1).Set("a_{2}", a2);
802 fitter.Config().ParSettings(1).Fix();
803 // calculate a4
804 double a4 = TGRSIFunctions::CalculateA4(j1, j2, j3, l1a, l1b, l2a, l2b, delta1, delta2);
805 // fix a4
806 fitter.Config().ParSettings(2).Set("a_{4}", a4);
807 fitter.Config().ParSettings(2).Fix();
808 if(!fitter.FitFCN()) {
809 std::cerr << i << ", " << j << ": Fit failed using a2 " << a2 << ", a4 " << a4 << std::endl;
810 continue;
811 }
812 auto fitResult = fitter.Result();
813 // MinFcnValue() is the minimum chi2, ac.Np gives the number of data points
814 result->SetPoint(i, mixangle1, fitResult.MinFcnValue() / (ac.Np() - fitResult.NFreeParameters()));
815 if(fitResult.MinFcnValue() / (ac.Np() - fitResult.NFreeParameters()) < minChi2) {
816 minChi2 = fitResult.MinFcnValue() / (ac.Np() - fitResult.NFreeParameters());
817 bestParameters.assign(fitResult.GetParams(), fitResult.GetParams() + nPar);
818 }
819 }
820 }
821 return result;
822}
823
824std::vector<double> A2a4Method(TGraphErrors* data, TGraphErrors* z0, TGraphErrors* z2, TGraphErrors* z4)
825{
826 assert(data->GetN() == z0->GetN());
827 assert(data->GetN() == z2->GetN());
828 assert(data->GetN() == z4->GetN());
829 // create a copy of the data with cos(theta) as x-axis and fit it with a legenre polynomial
830 // this is to get initial conditions for our fit
831 auto* cosTheta = new TGraphErrors(*data);
832 auto* x = cosTheta->GetX();
833 for(int i = 0; i < cosTheta->GetN(); ++i) {
834 x[i] = TMath::Cos(x[i] / 180. * TMath::Pi());
835 }
836
837 int nPar = 3;
838 auto* legendre = new TF1("legendre", TGRSIFunctions::LegendrePolynomial, -1., 1., nPar);
839 legendre->SetParNames("a_{0}", "a_{2}", "a_{4}");
840 legendre->SetParameters(1., 0.5, 0.5);
841 cosTheta->Fit(legendre, "QN0");
842
843 // the actual fitting
844 Ac ac(data, z0, z2, z4);
845 ROOT::Fit::Fitter fitter;
846 fitter.SetFCN(nPar, ac);
847 // this is a good guess for the initial scale
848 fitter.Config().ParSettings(0) = ROOT::Fit::ParameterSettings("a_{0}", data->GetMaximum() / z0->GetMaximum(), 0.0001, -10., 10.);
849 for(int i = 1; i < nPar; ++i) {
850 // parameter settings arguments are parameter name, initial value, step size, minimum, and maximum
851 fitter.Config().ParSettings(i) = ROOT::Fit::ParameterSettings(Form("a_{%d}", 2 * i), legendre->GetParameter(i), 0.0001, -10., 10.);
852 }
853 fitter.Config().MinimizerOptions().SetPrintLevel(0);
854 fitter.Config().SetMinimizer("Minuit2", "Migrad"); // or simplex?
855 if(!fitter.FitFCN()) {
856 std::cerr << "Fit failed" << std::endl;
857 return {};
858 }
859
860 // get the fit result and print chi^2 and parameters
861 auto fitResult = fitter.Result();
862 // MinFcnValue() is the minimum chi2, ac.Np gives the number of data points
863 std::cout << "Reduced chi^2: " << fitResult.MinFcnValue() / (ac.Np() - fitResult.NFreeParameters()) << std::endl;
864 std::vector<double> parameters(fitResult.GetParams(), fitResult.GetParams() + nPar);
865 const auto* errors = fitResult.GetErrors();
866 std::cout << "Parameters a_0: " << parameters[0] << " +- " << errors[0] << ", a_2: " << parameters[1] << " +- " << errors[1] << ", a_4: " << parameters[2] << " +- " << errors[2] << std::endl;
867 TMatrixD covariance(nPar, nPar);
868 fitResult.GetCovarianceMatrix(covariance);
869
870 // create fit and residual graphs
871 auto* fit = static_cast<TGraphErrors*>(z0->Clone("fit"));
872 for(int i = 0; i < fit->GetN(); ++i) {
873#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 20, 0)
874 fit->SetPointY(i, parameters[0] * ((1. - parameters[1] - parameters[2]) * z0->GetPointY(i) + parameters[1] * z2->GetPointY(i) + parameters[2] * z4->GetPointY(i)));
875#else
876 fit->SetPoint(i, fit->GetX()[i], parameters[0] * ((1. - parameters[1] - parameters[2]) * z0->GetY()[i] + parameters[1] * z2->GetY()[i] + parameters[2] * z4->GetY()[i]));
877#endif
878 fit->SetPointError(i, 0., std::abs(parameters[0]) * TMath::Sqrt(TMath::Power((1. - parameters[1] - parameters[2]) * z0->GetErrorY(i), 2) + TMath::Power(parameters[1] * z2->GetErrorY(i), 2) + TMath::Power(parameters[2] * z4->GetErrorY(i), 2)));
879 }
880
881 auto* residual = static_cast<TGraphErrors*>(data->Clone("residual"));
882 for(int i = 0; i < residual->GetN(); ++i) {
883#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 20, 0)
884 residual->SetPointY(i, data->GetPointY(i) - fit->GetPointY(i));
885#else
886 residual->SetPoint(i, residual->GetX()[i], data->GetY()[i] - fit->GetY()[i]);
887#endif
888 residual->SetPointError(i, 0., TMath::Sqrt(TMath::Power(data->GetErrorY(i), 2) + TMath::Power(fit->GetErrorY(i), 2)));
889 }
890
891 // This text box will display the fit statistics
892 // with the margins of the pads, the center in x is at 0.55 (0.545 to be exact_, so we center around that point
893 auto* stats = new TPaveText(0.35, 0.7, 0.75, 0.95, "NDC");
894 stats->SetTextFont(133);
895 stats->SetTextSize(20);
896 stats->SetFillStyle(0);
897 stats->SetBorderSize(0);
898 stats->AddText(Form("a_{2} = %f #pm %f", parameters[1], errors[1]));
899 stats->AddText(Form("a_{4} = %f #pm %f", parameters[2], errors[2]));
900 stats->AddText(Form("#chi^{2}/NDF = %.2f", fitResult.MinFcnValue() / (ac.Np() - fitResult.NFreeParameters())));
901
902 // create canvas and two pads (big one for comparison and small one for residuals)
903 // wider left margin for y-axis labels and title
904 // same for the bottom margin of the residuals
905 auto* canvas = new TCanvas;
906 auto* resPad = new TPad("resPad", "resPad", 0., 0., 1., 0.3);
907 resPad->SetTopMargin(0.);
908 resPad->SetBottomMargin(0.22);
909 resPad->SetLeftMargin(0.1);
910 resPad->SetRightMargin(0.01);
911 resPad->Draw();
912 auto* compPad = new TPad("compPad", "compPad", 0., 0.3, 1., 1.);
913 compPad->SetTopMargin(0.01);
914 compPad->SetBottomMargin(0.);
915 compPad->SetLeftMargin(0.1);
916 compPad->SetRightMargin(0.01);
917 compPad->Draw();
918
919 // plot comparison of fit and data
920 compPad->cd();
921
922 auto* multiGraph = new TMultiGraph;
923 fit->SetLineColor(kRed);
924 fit->SetFillColor(kRed);
925 fit->SetMarkerColor(kRed);
926 multiGraph->Add(fit, "l3"); // 3 = filled contour between upper and lower error bars
927 data->SetMarkerStyle(kFullDotLarge);
928 multiGraph->Add(data, "p");
929
930 multiGraph->SetTitle(";;Normalized Counts;");
931
932 multiGraph->GetXaxis()->SetRangeUser(0., 180.);
933
934 multiGraph->GetYaxis()->CenterTitle();
935 multiGraph->GetYaxis()->SetTitleSize(0.05);
936 multiGraph->GetYaxis()->SetTitleOffset(1.);
937
938 multiGraph->Draw("a");
939
940 stats->Draw();
941
942 // plot residuals
943 resPad->cd();
944 residual->SetTitle(";#vartheta [^{o}];Residual");
945
946 residual->GetXaxis()->CenterTitle();
947 residual->GetXaxis()->SetTitleSize(0.1);
948 residual->GetXaxis()->SetLabelSize(0.1);
949 residual->GetXaxis()->SetRangeUser(0., 180.);
950
951 residual->GetYaxis()->CenterTitle();
952 residual->GetYaxis()->SetTitleSize(0.1);
953 residual->GetYaxis()->SetTitleOffset(0.5);
954 residual->GetYaxis()->SetLabelSize(0.08);
955
956 residual->Draw("ap");
957 auto* zeroLine = new TLine(0., 0., 180., 0.);
958 zeroLine->Draw("same");
959
960 fit->Write("A2a4Fit");
961 residual->Write("Residual");
962 multiGraph->Write("FitComparison");
963 canvas->Write("A2a4Canvas");
964
965 return parameters;
966}
int main(int argc, char **argv)
double GetYError(TGraphErrors *graph, const double &x)
TGraph * MixingMethod(TGraphErrors *data, TGraphErrors *z0, TGraphErrors *z2, TGraphErrors *z4, int twoJhigh, int twoJmid, int twoJlow, std::vector< double > &bestParameters)
std::vector< double > A2a4Method(TGraphErrors *data, TGraphErrors *z0, TGraphErrors *z2, TGraphErrors *z4)
double bgLow
double bgHigh
void Z2(TGraphErrors *z2)
TGraphErrors * fData
void SetZ(TGraphErrors *z0, TGraphErrors *z2, TGraphErrors *z4)
void Z4(TGraphErrors *z4)
double operator()(const double *p)
void Z0(TGraphErrors *z0)
TGraphErrors * fZ4
TGraphErrors * fZ0
void Data(TGraphErrors *data)
Ac(TGraphErrors *data=nullptr, TGraphErrors *z0=nullptr, TGraphErrors *z2=nullptr, TGraphErrors *z4=nullptr)
TGraphErrors * fZ2
void parse(int argc, char **argv, bool firstPass)
Definition ArgParser.h:333
ArgParseConfigT< T > & option(const std::string flag, T *output_location, bool firstPass)
Definition ArgParser.h:412
TF1 * GetBackground()
Definition TPeakFitter.h:65
void AddPeak(TSinglePeak *peak)
Definition TPeakFitter.h:42
TFitResultPtr Fit(TH1 *fit_hist, Option_t *opt="")
TF1 * GetFitFunction() const
Definition TSinglePeak.h:76
Double_t GetReducedChi2() const
Definition TSinglePeak.h:91
Double_t AreaErr() const
Definition TSinglePeak.h:58
Double_t Area() const
Definition TSinglePeak.h:57
double CalculateA2(double j1, double j2, double j3, double l1a, double l1b, double l2a, double l2b, double delta1, double delta2)
Double_t LegendrePolynomial(Double_t *x, Double_t *p)
double CalculateA4(double j1, double j2, double j3, double l1a, double l1b, double l2a, double l2b, double delta1, double delta2)