MaCh3  2.8.0
Reference Guide
ParameterHandlerGeneric.cpp
Go to the documentation of this file.
2 
3 // ********************************************
4 // ETA - YAML constructor
5 // this will replace the root file constructor but let's keep it in
6 // to do some validations
7 ParameterHandlerGeneric::ParameterHandlerGeneric(const std::vector<std::string>& YAMLFile, std::string name,
8  double threshold, int FirstPCA, int LastPCA) {
9 // ********************************************
10  MACH3LOG_INFO("Constructing instance of ParameterHandler using");
11  inputFile = YAMLFile[0];
12  matrixName = name;
13  pca = true;
14 
15  doSpecialStepProposal = false;
16  // Not using adaptive by default
17  use_adaptive = false;
18  for(unsigned int i = 0; i < YAMLFile.size(); i++)
19  {
20  MACH3LOG_INFO("{}", YAMLFile[i]);
21  }
22  MACH3LOG_INFO("as an input");
23 
24  if (threshold < 0 || threshold >= 1) {
25  MACH3LOG_INFO("Principal component analysis but given the threshold for the principal components to be less than 0, or greater than (or equal to) 1. This will not work");
26  MACH3LOG_INFO("Please specify a number between 0 and 1");
27  MACH3LOG_INFO("You specified: ");
28  MACH3LOG_INFO("Am instead calling the usual non-PCA constructor...");
29  pca = false;
30  }
31 
32  InitialiseFromConfig(YAMLFile);
33  // Call the innocent helper function
34  if (pca) ConstructPCA(threshold, FirstPCA, LastPCA);
35 
37 
38  MACH3LOG_DEBUG("Constructing instance of ParameterHandler");
40  // Print
41  Print();
42 }
43 
44 // ********************************************
45 void ParameterHandlerGeneric::LoadAndMergeYAML(const std::vector<std::string>& YAMLFile,
46  std::map<std::pair<int,int>, std::unique_ptr<TMatrixDSym>>& ThrowSubMatrixOverrides) {
47 // ********************************************
48  int running_num_file_pars = 0;
49 
50  _fYAMLDoc["Systematics"] = YAML::Node(YAML::NodeType::Sequence);
51  for(unsigned int i = 0; i < YAMLFile.size(); i++)
52  {
53  YAML::Node YAMLDocTemp = M3OpenConfig(YAMLFile[i]);
54 
55  if (YAMLDocTemp["ThrowMatrixOverride"]) { // LP: this allows us to put in
56  // proposal matrix overrides per
57  // parameter-containing file, add
58  // the block diagonal proposal
59  // matrix to a list and overwrite
60  // the throw matrix after set up.
61  auto filename =
62  YAMLDocTemp["ThrowMatrixOverride"]["file"].as<std::string>();
63  TFile *submatrix_file = TFile::Open(filename.c_str());
64 
65  auto matrixname =
66  YAMLDocTemp["ThrowMatrixOverride"]["matrix"].as<std::string>();
67  std::unique_ptr<TMatrixDSym> submatrix{
68  submatrix_file->Get<TMatrixDSym>(matrixname.c_str())};
69  if (!submatrix) {
70  MACH3LOG_CRITICAL("Covariance matrix {} doesn't exist in file: {}",
71  matrixname, filename);
72  throw MaCh3Exception(__FILE__, __LINE__);
73  }
74  auto numrows = submatrix->GetNrows();
75  // LP: the -1 here is because we specify the last index for consistency
76  // with PCAHandler, not the first index after the end as is more common
77  // throughout computer science...
78  ThrowSubMatrixOverrides[{running_num_file_pars,
79  running_num_file_pars + (numrows - 1)}] = std::move(submatrix);
80 
81  // LP: check names by default, but have option to disable check if you
82  // know what you're doing
83  if (!bool(YAMLDocTemp["ThrowMatrixOverride"]["check_names"]) ||
84  YAMLDocTemp["ThrowMatrixOverride"]["check_names"].as<bool>()) {
85  auto nametree = submatrix_file->Get<TTree>("param_names");
86  if (!nametree) {
87  MACH3LOG_CRITICAL("TTree param_names doesn't exist in file: {}. Set "
88  "ThrowMatrixOverride: {{ check_names: False }} to "
89  "disable this check.",
90  filename);
91  throw MaCh3Exception(__FILE__, __LINE__);
92  }
93  std::string *param_name = nullptr;
94  nametree->SetBranchAddress("name", &param_name);
95 
96  if (nametree->GetEntries() != int(YAMLDocTemp["Systematics"].size())) {
97  MACH3LOG_CRITICAL("TTree param_names in file: {} has {} entries, but "
98  "the corresponding yaml file only declares {} "
99  "parameters. Set ThrowMatrixOverride: {{ "
100  "check_names: False }} to disable this check.",
101  filename, nametree->GetEntries(),
102  YAMLDocTemp["Systematics"].size());
103  throw MaCh3Exception(__FILE__, __LINE__);
104  }
105 
106  int pit = 0;
107  for (const auto &param : YAMLDocTemp["Systematics"]) {
108  nametree->GetEntry(pit++);
109  auto yaml_pname = Get<std::string>(
110  param["Systematic"]["Names"]["FancyName"], __FILE__, __LINE__);
111  if ((*param_name) != yaml_pname) {
113  "TTree param_names in file: {} at entry {} has parameter {}, "
114  "but "
115  "the corresponding yaml parameter is named {}. Set "
116  "ThrowMatrixOverride: {{ "
117  "check_names: False }} to disable this check.",
118  filename, pit, (*param_name), yaml_pname);
119  throw MaCh3Exception(__FILE__, __LINE__);
120  }
121  }
122  }
123  submatrix_file->Close();
124  }
125 
126  for (const auto& item : YAMLDocTemp["Systematics"]) {
127  _fYAMLDoc["Systematics"].push_back(item);
128  running_num_file_pars++;
129  }
130  }
131 }
132 
133 // ********************************************
134 void ParameterHandlerGeneric::LoadCorrelationFromConfig(std::vector<std::map<std::string,double>>& Correlations,
135  std::map<std::string, int>& CorrNamesMap) {
136 // ********************************************
137  // ETA Now that we've been through all systematic let's fill the covmatrix
138  //This makes the root TCov from YAML
139  TMatrixDSym* _fCovMatrix = new TMatrixDSym(_fNumPar);
140  for(int j = 0; j < _fNumPar; j++) {
141  (*_fCovMatrix)(j, j) = _fError[j]*_fError[j];
142  //Get the map of parameter name to correlation from the Correlations object
143  for (auto const& pair : Correlations[j]) {
144  auto const& key = pair.first;
145  auto const& val = pair.second;
146  int index = -1;
147  //If you found the parameter name then get the index
148  if (CorrNamesMap.find(key) != CorrNamesMap.end()) {
149  index = CorrNamesMap[key];
150  } else {
151  MACH3LOG_ERROR("Parameter {} not in list! Check your spelling?", key);
152  throw MaCh3Exception(__FILE__ , __LINE__ );
153  }
154  double Corr1 = val;
155  double Corr2 = 0;
156  if(Correlations[index].find(_fFancyNames[j]) != Correlations[index].end()) {
157  Corr2 = Correlations[index][_fFancyNames[j]];
158  //Do they agree to better than float precision?
159  constexpr double tolerance = 1e-6;
160  if(std::abs(Corr2 - Corr1) > tolerance) {
161  MACH3LOG_ERROR("Correlations are not equal between {} and {}", _fFancyNames[j], key);
162  MACH3LOG_ERROR("Got : {} and {}", Corr2, Corr1);
163  throw MaCh3Exception(__FILE__ , __LINE__ );
164  }
165  } else {
166  MACH3LOG_ERROR("Correlation does not appear reciprocally between {} and {}", _fFancyNames[j], key);
167  throw MaCh3Exception(__FILE__ , __LINE__ );
168  }
169  (*_fCovMatrix)(j, index)= (*_fCovMatrix)(index, j) = Corr1*_fError[j]*_fError[index];
170  }
171  }
172 
173  //Now make positive definite
174  MakePosDef(_fCovMatrix);
175  SetCovMatrix(_fCovMatrix);
176 }
177 
178 // ********************************************
179 // ETA An init function for the YAML constructor
180 // All you really need from the YAML file is the number of Systematics
181 void ParameterHandlerGeneric::InitialiseFromConfig(const std::vector<std::string>& YAMLFile) {
182 // ********************************************
183  std::map<std::pair<int, int>, std::unique_ptr<TMatrixDSym>> ThrowSubMatrixOverrides;
184  LoadAndMergeYAML(YAMLFile, ThrowSubMatrixOverrides);
185 
186  // Set the covariance matrix
187  _fNumPar = int(_fYAMLDoc["Systematics"].size());
188 
190 
191  int i = 0;
192  std::vector<std::map<std::string,double>> Correlations(_fNumPar);
193  std::map<std::string, int> CorrNamesMap;
194 
195  std::vector<PendingFunctionalFlipProposal> PendingFunctionalFlipParameters;
196  //ETA - read in the systematics. Would be good to add in some checks to make sure
197  //that there are the correct number of entries i.e. are the _fNumPar for Names,
198  //PreFitValues etc etc.
199  for (auto const &param : _fYAMLDoc["Systematics"])
200  {
201  _fFancyNames[i] = Get<std::string>(param["Systematic"]["Names"]["FancyName"], __FILE__ , __LINE__);
202  _fPreFitValue[i] = Get<double>(param["Systematic"]["ParameterValues"]["PreFitValue"], __FILE__ , __LINE__);
203  _fIndivStepScale[i] = Get<double>(param["Systematic"]["StepScale"], __FILE__ , __LINE__);
204  _fError[i] = Get<double>(param["Systematic"]["Error"], __FILE__ , __LINE__);
205  if(_fError[i] <= 0) {
206  MACH3LOG_ERROR("Error for param {}({}) is negative and equal to {}", _fFancyNames[i], i, _fError[i]);
207  throw MaCh3Exception(__FILE__ , __LINE__ );
208  }
209  //ETA - a bit of a fudge but works
210  auto TempBoundsVec = GetBounds(param["Systematic"]["ParameterBounds"]);
211  _fLowBound[i] = TempBoundsVec[0];
212  _fUpBound[i] = TempBoundsVec[1];
213 
214  //ETA - now for parameters which are optional and have default values
215  _fFlatPrior[i] = GetFromManager<bool>(param["Systematic"]["FlatPrior"], false, __FILE__ , __LINE__);
216 
217  // Allow to fix param, this setting should be used only for params which are permanently fixed like baseline, please use global config for fixing param more flexibly
218  if(GetFromManager<bool>(param["Systematic"]["FixParam"], false, __FILE__ , __LINE__)) {
220  }
221 
222  if(param["Systematic"]["SpecialProposal"]) {
223  EnableSpecialProposal(param["Systematic"]["SpecialProposal"], i, PendingFunctionalFlipParameters);
224  }
225 
226  //Fill the map to get the correlations later as well
227  CorrNamesMap[param["Systematic"]["Names"]["FancyName"].as<std::string>()]=i;
228 
229  //Also loop through the correlations
230  if(param["Systematic"]["Correlations"]) {
231  for(unsigned int Corr_i = 0; Corr_i < param["Systematic"]["Correlations"].size(); ++Corr_i){
232  for (YAML::const_iterator it = param["Systematic"]["Correlations"][Corr_i].begin(); it!=param["Systematic"]["Correlations"][Corr_i].end();++it) {
233  Correlations[i][it->first.as<std::string>()] = it->second.as<double>();
234  }
235  }
236  }
237  i++;
238  } // end loop over para
239  if(i != _fNumPar) {
240  MACH3LOG_CRITICAL("Inconsistent number of params in Yaml {} vs {}, this indicate wrong syntax", i, i, _fNumPar);
241  throw MaCh3Exception(__FILE__ , __LINE__ );
242  }
243 
244  ResolveFunctionalFlips(PendingFunctionalFlipParameters);
245 
246  // load correlation
247  LoadCorrelationFromConfig(Correlations, CorrNamesMap);
248  if (_fNumPar <= 0) {
249  MACH3LOG_ERROR("ParameterHandler object has {} systematics!", _fNumPar);
250  throw MaCh3Exception(__FILE__ , __LINE__ );
251  }
252 
253  for(auto const & matovr : ThrowSubMatrixOverrides){
254  SetSubThrowMatrix(matovr.first.first, matovr.first.second, *matovr.second);
255  }
256 
257  Tunes = std::make_unique<ParameterTunes>(_fYAMLDoc["Systematics"]);
258 
259  MACH3LOG_INFO("Created covariance matrix from files: ");
260  for(const auto &file : YAMLFile){
261  MACH3LOG_INFO("{} ", file);
262  }
263  MACH3LOG_INFO("----------------");
264  MACH3LOG_INFO("Found {} systematics parameters in total", _fNumPar);
265  MACH3LOG_INFO("----------------");
266 }
267 
268 // ********************************************
270 // ********************************************
272 
273  _fParamType = std::vector<SystType>(_fNumPar);
274  _ParameterGroup = std::vector<std::string>(_fNumPar);
275  _fSampleNames = std::vector<std::vector<std::string>>(_fNumPar);
276 
277  //KS: We know at most how params we expect so reserve memory for max possible params. Later we will shrink to size to not waste memory. Reserving means slightly faster loading and possible less memory fragmentation.
278  NormParams.reserve(_fNumPar);
279  SplineParams.reserve(_fNumPar);
280  FuncParams.reserve(_fNumPar);
281  OscParams.reserve(_fNumPar);
282 
283  int i = 0;
284  unsigned int ParamCounter[SystType::kSystTypes] = {0};
285  //ETA - read in the systematics. Would be good to add in some checks to make sure
286  //that there are the correct number of entries i.e. are the _fNumPars for Names,
287  //PreFitValues etc etc.
288  for (auto const &param : _fYAMLDoc["Systematics"])
289  {
290  _ParameterGroup[i] = Get<std::string>(param["Systematic"]["ParameterGroup"], __FILE__ , __LINE__);
291  _fSampleNames[i] = GetFromManager<std::vector<std::string>>(param["Systematic"]["SampleNames"], {}, __FILE__, __LINE__);
292 
293  //Fill the map to get the correlations later as well
294  auto ParamType = Get<std::string>(param["Systematic"]["Type"], __FILE__ , __LINE__);
295  //Now load in variables for spline systematics only
296  if (ParamType == SystType_ToString(SystType::kSpline))
297  {
298  //Set param type
300  // Fill Spline info
301  SplineParams.push_back(GetSplineParameter(param["Systematic"], i));
302 
303  //Insert the mapping from the spline index i.e. the length of _fSplineNames etc
304  //to the Systematic index i.e. the counter for things like _fSampleID
305  _fSystToGlobalSystIndexMap[SystType::kSpline].insert(std::make_pair(ParamCounter[SystType::kSpline], i));
306  ParamCounter[SystType::kSpline]++;
307  } else if(ParamType == SystType_ToString(SystType::kNorm)) {
309  NormParams.push_back(GetNormParameter(param["Systematic"], i));
310  _fSystToGlobalSystIndexMap[SystType::kNorm].insert(std::make_pair(ParamCounter[SystType::kNorm], i));
311  ParamCounter[SystType::kNorm]++;
312  } else if(ParamType == SystType_ToString(SystType::kFunc)){
314  FuncParams.push_back(GetFunctionalParameters(param["Systematic"], i));
315  _fSystToGlobalSystIndexMap[SystType::kFunc].insert(std::make_pair(ParamCounter[SystType::kFunc], i));
316  ParamCounter[SystType::kFunc]++;
317  } else if(ParamType == SystType_ToString(SystType::kOsc)){
319  OscParams.push_back(GetOscillationParameters(param["Systematic"], i));
320  _fSystToGlobalSystIndexMap[SystType::kOsc].insert(std::make_pair(ParamCounter[SystType::kOsc], i));
321  ParamCounter[SystType::kOsc]++;
322  } else{
323  MACH3LOG_ERROR("Given unrecognised systematic type: {}", ParamType);
324  std::string expectedTypes = "Expecting ";
325  for (int s = 0; s < SystType::kSystTypes; ++s) {
326  if (s > 0) expectedTypes += ", ";
327  expectedTypes += SystType_ToString(static_cast<SystType>(s)) + "\"";
328  }
329  expectedTypes += ".";
330  MACH3LOG_ERROR(expectedTypes);
331  throw MaCh3Exception(__FILE__, __LINE__);
332  }
333  i++;
334  } //end loop over params
335 
336  //KS We resized them above to all params to fight memory fragmentation, now let's resize to fit only allocated memory to save RAM
337  NormParams.shrink_to_fit();
338  SplineParams.shrink_to_fit();
339  FuncParams.shrink_to_fit();
340  OscParams.shrink_to_fit();
341 }
342 
343 // ********************************************
345 // ********************************************
346  MACH3LOG_DEBUG("Deleting ParameterHandler");
347 }
348 
349 // ********************************************
350 // DB Grab the Spline Names for the relevant SampleName
351 const std::vector<std::string> ParameterHandlerGeneric::GetSplineParsNamesFromSampleName(const std::string& SampleName) const {
352 // ********************************************
353  std::vector<std::string> returnVec;
354  for (auto &pair : _fSystToGlobalSystIndexMap[SystType::kSpline]) {
355  auto &SplineIndex = pair.first;
356  auto &SystIndex = pair.second;
357  if (AppliesToSample(SystIndex, SampleName)) { //If parameter applies to required Sample
358  returnVec.push_back(SplineParams[SplineIndex]._fSplineNames);
359  }
360  }
361  return returnVec;
362 }
363 
364 // ********************************************
365 const std::vector<SplineInterpolation> ParameterHandlerGeneric::GetSplineInterpolationFromSampleName(const std::string& SampleName) const {
366 // ********************************************
367  std::vector<SplineInterpolation> returnVec;
368  for (auto &pair : _fSystToGlobalSystIndexMap[SystType::kSpline]) {
369  auto &SplineIndex = pair.first;
370  auto &SystIndex = pair.second;
371 
372  if (AppliesToSample(SystIndex, SampleName)) { //If parameter applies to required SampleID
373  returnVec.push_back(SplineParams.at(SplineIndex)._SplineInterpolationType);
374  }
375  }
376  return returnVec;
377 }
378 
379 // ********************************************
380 // DB Grab the Spline Modes for the relevant SampleName
381 const std::vector< std::vector<int> > ParameterHandlerGeneric::GetSplineModeVecFromSampleName(const std::string& SampleName) const {
382 // ********************************************
383  std::vector< std::vector<int> > returnVec;
384  //Need a counter or something to correctly get the index in _fSplineModes since it's not of length nPars
385  //Should probably just make a std::map<std::string, int> for param name to FD spline index
386  for (auto &pair : _fSystToGlobalSystIndexMap[SystType::kSpline]) {
387  auto &SplineIndex = pair.first;
388  auto &SystIndex = pair.second;
389  if (AppliesToSample(SystIndex, SampleName)) { //If parameter applies to required SampleID
390  returnVec.push_back(SplineParams.at(SplineIndex)._fSplineModes);
391  }
392  }
393  return returnVec;
394 }
395 
396 // ********************************************
397 // Get Norm params
398 NormParameter ParameterHandlerGeneric::GetNormParameter(const YAML::Node& param, const int Index) const {
399 // ********************************************
400  NormParameter norm;
401 
402  GetBaseParameter(param, Index, norm);
403 
404  // ETA size 0 to mean apply to all
405  // Ultimately all this information ends up in the NormParams vector
406  norm.modes = GetFromManager<std::vector<int>>(param["Mode"], {}, __FILE__ , __LINE__);
407  norm.pdgs = GetFromManager<std::vector<int>>(param["NeutrinoFlavour"], {}, __FILE__ , __LINE__);
408  norm.preoscpdgs = GetFromManager<std::vector<int>>(param["NeutrinoFlavourUnosc"], {}, __FILE__ , __LINE__);
409  norm.targets = GetFromManager<std::vector<int>>(param["TargetNuclei"], {}, __FILE__ , __LINE__);
410 
411  if(_fLowBound[Index] < 0.) {
412  MACH3LOG_ERROR("Normalisation Parameter {} ({}), has lower parameters bound which can go below 0 and is equal {}",
413  GetParFancyName(Index), Index, _fLowBound[Index]);
414  MACH3LOG_ERROR("Normalisation parameters can't go bellow 0 as this is unphysical");
415  throw MaCh3Exception(__FILE__, __LINE__);
416  }
417 
418  return norm;
419 }
420 
421 // ********************************************
422 // Get Base Param
423 void ParameterHandlerGeneric::GetBaseParameter(const YAML::Node& param, const int Index, TypeParameterBase& Parameter) const {
424 // ********************************************
425  Parameter.name = GetParFancyName(Index);
426 
427  // Set the global parameter index of the normalisation parameter
428  Parameter.index = Index;
429 
430  int NumKinematicCuts = 0;
431  if(param["KinematicCuts"]) {
432  NumKinematicCuts = int(param["KinematicCuts"].size());
433 
434  std::vector<std::string> TempKinematicStrings;
435  std::vector<std::vector<std::vector<double>>> TempKinematicBounds;
436  //First element of TempKinematicBounds is always -999, and size is then 3
437  for(int KinVar_i = 0 ; KinVar_i < NumKinematicCuts ; ++KinVar_i) {
438  //ETA: This is a bit messy, Kinematic cuts is a list of maps
439  for (YAML::const_iterator it = param["KinematicCuts"][KinVar_i].begin();it!=param["KinematicCuts"][KinVar_i].end();++it) {
440  TempKinematicStrings.push_back(it->first.as<std::string>());
441  TempKinematicBounds.push_back(Get2DBounds(it->second));
442  }
443  if(TempKinematicStrings.size() == 0) {
444  MACH3LOG_ERROR("Received a KinematicCuts node but couldn't read the contents (it's a list of single-element dictionaries (python) = map of pairs (C++))");
445  MACH3LOG_ERROR("For Param {}", Parameter.name);
446  throw MaCh3Exception(__FILE__, __LINE__);
447  }
448  }//KinVar_i
449  Parameter.KinematicVarStr = TempKinematicStrings;
450  Parameter.Selection = TempKinematicBounds;
451  }
452 
453  //Next ones are kinematic bounds on where normalisation parameter should apply
454  //We set a bool to see if any bounds exist so we can short-circuit checking all of them every step
455  bool HasKinBounds = false;
456 
457  if(Parameter.KinematicVarStr.size() > 0) HasKinBounds = true;
458 
459  Parameter.hasKinBounds = HasKinBounds;
460  //End of kinematic bound checking
461 }
462 
463 // ********************************************
464 // Grab the global syst index for the relevant SampleName
465 // i.e. get a vector of size nSplines where each entry is filled with the global syst number
466 const std::vector<int> ParameterHandlerGeneric::GetGlobalSystIndexFromSampleName(const std::string& SampleName, const SystType Type) const {
467 // ********************************************
468  std::vector<int> returnVec;
469  for (auto &pair : _fSystToGlobalSystIndexMap[Type]) {
470  auto &SystIndex = pair.second;
471  if (AppliesToSample(SystIndex, SampleName)) { //If parameter applies to required SampleID
472  returnVec.push_back(SystIndex);
473  }
474  }
475  return returnVec;
476 }
477 
478 // ********************************************
479 // Grab the global syst index for the relevant SampleName
480 // i.e. get a vector of size nSplines where each entry is filled with the global syst number
481 const std::vector<int> ParameterHandlerGeneric::GetSystIndexFromSampleName(const std::string& SampleName, const SystType Type) const {
482 // ********************************************
483  std::vector<int> returnVec;
484  for (auto &pair : _fSystToGlobalSystIndexMap[Type]) {
485  auto &SplineIndex = pair.first;
486  auto &systIndex = pair.second;
487  if (AppliesToSample(systIndex, SampleName)) { //If parameter applies to required SampleID
488  returnVec.push_back(SplineIndex);
489  }
490  }
491  return returnVec;
492 }
493 
494 // ********************************************
495 // Get Spline params
496 SplineParameter ParameterHandlerGeneric::GetSplineParameter(const YAML::Node& param, const int Index) const {
497 // ********************************************
498  SplineParameter Spline;
499 
500  GetBaseParameter(param, Index, Spline);
501  auto& SplinePar = param["SplineInformation"];
502  //Now get the Spline interpolation type
503  if (SplinePar["InterpolationType"]) {
504  for(int InterpType = 0; InterpType < kSplineInterpolations ; ++InterpType){
505  if(SplinePar["InterpolationType"].as<std::string>() == SplineInterpolation_ToString(SplineInterpolation(InterpType)))
506  Spline._SplineInterpolationType = SplineInterpolation(InterpType);
507  }
508  } else { //KS: By default use TSpline3
510  }
511 
512  Spline._fSplineNames = Get<std::string>(SplinePar["SplineName"], __FILE__ , __LINE__);
513  Spline._SplineKnotUpBound = GetFromManager<double>(SplinePar["SplineKnotUpBound"], M3::DefSplineKnotUpBound, __FILE__ , __LINE__);
514  Spline._SplineKnotLowBound = GetFromManager<double>(SplinePar["SplineKnotLowBound"], M3::DefSplineKnotLowBound, __FILE__ , __LINE__);
515 
517  MACH3LOG_WARN("Spline knot capping enabled with bounds [{}, {}]. For reliable fits, consider modifying the input generation instead.",
518  Spline._SplineKnotLowBound, Spline._SplineKnotUpBound);
519  }
520  //If there is no mode information given then this will be an empty vector
521  Spline._fSplineModes = GetFromManager(SplinePar["Mode"], std::vector<int>(), __FILE__ , __LINE__);
522 
523  return Spline;
524 }
525 
526 // ********************************************
527 bool ParameterHandlerGeneric::AppliesToSample(const int SystIndex, const std::string& SampleName) const {
528 // ********************************************
529  // Empty means apply to all
530  if (_fSampleNames[SystIndex].size() == 0) return true;
531 
532  // Check for unsupported wildcards in SampleName
533  if (SampleName.find('*') != std::string::npos) {
534  MACH3LOG_ERROR("Wildcards ('*') are not supported in sample name: '{}'", SampleName);
535  throw MaCh3Exception(__FILE__ , __LINE__ );
536  }
537  return M3::CaseInsensitiveMatchAny(SampleName, _fSampleNames[SystIndex]);
538 }
539 
540 // ********************************************
541 // Get Func params
542 FunctionalParameter ParameterHandlerGeneric::GetFunctionalParameters(const YAML::Node& param, const int Index) const {
543 // ********************************************
544  FunctionalParameter func;
545  GetBaseParameter(param, Index, func);
546 
547  func.modes = GetFromManager<std::vector<int>>(param["Mode"], std::vector<int>(), __FILE__ , __LINE__);
548 
549  return func;
550 }
551 
552 // ********************************************
553 // Get Osc params
554 OscillationParameter ParameterHandlerGeneric::GetOscillationParameters(const YAML::Node& param, const int Index) const {
555 // ********************************************
556  OscillationParameter OscParamInfo;
557  GetBaseParameter(param, Index, OscParamInfo);
558  OscParamInfo.NuOscName = Get<std::string>(param["NuOscName"], __FILE__ , __LINE__);
559 
560  return OscParamInfo;
561 }
562 
563 // ********************************************
564 // HH: Grab the Functional parameters for the relevant SampleName
565 const std::vector<FunctionalParameter> ParameterHandlerGeneric::GetFunctionalParametersFromSampleName(const std::string& SampleName) const {
566 // ********************************************
568 }
569 
570 // ********************************************
571 // DB Grab the Normalisation parameters for the relevant SampleName
572 const std::vector<NormParameter> ParameterHandlerGeneric::GetNormParsFromSampleName(const std::string& SampleName) const {
573 // ********************************************
575 }
576 
577 // ********************************************
578 // KS Grab the Osc parameters for the relevant SampleName
579 const std::vector<OscillationParameter> ParameterHandlerGeneric::GetOscParsFromSampleName(const std::string& SampleName) const {
580 // ********************************************
582 }
583 
584 // ********************************************
585 // KS Grab the Spline parameters for the relevant SampleName
586 const std::vector<SplineParameter> ParameterHandlerGeneric::GetSplineParsFromSampleName(const std::string& SampleName) const {
587 // ********************************************
589 }
590 
591 // ********************************************
592 template<typename ParamT>
593 std::vector<ParamT> ParameterHandlerGeneric::GetTypeParamsFromSampleName(const std::map<int, int>& indexMap,
594  const std::vector<ParamT>& params, const std::string& SampleName) const {
595 // ********************************************
596  std::vector<ParamT> returnVec;
597  for (const auto& pair : indexMap) {
598  const auto& localIndex = pair.first;
599  const auto& globalIndex = pair.second;
600  if (AppliesToSample(globalIndex, SampleName)) {
601  returnVec.push_back(params[localIndex]);
602  }
603  }
604  return returnVec;
605 }
606 
607 // ********************************************
608 // DB Grab the number of parameters for the relevant SampleName
609 int ParameterHandlerGeneric::GetNumParamsFromSampleName(const std::string& SampleName, const SystType Type) const {
610 // ********************************************
611  int returnVal = 0;
612  IterateOverParams(SampleName,
613  [&](int i) { return GetParamType(i) == Type; }, // Filter condition
614  [&](int) { returnVal += 1; } // Action to perform if filter passes
615  );
616  return returnVal;
617 }
618 
619 // ********************************************
620 // DB Grab the parameter names for the relevant SampleName
621 const std::vector<std::string> ParameterHandlerGeneric::GetParsNamesFromSampleName(const std::string& SampleName, const SystType Type) const {
622 // ********************************************
623  std::vector<std::string> returnVec;
624  IterateOverParams(SampleName,
625  [&](int i) { return GetParamType(i) == Type; }, // Filter condition
626  [&](int i) { returnVec.push_back(GetParFancyName(i)); } // Action to perform if filter passes
627  );
628  return returnVec;
629 }
630 
631 // ********************************************
632 // DB DB Grab the parameter indices for the relevant SampleName
633 const std::vector<int> ParameterHandlerGeneric::GetParsIndexFromSampleName(const std::string& SampleName, const SystType Type) const {
634 // ********************************************
635  std::vector<int> returnVec;
636  IterateOverParams(SampleName,
637  [&](int i) { return GetParamType(i) == Type; }, // Filter condition
638  [&](int i) { returnVec.push_back(i); } // Action to perform if filter passes
639  );
640  return returnVec;
641 }
642 
643 // ********************************************
644 template <typename FilterFunc, typename ActionFunc>
645 void ParameterHandlerGeneric::IterateOverParams(const std::string& SampleName, FilterFunc filter, ActionFunc action) const {
646 // ********************************************
647  for (int i = 0; i < _fNumPar; ++i) {
648  if ((AppliesToSample(i, SampleName)) && filter(i)) { // Common filter logic
649  action(i); // Specific action for each function
650  }
651  }
652 }
653 
654 // ********************************************
656 // ********************************************
657  for (int i = 0; i < _fNumPar; ++i) {
658  //ETA - set the name to be param_% as this is what ProcessorMCMC expects
659  _fNames[i] = "param_"+std::to_string(i);
660 
661  // KS: Plenty of MaCh3 processing script rely on osc params having "fancy name" this is to maintain backward compatibility with them
662  if(_fParamType[i] == kOsc) {
663  _fNames[i] = _fFancyNames[i];
664 
665  if(_ParameterGroup[i] != "Osc"){
666  MACH3LOG_ERROR("Parameter {}, is of type Oscillation but doesn't belong to Osc group", _fFancyNames[i]);
667  MACH3LOG_ERROR("It belongs to {} group", _ParameterGroup[i]);
668  throw MaCh3Exception(__FILE__ , __LINE__ );
669  }
670  }
671  #pragma GCC diagnostic push
672  #pragma GCC diagnostic ignored "-Wuseless-cast"
673  // Set ParameterHandler parameters (Curr = current, Prop = proposed, Sigma = step)
674  _fCurrVal[i] = _fPreFitValue[i];
675  _fPropVal[i] = static_cast<M3::float_t>(_fCurrVal[i]);
676  #pragma GCC diagnostic pop
677  }
678  Randomize();
679  //KS: Transfer the starting parameters to the PCA basis, you don't want to start with zero..
680  if (pca) {
681  PCAObj->SetInitialParameters();
682  }
683 }
684 
685 // ********************************************
686 // Print everything we know about the inputs we're Getting
688 // ********************************************
689  MACH3LOG_INFO("#################################################");
690  MACH3LOG_INFO("Printing ParameterHandlerGeneric:");
691 
693 
694  PrintNormParams();
695 
697 
699 
701 
703 
704  MACH3LOG_INFO("Finished");
705  MACH3LOG_INFO("#################################################");
706 
708 } // End
709 
710 // ********************************************
712 // ********************************************
714  {"Name", 10, 40, M3::Utils::Alignment::Left},
715  {"Prior", 10, 15, M3::Utils::Alignment::Right},
716  {"Error", 10, 15, M3::Utils::Alignment::Right},
717  {"Lower", 10, 15, M3::Utils::Alignment::Right},
718  {"Upper", 10, 15, M3::Utils::Alignment::Right},
719  {"StepScale", 10, 15, M3::Utils::Alignment::Right},
720  {"SampleNames", 10, 20, M3::Utils::Alignment::Left},
721  {"Type", 10, 20, M3::Utils::Alignment::Left},});
722 
723  for (int i = 0; i < GetNumParams(); ++i) {
724  const std::string errorString = fmt::format("{:.2f}", _fError[i]);
725  const std::string sampleNameString = M3::Utils::join(_fSampleNames[i], ", ");
726 
727  table.AddRow(i,
728  GetParFancyName(i),
729  M3::Utils::Cell(_fPreFitValue[i], "{:.2f}"),
730  "+/- " + errorString,
731  M3::Utils::Cell(_fLowBound[i], "{:.2f}"),
732  M3::Utils::Cell(_fUpBound[i], "{:.2f}"),
733  M3::Utils::Cell(_fIndivStepScale[i], "{:.2f}"),
734  sampleNameString,
736  }
737 
738  for (const auto& line : table.Render()) {
739  MACH3LOG_INFO("{}", line);
740  }
741 }
742 
743 // ********************************************
745 // ********************************************
746  // Output the normalisation parameters as a sanity check!
747  MACH3LOG_INFO("Normalisation parameters: {}", NormParams.size());
748  if(_fSystToGlobalSystIndexMap[SystType::kNorm].size() == 0) return;
749 
751  {"Global #", 10, 10, M3::Utils::Alignment::Right},
752  {"Name", 10, 40, M3::Utils::Alignment::Left},
753  {"Int. mode", 10, 20, M3::Utils::Alignment::Left},
754  {"Target", 10, 20, M3::Utils::Alignment::Left},
755  {"pdg", 10, 20, M3::Utils::Alignment::Left},});
756 
757  bool have_parameter_with_kin_bounds = false;
758 
759  for (std::size_t i = 0; i < NormParams.size(); ++i) {
760  table.AddRow(i,
761  NormParams[i].index,
762  NormParams[i].name,
763  NormParams[i].modes.empty() ? "all" : M3::Utils::join(NormParams[i].modes),
764  NormParams[i].targets.empty() ? "all" : M3::Utils::join(NormParams[i].targets),
765  NormParams[i].pdgs.empty() ? "all" : M3::Utils::join(NormParams[i].pdgs));
766 
767  if(NormParams[i].hasKinBounds) have_parameter_with_kin_bounds = true;
768  }
769 
770  for (const auto& line : table.Render()) {
771  MACH3LOG_INFO("{}", line);
772  }
773  if(have_parameter_with_kin_bounds) {
774  MACH3LOG_INFO("Normalisation parameters KinematicCuts information");
775 
777  {"Global #", 10, 10, M3::Utils::Alignment::Right},
778  {"Name", 10, 40, M3::Utils::Alignment::Left},
779  {"KinematicCut", 10, 20, M3::Utils::Alignment::Left},
780  {"Value", 10, 40, M3::Utils::Alignment::Left},});
781 
782  for (std::size_t i = 0; i < NormParams.size(); ++i) {
783  //skip parameters with no KinematicCuts
784  if(!NormParams[i].hasKinBounds) continue;
785 
786  const std::size_t ncuts = NormParams[i].KinematicVarStr.size();
787 
788  for(std::size_t icut = 0; icut < ncuts; ++icut) {
789  std::string kinematicCutValueString;
790 
791  for(const auto& value : NormParams[i].Selection[icut]) {
792  for (const auto& v : value) {
793  kinematicCutValueString += fmt::format("{:.2f} ", v);
794  }
795  }
796 
797  if(icut == 0) {
798  kinTable.AddRow(i,
799  NormParams[i].index,
800  NormParams[i].name,
801  NormParams[i].KinematicVarStr[icut],
802  kinematicCutValueString);
803  }
804  else {
805  kinTable.AddRow("",
806  "",
807  "",
808  NormParams[i].KinematicVarStr[icut],
809  kinematicCutValueString);
810  }
811  }
812  }
813 
814  for (const auto& line : kinTable.Render()) {
815  MACH3LOG_INFO("{}", line);
816  }
817  }
818  else
819  MACH3LOG_INFO("No normalisation parameters have KinematicCuts defined");
820 }
821 
822 // ********************************************
824 // ********************************************
825  MACH3LOG_INFO("Spline parameters: {}", _fSystToGlobalSystIndexMap[SystType::kSpline].size());
826  if(_fSystToGlobalSystIndexMap[SystType::kSpline].size() == 0) return;
827 
829  {"Name", 10, 40, M3::Utils::Alignment::Left},
830  {"Spline Name", 10, 40, M3::Utils::Alignment::Left},
831  {"Spline Interpolation", 10, 20, M3::Utils::Alignment::Left},
832  {"Low Knot Bound", 10, 20, M3::Utils::Alignment::Right},
833  {"Up Knot Bound", 10, 20, M3::Utils::Alignment::Right},});
834 
835  for (const auto& pair : _fSystToGlobalSystIndexMap[SystType::kSpline]) {
836  const auto& SplineIndex = pair.first;
837  const auto& GlobalIndex = pair.second;
838 
839  table.AddRow(SplineIndex,
840  GetParFancyName(GlobalIndex),
841  SplineParams[SplineIndex]._fSplineNames,
845  }
846 
847  for (const auto& line : table.Render()) {
848  MACH3LOG_INFO("{}", line);
849  }
850 }
851 
852 // ********************************************
854 // ********************************************
855  MACH3LOG_INFO("Functional parameters: {}", _fSystToGlobalSystIndexMap[SystType::kFunc].size());
856  if(_fSystToGlobalSystIndexMap[SystType::kFunc].size() == 0) return;
857 
859  {"Global #", 10, 10, M3::Utils::Alignment::Right},
860  {"Name", 10, 40, M3::Utils::Alignment::Left},});
861 
862  for (const auto& pair : _fSystToGlobalSystIndexMap[SystType::kFunc]) {
863  const auto& FuncIndex = pair.first;
864  const auto& GlobalIndex = pair.second;
865 
866  table.AddRow(FuncIndex,
867  GlobalIndex,
868  GetParFancyName(GlobalIndex));
869  }
870 
871  for (const auto& line : table.Render()) {
872  MACH3LOG_INFO("{}", line);
873  }
874 }
875 
876 // ********************************************
878 // ********************************************
879  MACH3LOG_INFO("Oscillation parameters: {}", _fSystToGlobalSystIndexMap[SystType::kOsc].size());
880  if(_fSystToGlobalSystIndexMap[SystType::kOsc].size() == 0) return;
881 
883  {"Global #", 10, 10, M3::Utils::Alignment::Right},
884  {"Name", 10, 40, M3::Utils::Alignment::Left},
885  {"NuOscName", 10, 40, M3::Utils::Alignment::Left},});
886 
887  for (const auto& pair : _fSystToGlobalSystIndexMap[SystType::kOsc]) {
888  const auto& OscIndex = pair.first;
889  const auto& GlobalIndex = pair.second;
890 
891  table.AddRow(OscIndex,
892  GlobalIndex,
893  GetParFancyName(GlobalIndex),
894  OscParams[OscIndex].NuOscName);
895  }
896 
897  for (const auto& line : table.Render()){
898  MACH3LOG_INFO("{}", line);
899  }
900 }
901 
902 // ********************************************
904 // ********************************************
905  // KS: Create a map to store the counts of unique strings, in principle this could be in header file
906  std::unordered_map<std::string, int> paramCounts;
907 
908  std::for_each(_ParameterGroup.begin(), _ParameterGroup.end(),
909  [&paramCounts](const std::string& param) {
910  paramCounts[param]++;
911  });
912 
913  MACH3LOG_INFO("Printing parameter groups");
914  // Output the counts
915  for (const auto& pair : paramCounts) {
916  MACH3LOG_INFO("Found {}: {} params", pair.second, pair.first);
917  }
918 }
919 
920 // ********************************************
921 std::vector<std::string> ParameterHandlerGeneric::GetUniqueParameterGroups() const {
922 // ********************************************
923  std::unordered_set<std::string> uniqueGroups;
924 
925  // Fill the set with unique values
926  for (const auto& param : _ParameterGroup) {
927  uniqueGroups.insert(param);
928  }
929 
930  // Convert to vector and return
931  std::vector<std::string> result(uniqueGroups.begin(), uniqueGroups.end());
932  return result;
933 }
934 
935 // ********************************************
936 // KS: Check if matrix is correctly initialised
938 // ********************************************
939  // KS: Lambda Function which simply checks if there are no duplicates in std::vector
940  auto CheckForDuplicates = [](const std::vector<std::string>& names, const std::string& nameType, bool Warning) {
941  std::unordered_map<std::string, size_t> seenStrings;
942  for (size_t i = 0; i < names.size(); ++i) {
943  const auto& name = names[i];
944  if (seenStrings.find(name) != seenStrings.end()) {
945  size_t firstIndex = seenStrings[name];
946  if(Warning){
947  MACH3LOG_WARN("There are two systematics with the same {} '{}', first at index {}, and again at index {}", nameType, name, firstIndex, i);
948  MACH3LOG_WARN("Is this desired?");
949  return;
950  } else {
951  MACH3LOG_CRITICAL("There are two systematics with the same {} '{}', first at index {}, and again at index {}", nameType, name, firstIndex, i);
952  throw MaCh3Exception(__FILE__, __LINE__);
953  }
954  }
955  seenStrings[name] = i;
956  }
957  };
958  std::vector<std::string> SplineNameTemp(SplineParams.size());
959  for(size_t it = 0; it < SplineParams.size(); it++){
960  SplineNameTemp[it] = SplineParams[it]._fSplineNames;
961  }
962  // KS: Checks if there are no duplicates in fancy names etc, this can happen if we merge configs etc
963  CheckForDuplicates(_fFancyNames, "_fFancyNames", false);
964  CheckForDuplicates(SplineNameTemp, "_fSplineNames", true);
965 }
966 
967 // ********************************************
968 // Function to set to prior parameters of a given group
969 void ParameterHandlerGeneric::SetGroupOnlyParameters(const std::vector< std::string>& Groups) {
970 // ********************************************
971  for(size_t i = 0; i < Groups.size(); i++){
972  SetGroupOnlyParameters(Groups[i]);
973  }
974 }
975 
976 // ********************************************
977 // Function to set to prior parameters of a given group
978 void ParameterHandlerGeneric::SetGroupOnlyParameters(const std::string& Group, const std::vector<double>& Pars) {
979 // ********************************************
980  #pragma GCC diagnostic push
981  #pragma GCC diagnostic ignored "-Wuseless-cast"
982  // If empty, set the proposed to prior
983  if (Pars.empty()) {
984  for (int i = 0; i < _fNumPar; i++) {
985  if(IsParFromGroup(i, Group)) _fPropVal[i] = static_cast<M3::float_t>(_fPreFitValue[i]);
986  }
987  } else{
988  const size_t ExpectedSize = static_cast<size_t>(GetNumParFromGroup(Group));
989  if (Pars.size() != ExpectedSize) {
990  MACH3LOG_ERROR("Number of param in group {} is {}, while you passed {}", Group, ExpectedSize, Pars.size());
991  throw MaCh3Exception(__FILE__, __LINE__);
992  }
993  int Counter = 0;
994  for (int i = 0; i < _fNumPar; i++) {
995  // If belongs to group set value from parsed vector, otherwise use propose value
996  if(IsParFromGroup(i, Group)){
997  _fPropVal[i] = static_cast<M3::float_t>(Pars[Counter]);
998  Counter++;
999  }
1000  }
1001  }
1002  // And if pca make the transfer
1003  if (pca) {
1004  PCAObj->TransferToPCA();
1005  PCAObj->TransferToParam();
1006  }
1007  #pragma GCC diagnostic pop
1008 }
1009 
1010 // ********************************************
1011 // Set parameters to be fixed in a given group
1013 // ********************************************
1014  for (int i = 0; i < _fNumPar; ++i)
1015  if(IsParFromGroup(i, Group)) SetFixParameter(i);
1016 }
1017 
1018 // ********************************************
1019 // Set parameters of several groups to be fixed
1020 void ParameterHandlerGeneric::SetFixGroupOnlyParameters(const std::vector< std::string>& Groups) {
1021 // ********************************************
1022  for(size_t i = 0; i < Groups.size(); i++)
1023  SetFixGroupOnlyParameters(Groups[i]);
1024 }
1025 
1026 // ********************************************
1027 // Set parameters to be free in a given group
1029 // ********************************************
1030  for (int i = 0; i < _fNumPar; ++i)
1031  if(IsParFromGroup(i, Group)) SetFreeParameter(i);
1032 }
1033 
1034 // ********************************************
1035 // Set parameters of several groups to be fixed
1036 void ParameterHandlerGeneric::SetFreeGroupOnlyParameters(const std::vector< std::string>& Groups) {
1037 // ********************************************
1038  for(size_t i = 0; i < Groups.size(); i++)
1039  SetFreeGroupOnlyParameters(Groups[i]);
1040 }
1041 
1042 // ********************************************
1043 // Checks if parameter belongs to a given group
1044 bool ParameterHandlerGeneric::IsParFromGroup(const int i, const std::string& Group) const {
1045 // ********************************************
1046  std::string groupLower = Group;
1047  std::string paramGroupLower = _ParameterGroup[i];
1048 
1049  // KS: Convert both strings to lowercase, this way comparison will be case insensitive
1050  std::transform(groupLower.begin(), groupLower.end(), groupLower.begin(), ::tolower);
1051  std::transform(paramGroupLower.begin(), paramGroupLower.end(), paramGroupLower.begin(), ::tolower);
1052 
1053  return groupLower == paramGroupLower;
1054 }
1055 
1056 // ********************************************
1057 int ParameterHandlerGeneric::GetNumParFromGroup(const std::string& Group) const {
1058 // ********************************************
1059  int Counter = 0;
1060  for (int i = 0; i < _fNumPar; i++) {
1061  if(IsParFromGroup(i, Group)) Counter++;
1062  }
1063  return Counter;
1064 }
1065 
1066 // ********************************************
1067 // Dump Matrix to ROOT file, useful when we need to pass matrix info to another fitting group
1068 void ParameterHandlerGeneric::DumpMatrixToFile(const std::string& Name) {
1069 // ********************************************
1070  // KS: Ideally we remove it eventually...
1071  TH2D* CorrMatrix = GetCorrelationMatrix();
1073  _fPreFitValue,
1074  _fError,
1075  _fLowBound,
1076  _fUpBound,
1078  _fFancyNames,
1079  _fFlatPrior,
1080  SplineParams,
1081  covMatrix,
1082  CorrMatrix,
1083  Name);
1084  delete CorrMatrix;
1085  MACH3LOG_INFO("Finished dumping ParameterHandler object");
1086 }
#define MACH3LOG_CRITICAL
Definition: MaCh3Logger.h:38
#define MACH3LOG_DEBUG
Definition: MaCh3Logger.h:34
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
std::string SplineInterpolation_ToString(const SplineInterpolation i)
Convert a LLH type to a string.
SplineInterpolation
Make an enum of the spline interpolation type.
@ kTSpline3
Default TSpline3 interpolation .
@ kSplineInterpolations
This only enumerates.
std::string SystType_ToString(const SystType i)
Convert a Syst type type to a string.
SystType
@ kNorm
For normalisation parameters.
@ kSpline
For splined parameters (1D)
@ kSystTypes
This only enumerates.
@ kOsc
For oscillation parameters.
@ kFunc
For functional parameters.
#define Get2DBounds(filename)
Definition: YamlHelper.h:591
Type GetFromManager(const YAML::Node &node, const Type defval, const std::string &File, const int Line)
Get content of config file if node is not found take default value specified.
Definition: YamlHelper.h:328
#define M3OpenConfig(filename)
Macro to simplify calling LoadYaml with file and line info.
Definition: YamlHelper.h:589
#define GetBounds(filename)
Definition: YamlHelper.h:590
Creates fancy formatted text tables for terminal output.
Definition: TablePrinter.h:50
void AddRow(Args &&... args)
Add a row to the table.
Definition: TablePrinter.h:57
Custom exception class used throughout MaCh3.
int GetNumParams() const
Get total number of parameters.
bool use_adaptive
Are we using AMCMC?
void EnableSpecialProposal(const YAML::Node &param, const int Index, std::vector< PendingFunctionalFlipProposal > &PendingFunctionalFlipParameters)
Enable special proposal.
std::string inputFile
The input root file we read in.
TH2D * GetCorrelationMatrix() const
KS: Convert covariance matrix to correlation matrix and return TH2D which can be used for fancy plott...
void SetCovMatrix(TMatrixDSym *cov)
Set covariance matrix.
std::vector< M3::float_t > _fPropVal
Proposed value of the parameter.
std::unique_ptr< ParameterTunes > Tunes
Struct containing information about adaption.
void ReserveMemory(const int size)
Initialise vectors with parameters information.
std::vector< std::string > _fFancyNames
Fancy name for example rather than param_0 it is MAQE, useful for human reading.
bool doSpecialStepProposal
Check if any of special step proposal were enabled.
std::vector< bool > _fFlatPrior
Whether to apply flat prior or not.
std::string matrixName
Name of cov matrix.
std::string GetParFancyName(const int i) const
Get fancy name of the Parameter.
std::vector< double > _fError
Prior error on the parameter.
void SetFixParameter(const int i)
Set parameter to be fixed at prior value.
YAML::Node _fYAMLDoc
Stores config describing systematics.
std::unique_ptr< PCAHandler > PCAObj
Struct containing information about PCA.
int _fNumPar
Number of systematic parameters.
void ConstructPCA(const double eigen_threshold, int FirstPCAdpar, int LastPCAdpar)
CW: Calculate eigen values, prepare transition matrices and remove param based on defined threshold.
std::vector< double > _fLowBound
Lowest physical bound, parameter will not be able to go beyond it.
std::vector< double > _fCurrVal
Current value of the parameter.
TMatrixDSym * covMatrix
The covariance matrix.
std::vector< double > _fPreFitValue
Parameter value dictated by the prior model. Based on it penalty term is calculated.
void Randomize() _noexcept_
"Randomize" the parameters in the covariance class for the proposed step. Used the proposal kernel an...
std::vector< std::string > _fNames
ETA _fNames is set automatically in the covariance class to be something like param_i,...
void ResolveFunctionalFlips(std::vector< PendingFunctionalFlipProposal > &PendingFunctionalFlipParameters)
Resolve queued functional flips after parameter names are known.
void SetFreeParameter(const int i)
Set parameter to be treated as free.
std::vector< double > _fUpBound
Upper physical bound, parameter will not be able to go beyond it.
void SetSubThrowMatrix(int first_index, int last_index, TMatrixDSym const &subcov)
bool pca
perform PCA or not
std::vector< double > _fIndivStepScale
Individual step scale used by MCMC algorithm.
void MakePosDef(TMatrixDSym *cov=nullptr, bool verbose=true)
Make matrix positive definite by adding small values to diagonal, necessary for inverting matrix.
void PrintGlobablInfo() const
Prints general information about the ParameterHandler object.
void Print() const
Print information about the whole object once it is set.
std::vector< SplineParameter > SplineParams
Vector containing info for normalisation systematics.
FunctionalParameter GetFunctionalParameters(const YAML::Node &param, const int Index) const
Get Func params.
const std::vector< NormParameter > GetNormParsFromSampleName(const std::string &SampleName) const
DB Get norm/func parameters depending on given SampleName.
std::vector< std::string > GetUniqueParameterGroups() const
KS: Get names of all unique parameter groups.
ParameterHandlerGeneric(const std::vector< std::string > &FileNames, std::string name="xsec_cov", double threshold=-1, int FirstPCAdpar=-999, int LastPCAdpar=-999)
Constructor.
void PrintSplineParams() const
Prints spline parameters.
void IterateOverParams(const std::string &SampleName, FilterFunc filter, ActionFunc action) const
Iterates over parameters and applies a filter and action function.
const std::vector< int > GetParsIndexFromSampleName(const std::string &SampleName, const SystType Type) const
DB Grab the parameter indices for the relevant SampleName.
SplineParameter GetSplineParameter(const YAML::Node &param, const int Index) const
Get Spline params.
SystType GetParamType(const int i) const
Returns enum describing our param type.
const std::vector< int > GetSystIndexFromSampleName(const std::string &SampleName, const SystType Type) const
Grab the index of the syst relative to global numbering.
const std::vector< OscillationParameter > GetOscParsFromSampleName(const std::string &SampleName) const
KS Grab the Osc parameters for the relevant SampleName.
void GetBaseParameter(const YAML::Node &param, const int Index, TypeParameterBase &Parameter) const
Fill base parameters.
std::vector< NormParameter > NormParams
Vector containing info for normalisation systematics.
double GetParSplineKnotUpperBound(const int i) const
EM: value at which we cap spline knot weight.
std::vector< std::map< int, int > > _fSystToGlobalSystIndexMap
Map between number of given parameter type with global parameter numbering. For example 2nd norm para...
void LoadCorrelationFromConfig(std::vector< std::map< std::string, double >> &Correlations, std::map< std::string, int > &CorrNamesMap)
Load correlation from yaml config.
void SetGroupOnlyParameters(const std::string &Group, const std::vector< double > &Pars={})
KS Function to set to prior parameters of a given group or values from vector.
std::vector< SystType > _fParamType
Type of parameter like norm, spline etc.
const std::vector< SplineParameter > GetSplineParsFromSampleName(const std::string &SampleName) const
KS: Grab the Spline parameters for the relevant SampleName.
void PrintOscillationParams() const
Prints oscillation parameters.
const std::vector< FunctionalParameter > GetFunctionalParametersFromSampleName(const std::string &SampleName) const
HH Get functional parameters for the relevant SampleName.
void SetFreeGroupOnlyParameters(const std::string &Group)
TN Method to set parameters within a group to be treated as free.
void InitParametersTypeFromConfig()
Parses the YAML configuration to set up cross-section parameters. The YAML file defines the types of ...
std::vector< std::vector< std::string > > _fSampleNames
Tells to which samples object param should be applied.
std::vector< ParamT > GetTypeParamsFromSampleName(const std::map< int, int > &indexMap, const std::vector< ParamT > &params, const std::string &SampleName) const
Retrieve parameters that apply to a given sample name.
std::vector< FunctionalParameter > FuncParams
Vector containing info for functional systematics.
int GetNumParamsFromSampleName(const std::string &SampleName, const SystType Type) const
DB Grab the number of parameters for the relevant SampleName.
void PrintFunctionalParams() const
Prints functional parameters.
const std::vector< std::string > GetParsNamesFromSampleName(const std::string &SampleName, const SystType Type) const
DB Grab the parameter names for the relevant SampleName.
std::vector< OscillationParameter > OscParams
Vector containing info for functional systematics.
void DumpMatrixToFile(const std::string &Name)
Dump Matrix to ROOT file, useful when we need to pass matrix info to another fitting group.
const std::vector< std::string > GetSplineParsNamesFromSampleName(const std::string &SampleName) const
DB Get spline parameters depending on given SampleName.
SplineInterpolation GetParSplineInterpolation(const int i) const
Get interpolation type for a given parameter.
void InitParameters()
Initializes the systematic parameters from the configuration file. This function loads parameters lik...
const std::vector< int > GetGlobalSystIndexFromSampleName(const std::string &SampleName, const SystType Type) const
DB Get spline parameters depending on given SampleName.
OscillationParameter GetOscillationParameters(const YAML::Node &param, const int Index) const
Get Osc params.
NormParameter GetNormParameter(const YAML::Node &param, const int Index) const
Get Norm params.
bool AppliesToSample(const int SystIndex, const std::string &SampleName) const
Check if parameter is affecting given sample name.
const std::vector< SplineInterpolation > GetSplineInterpolationFromSampleName(const std::string &SampleName) const
Get the interpolation types for splines affecting a particular SampleName.
bool IsParFromGroup(const int i, const std::string &Group) const
Checks if parameter belongs to a given group.
void CheckCorrectInitialisation() const
KS: Check if matrix is correctly initialised.
void InitialiseFromConfig(const std::vector< std::string > &YAMLFile)
Initialisation of the class using config.
void SetFixGroupOnlyParameters(const std::string &Group)
TN Method to set parameters within a group to be fixed to their prior values.
std::vector< std::string > _ParameterGroup
KS: Allow to group parameters for example to affect only cross-section or only flux etc.
void LoadAndMergeYAML(const std::vector< std::string > &YAMLFile, std::map< std::pair< int, int >, std::unique_ptr< TMatrixDSym >> &overrides)
Initialise single yaml based on several yaml files.
double GetParSplineKnotLowerBound(const int i) const
EM: value at which we cap spline knot weight.
void PrintNormParams() const
Prints normalization parameters.
int GetNumParFromGroup(const std::string &Group) const
KS: Check how many parameters are associated with given group.
const std::vector< std::vector< int > > GetSplineModeVecFromSampleName(const std::string &SampleName) const
DB Grab the Spline Modes for the relevant SampleName.
void PrintParameterGroups() const
Prints groups of parameters.
static std::string Cell(T &&value, std::string_view format)
Format a value using a runtime fmt format string.
Definition: TablePrinter.h:44
std::string join(const Container &values, std::string_view separator=" ")
Join all values in a container into a single string.
Definition: TablePrinter.h:36
@ Right
Align text to the right.
@ Left
Align text to the left.
constexpr static const double DefSplineKnotUpBound
Default value for spline knot capping, default mean not capping is being applied.
Definition: Core.h:86
double float_t
Definition: Core.h:37
constexpr static const double DefSplineKnotLowBound
Default value for spline knot capping, default mean not capping is being applied.
Definition: Core.h:88
void DumpParamHandlerToFile(const int _fNumPar, const std::vector< double > &_fPreFitValue, const std::vector< double > &_fError, const std::vector< double > &_fLowBound, const std::vector< double > &_fUpBound, const std::vector< double > &_fIndivStepScale, const std::vector< std::string > &_fFancyNames, const std::vector< bool > &_fFlatPrior, const std::vector< SplineParameter > &SplineParams, TMatrixDSym *covMatrix, TH2D *CorrMatrix, const std::string &Name)
Dump Matrix to ROOT file, useful when we need to pass matrix info to another fitting group.
bool CaseInsensitiveMatchAny(std::string Text, const std::vector< std::string > &Patterns)
Matches a string against a simple wildcard Pattern using regex. Is not case sensitive.
HH - Functional parameters Carrier for whether you want to apply a systematic to an event or not.
std::vector< int > modes
Mode which parameter applies to.
ETA - Normalisations for cross-section parameters Carrier for whether you want to apply a systematic ...
std::vector< int > preoscpdgs
Preosc PDG which parameter applies to.
std::vector< int > modes
Mode which parameter applies to.
std::vector< int > pdgs
PDG which parameter applies to.
std::vector< int > targets
Targets which parameter applies to.
KS: Struct holding info about oscillation Systematics.
std::string NuOscName
Parameter name in NuOscillator.
Flat representation of a spline index entry.
Definition: SplineCommon.h:33
KS: Struct holding info about Spline Systematics.
SplineInterpolation _SplineInterpolationType
Spline interpolation vector.
double _SplineKnotUpBound
EM: Cap spline knot higher value.
double _SplineKnotLowBound
EM: Cap spline knot lower value.
std::vector< int > _fSplineModes
Modes to which spline applies (valid only for binned splines)
std::string _fSplineNames
Name of spline in TTree (TBranch),.
Base class storing info for parameters types, helping unify codebase.
int index
Parameter number of this normalisation in current systematic model.
bool hasKinBounds
Does this parameter have kinematic bounds.
std::string name
Name of parameters.
std::vector< std::string > KinematicVarStr
std::vector< std::vector< std::vector< double > > > Selection