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