MaCh3  2.8.0
Reference Guide
ParameterHandlerBase.cpp
Go to the documentation of this file.
2 #include "Utils/IOUtils.h"
3 
4 #include <regex>
5 
6 // ********************************************
7 ParameterHandlerBase::ParameterHandlerBase(std::string name, std::string file, double threshold, int FirstPCA, int LastPCA)
8  : inputFile(file), pca(true) {
9 // ********************************************
10  MACH3LOG_DEBUG("Constructing instance of ParameterHandler");
11  doSpecialStepProposal = false;
12  // Not using adaptive by default
13  use_adaptive = false;
14  if (threshold < 0 || threshold >= 1) {
15  MACH3LOG_INFO("NOTE: {} {}", name, file);
16  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");
17  MACH3LOG_INFO("Please specify a number between 0 and 1");
18  MACH3LOG_INFO("You specified: ");
19  MACH3LOG_INFO("Am instead calling the usual non-PCA constructor...");
20  pca = false;
21  }
22 
23  InitFromFile(name, file);
24 
25  // Call the innocent helper function
26  if (pca) ConstructPCA(threshold, FirstPCA, LastPCA);
27 }
28 
29 // ********************************************
30 //Destructor
32 // ********************************************
33  delete[] randParams;
34  delete[] corr_throw;
35 
36  if (covMatrix != nullptr) delete covMatrix;
37  if (invCovMatrix != nullptr) delete invCovMatrix;
38  if (throwMatrix != nullptr) delete throwMatrix;
39  for(int i = 0; i < _fNumPar; i++) {
40  delete[] throwMatrixCholDecomp[i];
41  }
42  delete[] throwMatrixCholDecomp;
43 }
44 
45 // ********************************************
46 void ParameterHandlerBase::ConstructPCA(const double eigen_threshold, int FirstPCAdpar, int LastPCAdpar) {
47 // ********************************************
48  if(AdaptiveHandler) {
49  MACH3LOG_ERROR("Adaption has been enabled and now trying to enable PCA. Right now both configuration don't work with each other");
50  throw MaCh3Exception(__FILE__ , __LINE__ );
51  }
52 
53  PCAObj = std::make_unique<PCAHandler>();
54  //Check whether first and last pcadpar are set and if not just PCA everything
55  if(FirstPCAdpar == -999 || LastPCAdpar == -999) {
56  if(FirstPCAdpar == -999 && LastPCAdpar == -999) {
57  FirstPCAdpar = 0;
58  LastPCAdpar = covMatrix->GetNrows()-1;
59  }
60  else{
61  MACH3LOG_ERROR("You must either leave FirstPCAdpar and LastPCAdpar at -999 or set them both to something");
62  throw MaCh3Exception(__FILE__ , __LINE__ );
63  }
64  }
65 
66  PCAObj->ConstructPCA(covMatrix, FirstPCAdpar, LastPCAdpar, eigen_threshold, _fNumPar);
67  PCAObj->SetupPointers(&_fCurrVal, &_fPropVal);
68  // Make a note that we have now done PCA
69  pca = true;
70 }
71 
72 // ********************************************
73 void ParameterHandlerBase::InitFromFile(const std::string& name, const std::string& file) {
74 // ********************************************
75  // Set the covariance matrix from input ROOT file (e.g. flux, ND280, NIWG)
76  TFile *infile = new TFile(file.c_str(), "READ");
77  if (infile->IsZombie()) {
78  MACH3LOG_ERROR("Could not open input covariance ROOT file {} !!!", file);
79  MACH3LOG_ERROR("Was about to retrieve matrix with name {}", name);
80  throw MaCh3Exception(__FILE__ , __LINE__ );
81  }
82 
83  TMatrixDSym *CovMat = static_cast<TMatrixDSym*>(infile->Get(name.c_str()));
84 
85  if (!CovMat) {
86  MACH3LOG_ERROR("Could not find covariance matrix name {} in file {}", name, file);
87  MACH3LOG_ERROR("Are you really sure {} exists in the file?", name);
88  throw MaCh3Exception(__FILE__ , __LINE__ );
89  }
90 
91  // Set the covariance matrix
92  _fNumPar = CovMat->GetNrows();
93 
95  SetName(name);
96  MakePosDef(CovMat);
97  SetCovMatrix(CovMat);
98 
99  infile->Close();
100 
101  MACH3LOG_INFO("Created covariance matrix named: {}", GetName());
102  MACH3LOG_INFO("from file: {}", file);
103  delete infile;
104 }
105 
106 // ********************************************
107 void ParameterHandlerBase::EnableSpecialProposal(const YAML::Node& param,
108  const int Index,
109  std::vector<PendingFunctionalFlipProposal>& PendingFunctionalFlipParameters){
110 // ********************************************
111  doSpecialStepProposal = true;
112 
113  bool CircEnabled = false;
114  std::pair<double, double> circular_bounds;
115 
116  bool FlipEnabled = false;
117  std::string flip_group;
118  double flip_point;
119 
120  bool FunctionalFlipEnabled = false;
121  YAML::Node functional_flip;
122 
123  if (param["CircularBounds"]) {
124  CircEnabled = true;
125  circular_bounds = Get<std::pair<double, double>>(param["CircularBounds"], __FILE__, __LINE__);
126  }
127 
128  if (param["FlipParameter"]) {
129  FlipEnabled = true;
130  // grab flip group if it exists, otherwise use the parameter name as the group
131  if (param["FlipGroup"]) {
132  flip_group = Get<std::string>(param["FlipGroup"], __FILE__, __LINE__);
133  } else {
134  flip_group = GetParFancyName(Index);
135  }
136  flip_point = Get<double>(param["FlipParameter"], __FILE__, __LINE__);
137  }
138 
139  if (param["FunctionalFlip"]) {
140  FunctionalFlipEnabled = true;
141  // grab functional flip details if needed
142  if (param["FlipGroup"]) {
143  flip_group = Get<std::string>(param["FlipGroup"], __FILE__, __LINE__);
144  } else {
145  flip_group = GetParFancyName(Index);
146  }
147  functional_flip = param["FunctionalFlip"];
148  }
149 
150  if (!CircEnabled && !FlipEnabled && !FunctionalFlipEnabled) {
151  MACH3LOG_ERROR("None of Special Proposal were enabled even though param {}, has SpecialProposal entry in Yaml", GetParFancyName(Index));
152  throw MaCh3Exception(__FILE__, __LINE__);
153  }
154 
155 
156  if (FlipEnabled && FunctionalFlipEnabled) {
157  MACH3LOG_ERROR("Parameter {} enables both FlipParameter and FunctionalFlip; choose exactly one flip type", GetParFancyName(Index));
158  throw MaCh3Exception(__FILE__, __LINE__);
159  }
160 
161  if (CircEnabled) {
162  CircularBoundsIndex.push_back(Index);
163  CircularBoundsValues.push_back(circular_bounds);
164  MACH3LOG_INFO("Enabling CircularBounds for parameter {} with range [{}, {}]",
165  GetParFancyName(Index),
166  circular_bounds.first,
167  circular_bounds.second);
168  // KS: Make sure circular bounds are within physical bounds. If we are outside of physics bound MCMC will never explore such phase space region
169  if (circular_bounds.first < _fLowBound.at(Index) || circular_bounds.second > _fUpBound.at(Index)) {
170  MACH3LOG_ERROR("Circular bounds [{}, {}] for parameter {} exceed physical bounds [{}, {}]",
171  circular_bounds.first, circular_bounds.second,
172  GetParFancyName(Index),
173  _fLowBound.at(Index), _fUpBound.at(Index));
174  throw MaCh3Exception(__FILE__, __LINE__);
175  }
176  // KS: Make sure CircularPrior is applied only to param with flat prior. Sadly doesn't work with Gaussian
177  if(GetFlatPrior(Index) == false) {
178  MACH3LOG_ERROR("Enabled CircularPrior for parameter {}, which has gaussian prior", GetParFancyName(Index));
179  MACH3LOG_ERROR("This is not supported, CircularPrior only works with flat prior");
180  MACH3LOG_ERROR("Change FlatPrior in Parameter config to true");
181  throw MaCh3Exception(__FILE__, __LINE__);
182  }
183  }
184 
185  if (FlipEnabled) {
186  FlipGroup& group = FlipGroups[flip_group];
187  group.FlipParameterIndex.push_back(Index);
188  group.FlipParameterPoint.push_back(flip_point);
189 
190  MACH3LOG_INFO("Enabling Flipping for parameter {} in group {} with value {}",
191  GetParFancyName(Index),
192  flip_group,
193  flip_point);
194  }
195 
196  if (FunctionalFlipEnabled) {
197  FlipGroups[flip_group];
198  QueueFunctionalFlip(PendingFunctionalFlipParameters, functional_flip, Index, flip_group); // leave the resolution of the functional flips until after all the params have been loaded in
199 
200  MACH3LOG_INFO("Enabling Functional Flipping for parameter {} in group {} with config {}",
201  GetParFancyName(Index),
202  flip_group,
203  YAML::Dump(functional_flip));
204  }
205 
206  if (CircEnabled && FlipEnabled) {
207  if (flip_point < circular_bounds.first || flip_point > circular_bounds.second) {
208  MACH3LOG_ERROR("FlipParameter value {} for parameter {} is outside the CircularBounds [{}, {}]",
209  flip_point, GetParFancyName(Index), circular_bounds.first, circular_bounds.second);
210  throw MaCh3Exception(__FILE__, __LINE__);
211  }
212 
213  const double low = circular_bounds.first;
214  const double high = circular_bounds.second;
215 
216  // Sanity check: ensure flipping any x in [low, high] keeps the result in [low, high]
217  const double flipped_low = 2 * flip_point - low;
218  const double flipped_high = 2 * flip_point - high;
219  const double min_flip = std::min(flipped_low, flipped_high);
220  const double max_flip = std::max(flipped_low, flipped_high);
221 
222  if (min_flip < low || max_flip > high) {
223  MACH3LOG_ERROR("Flipping about point {} for parameter {} would leave circular bounds [{}, {}]",
224  flip_point, GetParFancyName(Index), low, high);
225  throw MaCh3Exception(__FILE__, __LINE__);
226  }
227  }
228 }
229 
230 // ********************************************
231 void ParameterHandlerBase::QueueFunctionalFlip(std::vector<PendingFunctionalFlipProposal>& PendingFunctionalFlipParameters,
232  const YAML::Node& param, const int index, const std::string& group_name) {
233 // ********************************************
234  PendingFunctionalFlipProposal pending_flip;
235  pending_flip.target_index = index;
236  pending_flip.group_name = group_name;
237  pending_flip.config = YAML::Clone(param);
238  PendingFunctionalFlipParameters.push_back(std::move(pending_flip));
239 }
240 
241 // ********************************************
242 void ParameterHandlerBase::ResolveFunctionalFlips(std::vector<PendingFunctionalFlipProposal>& PendingFunctionalFlipParameters) {
243 // ********************************************
244  for (const auto& pending_flip : PendingFunctionalFlipParameters) {
245  AddFunctionalFlip(pending_flip.config, pending_flip.target_index, pending_flip.group_name);
246  }
247 
248  PendingFunctionalFlipParameters.clear();
249 }
250 
251 // ********************************************
252 void ParameterHandlerBase::AddFunctionalFlip(const YAML::Node& param, const int index, const std::string& group_name) {
253 // ********************************************
254  YAML::Node functional_flip = YAML::Clone(param);
255  const YAML::Node formula = functional_flip["Formula"];
256  const YAML::Node parameters = functional_flip["Parameters"];
257 
258  if (!formula) {
259  MACH3LOG_ERROR("FunctionalFlip for parameter {} is missing Formula", GetParFancyName(index));
260  throw MaCh3Exception(__FILE__, __LINE__);
261  }
262  if (!parameters) {
263  MACH3LOG_ERROR("FunctionalFlip for parameter {} is missing Parameters list", GetParFancyName(index));
264  throw MaCh3Exception(__FILE__, __LINE__);
265  }
266 
268  flip.target_index = index;
269  auto formula_name = Get<std::string>(formula, __FILE__, __LINE__);
270  flip.argument_names = Get<std::vector<std::string>>(parameters, __FILE__, __LINE__);
271 
272  for (const auto& name : flip.argument_names) {
273  const int argument_index = GetParIndex(name);
274  if (argument_index == M3::_BAD_INT_) {
275  MACH3LOG_ERROR("FunctionalFlip for parameter {} refers to unknown parameter {}",
276  GetParFancyName(index), name);
277  throw MaCh3Exception(__FILE__, __LINE__);
278  }
279  flip.argument_indices.push_back(argument_index);
280  }
281 
282  const std::string flip_name = fmt::format("{}_{}_functional_flip_{}",
283  matrixName,
284  group_name,
285  FlipGroups[group_name].FunctionalFlipParameters.size());
286  flip.evaluator = std::make_unique<TF1>(flip_name.c_str(), formula_name.c_str(), 0.0, 1.0);
287 
288  if (!flip.evaluator || flip.evaluator->IsZombie()) {
289  MACH3LOG_ERROR("Failed to parse FunctionalFlip formula for parameter {}: {}",
290  GetParFancyName(index), formula_name);
291  throw MaCh3Exception(__FILE__, __LINE__);
292  }
293 
294  if (flip.evaluator->GetNpar() != static_cast<int>(flip.argument_names.size())) {
295  MACH3LOG_ERROR("FunctionalFlip formula for parameter {} expects {} auxiliary parameters, but {} names were provided",
296  GetParFancyName(index), flip.evaluator->GetNpar(), flip.argument_names.size());
297  MACH3LOG_ERROR("Use x for the target parameter and [0], [1], ... for the listed Parameters entries");
298  throw MaCh3Exception(__FILE__, __LINE__);
299  }
300 
301  MACH3LOG_INFO("Enabling FunctionalFlip for parameter {} with formula '{}'",
302  GetParFancyName(index), formula_name);
303  FlipGroups[group_name].FunctionalFlipParameters.push_back(std::move(flip));
304 }
305 
306 // ********************************************
307 // Set the covariance matrix for this class
308 void ParameterHandlerBase::SetCovMatrix(TMatrixDSym *cov) {
309 // ********************************************
310  if (cov == nullptr) {
311  MACH3LOG_ERROR("Could not find covariance matrix you provided to {}", __func__ );
312  throw MaCh3Exception(__FILE__ , __LINE__ );
313  }
314  covMatrix = cov;
315 
316  invCovMatrix = static_cast<TMatrixDSym *>(cov->Clone());
317  invCovMatrix->Invert();
318  //KS: ROOT has bad memory management, using standard double means we can decrease most operation by factor 2 simply due to cache hits
319  for (int i = 0; i < _fNumPar; i++)
320  {
321  for (int j = 0; j < _fNumPar; ++j)
322  {
323  InvertCovMatrix[i][j] = (*invCovMatrix)(i,j);
324  }
325  }
326 
327  SetThrowMatrix(cov);
328 }
329 // ********************************************
330 void ParameterHandlerBase::ReserveMemory(const int SizeVec) {
331 // ********************************************
332  if (SizeVec <= 0) {
333  MACH3LOG_CRITICAL("Covariance matrix {} has {} entries!", GetName(), SizeVec);
334  throw MaCh3Exception(__FILE__ , __LINE__ );
335  }
336 
337  _fNames = std::vector<std::string>(SizeVec);
338  _fFancyNames = std::vector<std::string>(SizeVec);
339  _fPreFitValue = std::vector<double>(SizeVec, 1.0);
340  _fError = std::vector<double>(SizeVec, 1.0);
341  _fCurrVal = std::vector<double>(SizeVec, 0.0);
342  _fPropVal = std::vector<M3::float_t>(SizeVec, 0.0);
343  _fLowBound = std::vector<double>(SizeVec, -999.99);
344  _fUpBound = std::vector<double>(SizeVec, 999.99);
345  _fFlatPrior = std::vector<bool>(SizeVec, false);
346  _fIndivStepScale = std::vector<double>(SizeVec, 1.0);
347 
348  corr_throw = new double[SizeVec];
349  // set random parameter vector (for correlated steps)
350  randParams = new double[SizeVec];
351 
352  // Set the defaults to true
353  for(int i = 0; i < SizeVec; i++) {
354  corr_throw[i] = 0.0;
355  randParams[i] = 0.0;
356  }
357 
358  InvertCovMatrix.resize(SizeVec, std::vector<double>(SizeVec, 0.0));
359  throwMatrixCholDecomp = new double*[SizeVec]();
360  // Set the defaults to true
361  for(int i = 0; i < SizeVec; i++) {
362  throwMatrixCholDecomp[i] = new double[SizeVec]();
363  for (int j = 0; j < SizeVec; j++) {
364  throwMatrixCholDecomp[i][j] = 0.;
365  }
366  }
367 
368  _fGlobalStepScale = 1.0;
369 }
370 
371 // ********************************************
372 // Set all the covariance matrix parameters to a user-defined value
373 // Might want to split this
374 void ParameterHandlerBase::SetPar(const int i , const double val) {
375 // ********************************************
376  MACH3LOG_DEBUG("Over-riding {}: _fPropVal ({}), _fCurrVal ({}), _fPreFitValue ({}) to ({})",
377  GetParFancyName(i), _fPropVal[i], _fCurrVal[i], _fPreFitValue[i], val);
378 
379  _fPropVal[i] = static_cast<M3::float_t>(val);
380  _fCurrVal[i] = val;
381  _fPreFitValue[i] = val;
382 
383  // Transfer the parameter values to the PCA basis
384  if (pca) PCAObj->TransferToPCA();
385 }
386 
387 // *************************************
388 // Throw the parameters according to the covariance matrix
389 // This shouldn't be used in MCMC code ase it can break Detailed Balance;
391 // *************************************
392  // First draw new randParams
393  Randomize();
394 
396  #pragma GCC diagnostic push
397  #pragma GCC diagnostic ignored "-Wuseless-cast"
398  // KS: We use PCA very rarely on top PCA functionality isn't implemented for this function.
399  // Use __builtin_expect to give compiler a hint which option is more likely, which should help
400  // with better optimisation. This isn't critical but more to have example
401  if (__builtin_expect(!pca, 1)) {
402  #ifdef MULTITHREAD
403  #pragma omp parallel for
404  #endif
405  for (int i = 0; i < _fNumPar; ++i) {
406  // Check if parameter is fixed first: if so don't randomly throw
407  if (IsParameterFixed(i)) continue;
408  _fPropVal[i] = static_cast<M3::float_t>(_fPreFitValue[i] + corr_throw[i]);
409 
410  int throws = 0;
411  // Try again if we the initial parameter proposal falls outside of the range of the parameter
412  while (_fPropVal[i] > _fUpBound[i] || _fPropVal[i] < _fLowBound[i]) {
413  randParams[i] = M3::rand::Gaus(0, 1);
414  const double corr_throw_single = M3::MatrixVectorMultiSingle(throwMatrixCholDecomp, randParams, _fNumPar, i);
415  _fPropVal[i] = static_cast<M3::float_t>(_fPreFitValue[i] + corr_throw_single);
416  if (throws > 10000)
417  {
418  //KS: Since we are multithreading there is danger that those messages
419  //will be all over the place, small price to pay for faster code
420  MACH3LOG_WARN("Tried {} times to throw parameter {} but failed", throws, i);
421  MACH3LOG_WARN("Matrix: {}", matrixName);
422  MACH3LOG_WARN("Param: {}", _fNames[i]);
423  MACH3LOG_WARN("Setting _fPropVal: {} to {}", _fPropVal[i], _fPreFitValue[i]);
424  MACH3LOG_WARN("I live at {}:{}", __FILE__, __LINE__);
425  _fPropVal[i] = static_cast<M3::float_t>(_fPreFitValue[i]);
426  //throw MaCh3Exception(__FILE__ , __LINE__ );
427  }
428  throws++;
429  }
430  _fCurrVal[i] = _fPropVal[i];
431  }
432  }
433  else
434  {
435  PCAObj->ThrowParameters(throwMatrixCholDecomp,
438  } // end if pca
439  #pragma GCC diagnostic pop
440  // KS: At the end once we are happy with proposal do special proposal
442 }
443 
444 // *************************************
445 // Throw each parameter within their 1 sigma range
446 // Used to start the chain in different states
448 // *************************************
449  #pragma GCC diagnostic push
450  #pragma GCC diagnostic ignored "-Wuseless-cast"
451  // Have the 1 sigma for each parameter in each covariance class, sweet!
452  // Don't want to change the prior array because that's what determines our likelihood
453  // Want to change the _fPropVal, _fCurrVal, _fPreFitValue
454  // _fPreFitValue and the others will already be set
455  for (int i = 0; i < _fNumPar; ++i) {
456  // Check if parameter is fixed first: if so don't randomly throw
457  if (IsParameterFixed(i)) continue;
458  // Check that the sigma range is larger than the parameter range
459  // If not, throw in the valid parameter range instead
460  const double paramrange = _fUpBound[i] - _fLowBound[i];
461  const double sigma = sqrt((*covMatrix)(i,i));
462  double throwrange = sigma;
463  if (paramrange < sigma) throwrange = paramrange;
464 
465  _fPropVal[i] = static_cast<M3::float_t>(_fPreFitValue[i] + M3::rand::Gaus(0, 1)*throwrange);
466  // Try again if we the initial parameter proposal falls outside of the range of the parameter
467  int throws = 0;
468  while (_fPropVal[i] > _fUpBound[i] || _fPropVal[i] < _fLowBound[i]) {
469  if (throws > 1000) {
470  MACH3LOG_WARN("Tried {} times to throw parameter {} but failed", throws, i);
471  MACH3LOG_WARN("Matrix: {}", matrixName);
472  MACH3LOG_WARN("Param: {}", _fNames[i]);
473  throw MaCh3Exception(__FILE__ , __LINE__ );
474  }
475  _fPropVal[i] = static_cast<M3::float_t>(_fPreFitValue[i] + M3::rand::Gaus(0, 1)*throwrange);
476  throws++;
477  }
478  MACH3LOG_INFO("Setting current step in {} param {} = {} from {}", matrixName, i, _fPropVal[i], _fCurrVal[i]);
479  _fCurrVal[i] = _fPropVal[i];
480  }
481  #pragma GCC diagnostic pop
482  if (pca) PCAObj->TransferToPCA();
483 
484  // KS: At the end once we are happy with proposal do special proposal
486 }
487 
488 // *************************************
489 // Set a single parameter
490 void ParameterHandlerBase::SetSingleParameter(const int parNo, const double parVal) {
491 // *************************************
492  _fPropVal[parNo] = static_cast<M3::float_t>(parVal);
493  _fCurrVal[parNo] = parVal;
494  MACH3LOG_DEBUG("Setting {} (parameter {}) to {})", GetParFancyName(parNo), parNo, parVal);
495  if (pca) PCAObj->TransferToPCA();
496 }
497 
498 // ********************************************
499 void ParameterHandlerBase::SetParCurrProp(const int parNo, const double parVal) {
500 // ********************************************
501  _fPropVal[parNo] = static_cast<M3::float_t>(parVal);
502  _fCurrVal[parNo] = parVal;
503  MACH3LOG_DEBUG("Setting {} (parameter {}) to {})", GetParFancyName(parNo), parNo, parVal);
504  if (pca) PCAObj->TransferToPCA();
505 }
506 
507 // ************************************************
508 // Propose a step for the set of systematics parameters this covariance class holds
510 // ************************************************
511  // Make the random numbers for the step proposal
512  Randomize();
513  CorrelateSteps();
514 
515  // KS: According to Dr Wallace we update using previous not proposed step
516  // this way we do special proposal after adaptive after.
517  // This way we can shortcut and skip rest of proposal
518  if(!doSpecialStepProposal) return;
519 
521 }
522 
523 // ************************************************
525 // ************************************************
527 
528  // HW It should now automatically set dcp to be with [-pi, pi]
529  for (size_t i = 0; i < CircularBoundsIndex.size(); ++i) {
530  const int index = CircularBoundsIndex[i];
531  if(!IsParameterFixed(index))
532  CircularParBounds(index, CircularBoundsValues[i].first, CircularBoundsValues[i].second);
533  }
534 
535  // // Okay now we've done the standard steps, we can add in our nice flips hierarchy flip first
536  for (const auto& [group_name, group] : FlipGroups) {
537  FlipParameterGroup(group_name);
538  }
539 }
540 
541 // ************************************************
542 // "Randomize" the parameters in the covariance class for the proposed step
543 // Used the proposal kernel and the current parameter value to set proposed step
544 // Also get a new random number for the randParams
546 // ************************************************
547  if (!pca) {
548  //KS: By multithreading here we gain at least factor 2 with 8 threads with ND only fit
549  #ifdef MULTITHREAD
550  #pragma omp parallel for
551  #endif
552  for (int i = 0; i < _fNumPar; ++i) {
553  // If parameter isn't fixed
554  if (!IsParameterFixed(i) > 0.0) {
555  randParams[i] = M3::rand::Gaus(0, 1);
556  // If parameter IS fixed
557  } else {
558  randParams[i] = 0.0;
559  }
560  } // end for
561  // If we're in the PCA basis we instead throw parameters there (only _fNumParPCA parameter)
562  } else {
563  // Scale the random parameters by the sqrt of eigen values for the throw
564  #ifdef MULTITHREAD
565  #pragma omp parallel for
566  #endif
567  for (int i = 0; i < PCAObj->GetNumberPCAedParameters(); ++i)
568  {
569  // If parameter IS fixed or out of bounds
570  if (PCAObj->IsParameterFixedPCA(i)) {
571  randParams[i] = 0.0;
572  } else {
573  randParams[i] = M3::rand::Gaus(0, 1);
574  }
575  }
576  }
577 }
578 
579 // ************************************************
580 // Correlate the steps by setting the proposed step of a parameter to its current value + some correlated throw
582 // ************************************************
583  //KS: Using custom function compared to ROOT one with 8 threads we have almost factor 2 performance increase, by replacing TMatrix with just double we increase it even more
585 
586  // If not doing PCA
587  if (!pca) {
588  #ifdef MULTITHREAD
589  #pragma omp parallel for
590  #endif
591  for (int i = 0; i < _fNumPar; ++i) {
592  if (!IsParameterFixed(i) > 0.) {
593  #pragma GCC diagnostic push
594  #pragma GCC diagnostic ignored "-Wuseless-cast"
596  #pragma GCC diagnostic pop
597  }
598  }
599  // If doing PCA throw uncorrelated in PCA basis (orthogonal basis by definition)
600  } else {
602  }
603 }
604 // ********************************************
605 // Update so that current step becomes the previously proposed step
607 // ********************************************
608  if (!pca) {
609  #ifdef MULTITHREAD
610  #pragma omp parallel for
611  #endif
612  for (int i = 0; i < _fNumPar; ++i) {
613  // Update state so that current state is proposed state
614  _fCurrVal[i] = _fPropVal[i];
615  }
616  } else {
617  PCAObj->AcceptStep();
618  }
619 
620  if (AdaptiveHandler) {
621  AdaptiveHandler->IncrementAcceptedSteps();
622  }
623 }
624 
625 #pragma GCC diagnostic push
626 #pragma GCC diagnostic ignored "-Wuseless-cast"
627 // *************************************
628 //HW: This method is a tad hacky but modular arithmetic gives me a headache.
629 void ParameterHandlerBase::CircularParBounds(const int index, const double LowBound, const double UpBound) {
630 // *************************************
631  if(_fPropVal[index] > UpBound) {
632  _fPropVal[index] = static_cast<M3::float_t>(LowBound + std::fmod(_fPropVal[index] - UpBound, UpBound - LowBound));
633  } else if (_fPropVal[index] < LowBound) {
634  _fPropVal[index] = static_cast<M3::float_t>(UpBound - std::fmod(LowBound - _fPropVal[index], UpBound - LowBound));
635  }
636 }
637 
638 // *************************************
639 void ParameterHandlerBase::FlipParameterGroup(const std::string& group) {
640 // *************************************
641  const FlipGroup& flip_group = FlipGroups.at(group);
642  // All standard and functional flip groups use the same 50% gate
643  // The exact value doesn't matter: studies with different probabilities showed
644  // it doesn't help exploration even for very unlikely hypotheses, because once
645  // the chain flips to a state, it stays there for a very long time regardless.
646  if (M3::rand::Uniform() >= 0.5) {
647  return;
648  }
649 
650  // store the proposed values before doing any flipping, so that the functional flip can see the unflipped values for any standard flips
651  std::vector<double> proposed_values(_fNumPar, 0.0);
652  for (int i = 0; i < _fNumPar; ++i) {
653  proposed_values[i] = _fPropVal[i];
654  }
655 
656  // perform standard flips first
657  for (size_t i = 0; i < flip_group.FlipParameterIndex.size(); ++i) {
658  const int index = flip_group.FlipParameterIndex[i];
659  if (!IsParameterFixed(index)) {
660  const double flip_point = flip_group.FlipParameterPoint[i];
661  _fPropVal[index] = static_cast<M3::float_t>(2 * flip_point - proposed_values[index]);
662  }
663  }
664 
665  // perform functional flips next
666  for (const auto& functional_flip : flip_group.FunctionalFlipParameters) {
667  if (IsParameterFixed(functional_flip.target_index)) {
668  continue;
669  }
670 
671  _fPropVal[functional_flip.target_index] = EvaluateFunctionalFlip(functional_flip, proposed_values);
672  }
673 }
674 
675 
676 // *************************************
678  const std::vector<double>& proposed_values) const {
679 // *************************************
680  std::vector<double> parameter_values(flip.argument_indices.size(), 0.0);
681  for (size_t i = 0; i < flip.argument_indices.size(); ++i) {
682  parameter_values[i] = proposed_values[flip.argument_indices[i]];
683  }
684 
685  const double target_value = proposed_values[flip.target_index];
686  const double flipped_value = flip.evaluator->EvalPar(&target_value, parameter_values.data());
687  return static_cast<M3::float_t>(flipped_value);
688 }
689 #pragma GCC diagnostic pop
690 // ********************************************
691 // Function to print the prior values
693 // ********************************************
694  MACH3LOG_INFO("Prior values for {} ParameterHandler:", GetName());
695 
696  M3::Utils::TablePrinter table({{"Parameter", 10, 40, M3::Utils::Alignment::Left},
697  {"Prior", 10, 15, M3::Utils::Alignment::Right},});
698 
699  for (int i = 0; i < _fNumPar; ++i) {
700  table.AddRow(GetParFancyName(i), GetParPreFit(i));
701  }
702 
703  for (const auto& line : table.Render()) {
704  MACH3LOG_INFO("{}", line);
705  }
706 }
707 
708 // ********************************************
709 // Function to print the prior, current and proposed values
711 // ********************************************
712  MACH3LOG_INFO("Printing parameters for {}", GetName());
713  // Dump out the PCA parameters too
714  if (pca) {
715  PCAObj->Print();
716  }
717  M3::Utils::TablePrinter table({{"Name", 10, 40, M3::Utils::Alignment::Left},
718  {"Prior", 10, 15, M3::Utils::Alignment::Right},
719  {"Current", 10, 15, M3::Utils::Alignment::Right},
720  {"Proposed", 10, 15, M3::Utils::Alignment::Right},});
721 
722  for (int i = 0; i < _fNumPar; ++i) {
723  table.AddRow(GetParFancyName(i),
724  M3::Utils::Cell(_fPreFitValue[i], "{:.2f}"),
725  M3::Utils::Cell(_fCurrVal[i], "{:.2f}"),
726  M3::Utils::Cell(_fPropVal[i], "{:.2f}"));
727  }
728 
729  for (const auto& line : table.Render()) {
730  MACH3LOG_INFO("{}", line);
731  }
732 }
733 
734 // ********************************************
735 // Get the likelihood in the case where we want to include priors on the parameters
736 // _fFlatPrior stores if we want to evaluate the likelihood for the given parameter
737 // true = don't evaluate likelihood (so run without a prior)
738 // false = evaluate likelihood (so run with a prior)
740 // ********************************************
741  double logL = 0.0;
742  #ifdef MULTITHREAD
743  #pragma omp parallel for reduction(+:logL)
744  #endif
745  for(int i = 0; i < _fNumPar; ++i) {
746  if(_fFlatPrior[i]){
747  //HW: Flat prior, no need to calculate anything
748  continue;
749  }
750  // KS: Precalculate Diff once per "i" without doing this for every "j"
751  const double Diff = _fPropVal[i] - _fPreFitValue[i];
752  #ifdef MULTITHREAD
753  #pragma omp simd
754  #endif
755  for (int j = 0; j <= i; ++j) {
756  if (!_fFlatPrior[j]) {
757  //KS: Since matrix is symmetric we can calculate non diagonal elements only once and multiply by 2, can bring up to factor speed decrease.
758  double scale = (i != j) ? 1. : 0.5;
759  logL += scale * Diff * (_fPropVal[j] - _fPreFitValue[j])*InvertCovMatrix[i][j];
760  }
761  }
762  }
763  return logL;
764 }
765 
766 // ********************************************
768 // ********************************************
769  int NOutside = 0;
770  for (int i = 0; i < _fNumPar; ++i) {
771  // KS: Count how many parameters are outside bounds using branchless logic
772  // faster by at least factor two
773  // Do not multithread even with 5k params no gains
774  NOutside += (_fPropVal[i] > _fUpBound[i]) | (_fPropVal[i] < _fLowBound[i]);
775  }
776  return NOutside;
777 }
778 
779 // ********************************************
781 // ********************************************
782  // Default behaviour is to reject negative values + do std llh calculation
783  const int NOutside = CheckBounds();
784 
785  if(NOutside > 0) return NOutside*M3::_LARGE_LOGL_;
786 
787  return CalcLikelihood();
788 }
789 
790 // ********************************************
791 // Sets the proposed parameters to the prior values
792 void ParameterHandlerBase::SetParameters(const std::vector<double>& pars) {
793 // ********************************************
794  #pragma GCC diagnostic push
795  #pragma GCC diagnostic ignored "-Wuseless-cast"
796  // If empty, set the proposed to prior
797  if (pars.empty()) {
798  for (int i = 0; i < _fNumPar; i++) {
799  _fPropVal[i] = static_cast<M3::float_t>(_fPreFitValue[i]);
800  }
801  // If not empty, set the parameters to the specified
802  } else {
803  if (pars.size() != static_cast<size_t>(_fNumPar)) {
804  MACH3LOG_ERROR("Parameter arrays of incompatible size! Not changing parameters! {} has size {} but was expecting {}", matrixName, pars.size(), _fNumPar);
805  throw MaCh3Exception(__FILE__ , __LINE__ );
806  }
807  int parsSize = int(pars.size());
808  for (int i = 0; i < parsSize; i++) {
809  //Make sure that you are actually passing a number to set the parameter to
810  if(std::isnan(pars[i])) {
811  MACH3LOG_ERROR("Trying to set parameter value to a nan for parameter {} in matrix {}. This will not go well!", GetParName(i), matrixName);
812  throw MaCh3Exception(__FILE__ , __LINE__ );
813  } else {
814  _fPropVal[i] = static_cast<M3::float_t>(pars[i]);
815  }
816  }
817  }
818  // And if pca make the transfer
819  if (pca) {
820  PCAObj->TransferToPCA();
821  PCAObj->TransferToParam();
822  }
823  #pragma GCC diagnostic pop
824 }
825 
826 // ********************************************
827 void ParameterHandlerBase::SetBranches(TTree &tree, bool SaveProposal) {
828 // ********************************************
829  // loop over parameters and set a branch
830  for (int i = 0; i < _fNumPar; ++i) {
831  tree.Branch(_fNames[i].c_str(), &_fCurrVal[i], Form("%s/D", _fNames[i].c_str()));
832  }
833  // When running PCA, also save PCA parameters
834  if (pca) {
835  PCAObj->SetBranches(tree, SaveProposal, _fNames);
836  }
837  if(SaveProposal)
838  {
839  // loop over parameters and set a branch
840  for (int i = 0; i < _fNumPar; ++i) {
841  tree.Branch(Form("%s_Prop", _fNames[i].c_str()), &_fPropVal[i], Form("%s_Prop/D", _fNames[i].c_str()));
842  }
843  }
844  if(use_adaptive && AdaptiveHandler->GetUseRobbinsMonro()){
845  tree.Branch(Form("GlobalStepScale_%s", GetName().c_str()), &_fGlobalStepScale, Form("GlobalStepScale_%s/D", GetName().c_str()));
846  }
847 }
848 
849 // ********************************************
850 void ParameterHandlerBase::SetStepScale(const double scale, const bool verbose) {
851 // ********************************************
852  if(scale <= 0) {
853  MACH3LOG_ERROR("You are trying so set StepScale to 0 or negative this will not work");
854  throw MaCh3Exception(__FILE__ , __LINE__ );
855  }
856 
857  if(verbose){
858  MACH3LOG_INFO("{} setStepScale() = {}", GetName(), scale);
859  const double SuggestedScale = 2.38/std::sqrt(_fNumPar);
860  if(std::fabs(scale - SuggestedScale)/SuggestedScale > 1) {
861  MACH3LOG_WARN("Defined Global StepScale is {}, while suggested suggested {}", scale, SuggestedScale);
862  }
863  }
864  _fGlobalStepScale = scale;
865 }
866 
867 // ********************************************
868 int ParameterHandlerBase::GetParIndex(const std::string& name) const {
869 // ********************************************
870  int Index = M3::_BAD_INT_;
871  for (int i = 0; i <_fNumPar; ++i) {
872  if(name == _fFancyNames[i]) {
873  Index = i;
874  break;
875  }
876  }
877  return Index;
878 }
879 
880 // ********************************************
882 // ********************************************
883  // Check if the parameter is fixed and if not, toggle fix it
884  for (int i = 0; i < _fNumPar; ++i)
886 }
887 
888 // ********************************************
890 // ********************************************
891  // Check if the parameter is fixed and if not, toggle fix it
893 }
894 
895 // ********************************************
896 void ParameterHandlerBase::SetFixParameter(const std::string& name) {
897 // ********************************************
898  // Check if the parameter is fixed and if not, toggle fix it
899  if(!IsParameterFixed(name)) ToggleFixParameter(name);
900 }
901 
902 // ********************************************
904 // ********************************************
905  // Check if the parameter is fixed and if not, toggle fix it
906  for (int i = 0; i < _fNumPar; ++i)
908 }
909 
910 // ********************************************
912 // ********************************************
913  // Check if the parameter is fixed and if not, toggle fix it
915 }
916 
917 // ********************************************
918 void ParameterHandlerBase::SetFreeParameter(const std::string& name) {
919 // ********************************************
920  // Check if the parameter is fixed and if not, toggle fix it
921  if(IsParameterFixed(name)) ToggleFixParameter(name);
922 }
923 
924 // ********************************************
926 // ********************************************
927  if(!pca) {
928  if (i > _fNumPar) {
929  MACH3LOG_ERROR("Can't {} for parameter {} because size of covariance ={}", __func__, i, _fNumPar);
930  MACH3LOG_ERROR("Fix this in your config file please!");
931  throw MaCh3Exception(__FILE__ , __LINE__ );
932  } else {
933  _fError[i] *= -1.0;
934  if(IsParameterFixed(i)) MACH3LOG_INFO("Setting {}(parameter {}) to fixed at {}", GetParFancyName(i), i, _fCurrVal[i]);
935  else MACH3LOG_INFO("Setting {}(parameter {}) free", GetParFancyName(i), i);
936  }
937  if( (_fCurrVal[i] > _fUpBound[i] || _fCurrVal[i] < _fLowBound[i]) && IsParameterFixed(i) ) {
938  MACH3LOG_ERROR("Parameter {} (index {}) is fixed at {}, which is outside of its bounds [{}, {}]", GetParFancyName(i), i, _fCurrVal[i], _fLowBound[i], _fUpBound[i]);
939  throw MaCh3Exception(__FILE__ , __LINE__ );
940  }
941  } else {
942  PCAObj->ToggleFixParameter(i, _fNames);
943  }
944 }
945 
946 // ********************************************
947 void ParameterHandlerBase::ToggleFixParameter(const std::string& name) {
948 // ********************************************
949  const int Index = GetParIndex(name);
950  if(Index != M3::_BAD_INT_) {
951  ToggleFixParameter(Index);
952  return;
953  }
954  MACH3LOG_WARN("I couldn't find parameter with name {}, therefore will not fix it", name);
955 }
956 
957 // ********************************************
958 bool ParameterHandlerBase::IsParameterFixed(const std::string& name) const {
959 // ********************************************
960  const int Index = GetParIndex(name);
961  if(Index != M3::_BAD_INT_) {
962  return IsParameterFixed(Index);
963  }
964 
965  MACH3LOG_WARN("I couldn't find parameter with name {}, therefore don't know if it fixed", name);
966  return false;
967 }
968 
969 // ********************************************
970 void ParameterHandlerBase::SetFlatPrior(const int i, const bool eL) {
971 // ********************************************
972  if (i > _fNumPar) {
973  MACH3LOG_INFO("Can't {} for Cov={}/Param={} because size of Covariance = {}", __func__, GetName(), i, _fNumPar);
974  MACH3LOG_ERROR("Fix this in your config file please!");
975  throw MaCh3Exception(__FILE__ , __LINE__ );
976  } else {
977  if(eL){
978  MACH3LOG_INFO("Setting {} (parameter {}) to flat prior", GetParName(i), i);
979  }
980  else{
981  // HW :: This is useful
982  MACH3LOG_INFO("Setting {} (parameter {}) to non-flat prior", GetParName(i), i);
983  }
984  _fFlatPrior[i] = eL;
985  }
986 }
987 
988 // ********************************************
989 void ParameterHandlerBase::SetIndivStepScale(const std::vector<double>& stepscale) {
990 // ********************************************
991  if (static_cast<int>(stepscale.size()) != _fNumPar)
992  {
993  MACH3LOG_WARN("Stepscale vector not equal to number of parameters. Quitting..");
994  MACH3LOG_WARN("Size of argument vector: {}", stepscale.size());
995  MACH3LOG_WARN("Expected size: {}", _fNumPar);
996  return;
997  }
998 
999  for (int iParam = 0 ; iParam < _fNumPar; iParam++) {
1000  _fIndivStepScale[iParam] = stepscale[iParam];
1001  }
1003 }
1004 
1005 // ********************************************
1007 // ********************************************
1008  M3::Utils::TablePrinter table({{"Parameter", 10, 40, M3::Utils::Alignment::Left},
1009  {"Step scale", 10, 15, M3::Utils::Alignment::Right},});
1010 
1011  for (int iParam = 0; iParam < _fNumPar; ++iParam) {
1012  table.AddRow(_fFancyNames[iParam], _fIndivStepScale[iParam]);
1013  }
1014 
1015  for (const auto& line : table.Render()) {
1016  MACH3LOG_INFO("{}", line);
1017  }
1018 }
1019 
1020 // ********************************************
1021 //Makes sure that matrix is positive-definite by adding a small number to on-diagonal elements
1022 void ParameterHandlerBase::MakePosDef(TMatrixDSym *cov, bool verbose) {
1023 // ********************************************
1024  if(cov == nullptr){
1025  cov = &*covMatrix;
1026  MACH3LOG_WARN("Passed nullptr to cov matrix in {}", matrixName);
1027  }
1028 
1029  int n_attempts = M3::MakeMatrixPosDef(cov);
1030 
1031  if(n_attempts > 0 && verbose) {
1032  MACH3LOG_WARN("Covariance matrix {} was not positive-definite, made it positive-definite after {} attempts", matrixName, n_attempts);
1033  }
1034 }
1035 
1036 // ********************************************
1038 // ********************************************
1039  std::vector<double> stepScales(_fNumPar, 1.0);
1040  _fGlobalStepScale = 1.0;
1041  SetIndivStepScale(stepScales);
1042 }
1043 
1044 // ********************************************
1046 // ********************************************
1047  if (!param_skip_adapt_flags.size()) {
1048  MACH3LOG_ERROR("Parameter skip adapt flags not set, cannot set individual step scales for skipped parameters.");
1049  throw MaCh3Exception(__FILE__ , __LINE__ );
1050  }
1051  // HH: Cancel the effect of global step scale change for parameters that are not adapting
1052  for (int i = 0; i <_fNumPar; i++) {
1053  if (param_skip_adapt_flags[i]) {
1055  }
1056  }
1057  MACH3LOG_DEBUG("Updating individual step scales for non-adapting parameters to cancel global step scale change.");
1058  MACH3LOG_DEBUG("Global step scale initial: {}, current: {}", _fGlobalStepScaleInitial, _fGlobalStepScale);
1059 }
1060 
1061 // ********************************************
1062 // HW: Code for throwing from separate throw matrix, needs to be set after init to ensure pos-def
1063 void ParameterHandlerBase::SetThrowMatrix(const TMatrixDSym *cov) {
1064 // ********************************************
1065  if (cov == nullptr) {
1066  MACH3LOG_ERROR("Could not find covariance matrix you provided to {}", __func__);
1067  throw MaCh3Exception(__FILE__ , __LINE__ );
1068  }
1069 
1070  if (covMatrix->GetNrows() != cov->GetNrows()) {
1071  MACH3LOG_ERROR("Matrix given for throw Matrix is not the same size as the covariance matrix stored in object!");
1072  MACH3LOG_ERROR("Stored covariance matrix size: {}", covMatrix->GetNrows());
1073  MACH3LOG_ERROR("Given matrix size: {}", cov->GetNrows());
1074  throw MaCh3Exception(__FILE__ , __LINE__ );
1075  }
1076 
1077  throwMatrix = static_cast<TMatrixDSym*>(cov->Clone());
1078  if(use_adaptive && AdaptiveHandler->AdaptionUpdate()) {
1080  } else {
1081  // HW: Prevent spam from adaptive handler
1082  bool verbose = AdaptiveHandler ? AdaptiveHandler->GetTotalSteps() < 2 : true;
1083  MakePosDef(throwMatrix, verbose);
1084  }
1085 
1086  // Simple sanitizer
1087  for (int i = 0; i < _fNumPar; ++i) {
1088  const double variance = (*throwMatrix)(i, i);
1089  if(!std::isfinite(variance) || variance <= 0.) {
1090  MACH3LOG_WARN("Invalid variance for param {} ({}): {}, after posdef this will cause proposal to fail",
1091  i, _fFancyNames[i], variance);
1092  }
1093  }
1094 
1095  auto throwMatrix_CholDecomp = M3::GetCholeskyDecomposedMatrix(*throwMatrix, matrixName);
1096 
1097  //KS: ROOT has bad memory management, using standard double means we can decrease most operation by factor 2 simply due to cache hits
1098  #ifdef MULTITHREAD
1099  #pragma omp parallel for collapse(2)
1100  #endif
1101  for (int i = 0; i < _fNumPar; ++i)
1102  {
1103  for (int j = 0; j < _fNumPar; ++j)
1104  {
1105  throwMatrixCholDecomp[i][j] = throwMatrix_CholDecomp[i][j];
1106  }
1107  }
1108 }
1109 
1110 // ********************************************
1111 void ParameterHandlerBase::SetSubThrowMatrix(int first_index, int last_index,
1112  TMatrixDSym const &subcov) {
1113 // ********************************************
1114  if ((last_index - first_index) >= subcov.GetNrows()) {
1115  MACH3LOG_ERROR("Trying to SetSubThrowMatrix into range: ({},{}) with a "
1116  "submatrix with only {} rows {}",
1117  first_index, last_index, subcov.GetNrows(), __func__);
1118  throw MaCh3Exception(__FILE__, __LINE__);
1119  }
1120 
1121  TMatrixDSym *current_ThrowMatrix =
1122  static_cast<TMatrixDSym *>(throwMatrix->Clone());
1123  for (int i = first_index; i <= last_index; ++i) {
1124  for (int j = first_index; j <= last_index; ++j) {
1125  current_ThrowMatrix->operator()(i, j) =
1126  subcov(i - first_index, j - first_index);
1127  }
1128  }
1129 
1130  SetThrowMatrix(current_ThrowMatrix);
1131  delete current_ThrowMatrix;
1132 }
1133 
1134 // ********************************************
1136 // ********************************************
1137  delete throwMatrix;
1138  throwMatrix = nullptr;
1139  SetThrowMatrix(cov);
1140 }
1141 
1142 // ********************************************
1144 // ********************************************
1145  for (const auto& [_, group] : FlipGroups) {
1146  for (size_t i = 0; i < group.FlipParameterIndex.size(); ++i) {
1147  const int index = group.FlipParameterIndex[i];
1148  if(!param_skip_adapt_flags[index]) {
1149  MACH3LOG_ERROR("You enabled adaption for parameter which has enabled flipping ({})", _fFancyNames[index]);
1150  MACH3LOG_ERROR("Right now flipping and adapting doesn't work very well");
1151  MACH3LOG_ERROR("Please skip adaption for param {}, using ParametersToSkip option in config", _fFancyNames[index]);
1152  throw MaCh3Exception(__FILE__, __LINE__);
1153  }
1154  }
1155  }
1156 
1157  // HH: Loop over correlations to check if any skipped parameter is correlated with adapted one
1158  // We don't want to change one parameter while keeping the other fixed as this would
1159  // lead to weird penalty terms in the prior after adapting
1160  constexpr double max_correlation = 0.01; // Define a threshold for significant correlation above which we throw an error
1161  for (int i = 0; i < _fNumPar; ++i) {
1162  for (int j = 0; j <= i; ++j) {
1163  // The symmetry should have been checked during the Init phase
1165  double corr = (*covMatrix)(i,j)/std::sqrt((*covMatrix)(i,i)*(*covMatrix)(j,j));
1166  if(std::fabs(corr) > max_correlation) {
1167  MACH3LOG_ERROR("Correlation between skipped parameter {} ({}) and non-skipped parameter {} ({}) is {:.6e}, above the allowed threshold of {:.6e}.",
1168  i, _fFancyNames[i], j, _fFancyNames[j], corr, max_correlation);
1169  throw MaCh3Exception(__FILE__, __LINE__);
1170  }
1171  }
1172  }
1173  }
1174 }
1175 
1176 // ********************************************
1177 // HW : Here be adaption
1178 void ParameterHandlerBase::InitialiseAdaption(const YAML::Node& adapt_manager) {
1179 // ********************************************
1180  if(PCAObj){
1181  MACH3LOG_ERROR("PCA has been enabled and now trying to enable Adaption. Right now both configuration don't work with each other");
1182  throw MaCh3Exception(__FILE__ , __LINE__ );
1183  }
1184  if(AdaptiveHandler){
1185  MACH3LOG_ERROR("Adaptive Handler has already been initialise can't do it again so skipping.");
1186  return;
1187  }
1188  AdaptiveHandler = std::make_unique<AdaptiveMCMCHandler>();
1189 
1190  // HH: Backing up _fIndivStepScale and _fGlobalStepScale before adaption
1193 
1194  // HH: adding these here because they will be used to set the individual step scales for non-adapting parameters
1195  auto params_to_skip = GetFromManager<std::vector<std::string>>(adapt_manager["AdaptionOptions"]["Covariance"][matrixName]["ParametersToSkip"], {}, __FILE__ , __LINE__);
1196  // Build a list of skip flags
1197  param_skip_adapt_flags.resize(_fNumPar, false);
1198  for (int i = 0; i <_fNumPar; ++i) {
1200  }
1201 
1202  // Now we read the general settings [these SHOULD be common across all matrices!]
1203  bool success = AdaptiveHandler->InitFromConfig(adapt_manager, matrixName,
1206  );
1207  if (success) {
1208  // Ensure there is no misconfiguration in adaption config
1209  SanitizeAdaption();
1210  AdaptiveHandler->Print();
1211  } else {
1212  MACH3LOG_INFO("Not using adaptive MCMC for {}. Checking external matrix options...", matrixName);
1213  }
1214 
1215  // HH: Adjusting the external matrix reading logic such that you can not do adaptive
1216  // and still read an external matrix
1217  // Logic:
1218  // if read external matrix:
1219  // set throw matrix regardless of adaptive or not
1220  // else:
1221  // if adaptive:
1222  // create new adaptive matrix from scratch
1223  // else:
1224  // do nothing
1225  if(GetFromManager<bool>(adapt_manager["AdaptionOptions"]["Covariance"][matrixName]["UseExternalMatrix"], false, __FILE__ , __LINE__)) {
1226  // Finally, we accept that we want to read the matrix from a file!
1227  auto external_file_name = GetFromManager<std::string>(adapt_manager["AdaptionOptions"]["Covariance"][matrixName]["ExternalMatrixFileName"], "", __FILE__ , __LINE__);
1228  auto external_matrix_name = GetFromManager<std::string>(adapt_manager["AdaptionOptions"]["Covariance"][matrixName]["ExternalMatrixName"], "", __FILE__ , __LINE__);
1229  auto external_mean_name = GetFromManager<std::string>(adapt_manager["AdaptionOptions"]["Covariance"][matrixName]["ExternalMeansName"], "", __FILE__ , __LINE__);
1230 
1231  AdaptiveHandler->SetThrowMatrixFromFile(external_file_name, external_matrix_name, external_mean_name, use_adaptive);
1232  SetThrowMatrix(AdaptiveHandler->GetAdaptiveCovariance());
1233 
1235  // HH: Set individual step scales for non-adapting parameters to the default individual step scales
1236  // global step scale should be 1 so no need to adjust for that
1238 
1239  MACH3LOG_INFO("Successfully Set External Throw Matrix Stored in {}", external_file_name);
1240  } else {
1241  MACH3LOG_INFO("Not using external matrix for {}", matrixName);
1242  if (!success) return; // Not adaptive either so nothing to do
1243  MACH3LOG_INFO("Initialising adaption from scratch");
1244  // If we don't have a covariance matrix to start from for adaptive tune we need to make one!
1245  use_adaptive = true;
1246  AdaptiveHandler->CheckMatrixValidityForAdaption(GetCovMatrix());
1247  AdaptiveHandler->CreateNewAdaptiveCovariance();
1248  return;
1249  }
1250 }
1251 
1252 // ********************************************
1253 // Truely adaptive MCMC!
1255 // ********************************************
1256  // Updates adaptive matrix
1257  // First we update the total means
1258 
1259  // Skip this if we're at a large number of steps
1260  if(AdaptiveHandler->SkipAdaption()) {
1261  AdaptiveHandler->IncrementNSteps();
1262  return;
1263  }
1264 
1266  if(AdaptiveHandler->GetStartRobbinsMonro()){
1267  bool verbose=false;
1268  #ifdef MACH3_DEBUG
1269  verbose=true;
1270  #endif
1271  AdaptiveHandler->UpdateRobbinsMonroScale();
1272  SetStepScale(AdaptiveHandler->GetAdaptionScale(), verbose);
1274  }
1275 
1276  // Call main adaption function
1277  AdaptiveHandler->UpdateAdaptiveCovariance();
1278 
1279  // Set scales to 1 * optimal scale
1280  if(AdaptiveHandler->IndivStepScaleAdapt()) {
1282  SetStepScale(AdaptiveHandler->GetAdaptionScale());
1284  }
1285 
1286  if(AdaptiveHandler->ShouldUpdateMatrixAdapt()) {
1287  TMatrixDSym* update_matrix = static_cast<TMatrixDSym*>(AdaptiveHandler->GetAdaptiveCovariance()->Clone());
1288  UpdateThrowMatrix(update_matrix); //Now we update and continue!
1289  //Also Save the adaptive to file
1290  AdaptiveHandler->SaveAdaptiveToFile(AdaptiveHandler->GetOutFileName(), GetName());
1291  }
1292 
1293  AdaptiveHandler->IncrementNSteps();
1294 }
1295 
1296 // ********************************************
1297 //HW: Finds closest possible positive definite matrix in Frobenius Norm ||.||_frob
1298 // Where ||X||_frob=sqrt[sum_ij(x_ij^2)] (basically just turns an n,n matrix into vector in n^2 space
1299 // then does Euclidean norm)
1301 // ********************************************
1302  // Want to get cov' = (cov_sym+cov_polar)/2
1303  // cov_sym=(cov+cov^T)/2
1304  // cov_polar-> SVD cov to cov=USV^T then cov_polar=VSV^T
1305 
1306  //Get frob norm of cov
1307  // Double_t cov_norm=cov->E2Norm();
1308 
1309  TMatrixDSym* cov_trans = cov;
1310  cov_trans->T();
1311  TMatrixDSym cov_sym = 0.5*(*cov+*cov_trans); //If cov is symmetric does nothing, otherwise just ensures symmetry
1312 
1313  //Do SVD to get polar form
1314  TDecompSVD cov_sym_svd=TDecompSVD(cov_sym);
1315  if(!cov_sym_svd.Decompose()){
1316  MACH3LOG_WARN("Cannot do SVD on input matrix, trying MakePosDef() first!");
1317  MakePosDef(&cov_sym);
1318  }
1319 
1320  TMatrixD cov_sym_v = cov_sym_svd.GetV();
1321  TMatrixD cov_sym_vt = cov_sym_v;
1322  cov_sym_vt.T();
1323  //SVD returns as vector (grrr) so need to get into matrix form for multiplying!
1324  TVectorD cov_sym_sigvect = cov_sym_svd.GetSig();
1325 
1326  const Int_t nCols = cov_sym_v.GetNcols(); //square so only need rows hence lack of cols
1327  TMatrixDSym cov_sym_sig(nCols);
1328  TMatrixDDiag cov_sym_sig_diag(cov_sym_sig);
1329  cov_sym_sig_diag=cov_sym_sigvect;
1330 
1331  //Can finally get H=VSV
1332  TMatrixDSym cov_sym_polar = cov_sym_sig.SimilarityT(cov_sym_vt);//V*S*V^T (this took forver to find!)
1333 
1334  //Now we can construct closest approximater Ahat=0.5*(B+H)
1335  TMatrixDSym cov_closest_approx = 0.5*(cov_sym+cov_sym_polar);//Not fully sure why this is even needed since symmetric B -> U=V
1336  //Get norm of transformed
1337  // Double_t approx_norm=cov_closest_approx.E2Norm();
1338  //MACH3LOG_INFO("Initial Norm: {:.6f} | Norm after transformation: {:.6f} | Ratio: {:.6f}", cov_norm, approx_norm, cov_norm / approx_norm);
1339 
1340  *cov = cov_closest_approx;
1341  //Now can just add a makeposdef!
1342  MakePosDef(cov);
1343 }
1344 
1345 // ********************************************
1346 // KS: Convert covariance matrix to correlation matrix and return TH2D which can be used for fancy plotting
1348 // ********************************************
1349  TH2D* hMatrix = new TH2D(GetName().c_str(), GetName().c_str(), _fNumPar, 0.0, _fNumPar, _fNumPar, 0.0, _fNumPar);
1350  hMatrix->SetDirectory(nullptr);
1351  for(int i = 0; i < _fNumPar; i++)
1352  {
1353  hMatrix->SetBinContent(i+1, i+1, 1.);
1354  hMatrix->GetXaxis()->SetBinLabel(i+1, GetParFancyName(i).c_str());
1355  hMatrix->GetYaxis()->SetBinLabel(i+1, GetParFancyName(i).c_str());
1356  }
1357 
1358  #ifdef MULTITHREAD
1359  #pragma omp parallel for
1360  #endif
1361  for(int i = 0; i < _fNumPar; i++)
1362  {
1363  for(int j = 0; j <= i; j++)
1364  {
1365  const double Corr = (*covMatrix)(i,j) / ( GetDiagonalError(i) * GetDiagonalError(j));
1366  hMatrix->SetBinContent(i+1, j+1, Corr);
1367  hMatrix->SetBinContent(j+1, i+1, Corr);
1368  }
1369  }
1370  return hMatrix;
1371 }
1372 
1373 // ********************************************
1374 // KS: After step scale, prefit etc. value were modified save this modified config.
1376 // ********************************************
1377  if (!_fYAMLDoc)
1378  {
1379  MACH3LOG_CRITICAL("Yaml node hasn't been initialised for matrix {}, something is not right", matrixName);
1380  MACH3LOG_CRITICAL("I am not throwing error but should be investigated");
1381  return;
1382  }
1383 
1384  YAML::Node copyNode = _fYAMLDoc;
1385  int i = 0;
1386 
1387  for (YAML::Node param : copyNode["Systematics"])
1388  {
1389  //KS: Feel free to update it, if you need updated prefit value etc
1390  param["Systematic"]["StepScale"] = M3::Utils::FormatDouble(_fIndivStepScale[i], 4);
1391  i++;
1392  }
1393  // Save the modified node to a file
1394  std::ofstream fout("Modified_Matrix.yaml");
1395  fout << copyNode;
1396  fout.close();
1397 }
1398 
1399 // ********************************************
1400 // Set proposed parameter values vector to be base on tune values
1401 void ParameterHandlerBase::SetTune(const std::string& TuneName) {
1402 // ********************************************
1403  if(Tunes == nullptr) {
1404  MACH3LOG_ERROR("Tunes haven't been initialised, which are being loaded from YAML, have you used some deprecated constructor");
1405  throw MaCh3Exception(__FILE__, __LINE__);
1406  }
1407  auto Values = Tunes->GetTune(TuneName);
1408 
1409  SetParameters(Values);
1410 }
1411 
1412 // *************************************
1414  std::vector<double>& BranchValues,
1415  std::vector<std::string>& BranchNames,
1416  const std::vector<std::string>& FancyNames) {
1417 // *************************************
1418  BranchValues.resize(GetNumParams());
1419  BranchNames.resize(GetNumParams());
1420 
1421  // if fancy names are passed match ONLY them
1422  // this allow to perform studies where one perform ND fits and pass it to FD fits
1423  // which usually have more params like osc...
1424  if(FancyNames.size() != 0){
1425  for (int i = 0; i < GetNumParams(); ++i) {
1426  BranchNames[i] = GetParName(i);
1427  // by default set current step
1428  BranchValues[i] = _fPropVal[i];
1429  bool matched = false;
1430  for (size_t iPar = 0; iPar < FancyNames.size(); ++iPar) {
1431  if(GetParFancyName(i) == FancyNames[iPar]) {
1432  MACH3LOG_DEBUG("Matched name {} in config", FancyNames[iPar]);
1433  PosteriorFile->SetBranchStatus(BranchNames[iPar].c_str(), true);
1434  PosteriorFile->SetBranchAddress(BranchNames[iPar].c_str(), &BranchValues[i]);
1435  matched = true;
1436  break;
1437  }
1438  }
1439  if(!matched) {
1440  MACH3LOG_WARN("Didn't match param {}, is this what you want?", GetParFancyName(i));
1441  }
1442  }
1443  } else {
1444  // simply loop over params and match them
1445  for (int i = 0; i < GetNumParams(); ++i) {
1446  BranchNames[i] = GetParName(i);
1447  if (!PosteriorFile->GetBranch(BranchNames[i].c_str())) {
1448  MACH3LOG_WARN("Branch '{}' does not exist in the TTree, is this what you want?", BranchNames[i]);
1449  continue;
1450  }
1451  PosteriorFile->SetBranchStatus(BranchNames[i].c_str(), true);
1452  PosteriorFile->SetBranchAddress(BranchNames[i].c_str(), &BranchValues[i]);
1453  }
1454  }
1455 }
#define _noexcept_
KS: noexcept can help with performance but is terrible for debugging, this is meant to help easy way ...
Definition: Core.h:96
#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
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.
std::vector< int > CircularBoundsIndex
Indices of parameters with circular bounds.
int GetNumParams() const
Get total number of parameters.
std::vector< bool > param_skip_adapt_flags
Flags telling if parameter should be skipped during adaption.
void ToggleFixParameter(const int i)
Toggle fixing parameter at prior values.
bool use_adaptive
Are we using AMCMC?
void SetFixAllParameters()
Set all parameters to be fixed at prior values.
virtual void ProposeStep()
Generate a new proposed state.
void EnableSpecialProposal(const YAML::Node &param, const int Index, std::vector< PendingFunctionalFlipProposal > &PendingFunctionalFlipParameters)
Enable special proposal.
TH2D * GetCorrelationMatrix() const
KS: Convert covariance matrix to correlation matrix and return TH2D which can be used for fancy plott...
void SanitizeAdaption() const
Perform sanity check to ensure adaption isn't misbehaving before fit starts.
double * randParams
Random number taken from gaussian around prior error used for corr_throw.
void SetName(const std::string &name)
Set matrix name.
std::map< std::string, FlipGroup > FlipGroups
Map of flip groups, where the key is the group name and the value is a FlipGroup struct.
void AddFunctionalFlip(const YAML::Node &param, const int index, const std::string &group_name)
Parse and register a functional flip defined in YAML.
double ** throwMatrixCholDecomp
Throw matrix that is being used in the fit, much faster as TMatrixDSym cache miss.
void SetStepScale(const double scale, const bool verbose=true)
Set global step scale for covariance object.
virtual ~ParameterHandlerBase()
Destructor.
TMatrixDSym * invCovMatrix
The inverse covariance matrix.
void SetCovMatrix(TMatrixDSym *cov)
Set covariance matrix.
std::string GetParName(const int i) const
Get name of parameter.
void SetFlatPrior(const int i, const bool eL)
Set if parameter should have flat prior or not.
void AcceptStep() _noexcept_
Accepted this step.
virtual double GetLikelihood()
Return CalcLikelihood if some params were thrown out of boundary return LARGE_LOGL
std::unique_ptr< AdaptiveMCMCHandler > AdaptiveHandler
Struct containing information about adaption.
std::vector< M3::float_t > _fPropVal
Proposed value of the parameter.
std::unique_ptr< ParameterTunes > Tunes
Struct containing information about adaption.
void InitialiseAdaption(const YAML::Node &adapt_manager)
Initialise adaptive MCMC.
TMatrixDSym * throwMatrix
Matrix which we use for step proposal before Cholesky decomposition (not actually used for step propo...
double _fGlobalStepScale
Global step scale applied to all params in this class.
void FlipParameterGroup(const std::string &group)
With a 50% chance, flip all parameters in a group around their respective flip points.
int GetParIndex(const std::string &name) const
Get index based on name.
void ReserveMemory(const int size)
Initialise vectors with parameters information.
M3::float_t EvaluateFunctionalFlip(const FunctionalFlipProposal &flip, const std::vector< double > &proposed_values) const
Evaluate a formula-driven flip for a target parameter.
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.
void ThrowParameters()
Throw the parameters according to the covariance matrix. This shouldn't be used in MCMC code ase it c...
double _fGlobalStepScaleInitial
Backup of _fGlobalStepScale for parameters which are skipped during adaption.
std::string matrixName
Name of cov matrix.
void MakeClosestPosDef(TMatrixDSym *cov)
HW: Finds closest possible positive definite matrix in Frobenius Norm ||.||_frob Where ||X||_frob=sqr...
void RandomConfiguration()
Randomly throw the parameters in their 1 sigma range.
TMatrixDSym * GetCovMatrix() const
Return covariance matrix.
void UpdateAdaptiveCovariance()
Method to update adaptive MCMC .
std::string GetParFancyName(const int i) const
Get fancy name of the Parameter.
std::vector< double > _fError
Prior error on the parameter.
void SetFreeAllParameters()
Set all parameters to be treated as free.
void SetFixParameter(const int i)
Set parameter to be fixed at prior value.
void SetParameters(const std::vector< double > &pars={})
Set parameter values using vector, it has to have same size as covariance class.
YAML::Node _fYAMLDoc
Stores config describing systematics.
void SetThrowMatrix(const TMatrixDSym *cov)
Use new throw matrix, used in adaptive MCMC.
bool IsParameterFixed(const int i) const
Is parameter fixed or not.
void MatchMaCh3OutputBranches(TTree *PosteriorFile, std::vector< double > &BranchValues, std::vector< std::string > &BranchNames, const std::vector< std::string > &FancyNames={})
Matches branches in a TTree to parameters in a systematic handler.
void UpdateThrowMatrix(TMatrixDSym *cov)
Replaces old throw matrix with new one.
void CircularParBounds(const int i, const double LowBound, const double UpBound)
HW :: This method is a tad hacky but modular arithmetic gives me a headache.
void SetBranches(TTree &tree, const bool SaveProposal=false)
set branches for output file
void SaveUpdatedMatrixConfig()
KS: After step scale, prefit etc. value were modified save this modified config.
void InitFromFile(const std::string &name, const std::string &file)
Initialisation of the class using matrix from root file.
void ResetIndivStepScale()
Adaptive Step Tuning Stuff.
std::unique_ptr< PCAHandler > PCAObj
Struct containing information about PCA.
int _fNumPar
Number of systematic parameters.
double CalcLikelihood() const _noexcept_
Calc penalty term based on inverted covariance matrix.
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 > _fIndivStepScaleInitial
Backup of _fIndivStepScale for parameters which are skipped during adaption.
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.
std::vector< std::vector< double > > InvertCovMatrix
KS: Same as above but much faster as TMatrixDSym cache miss.
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...
void PrintIndivStepScale() const
Print step scale for each parameter.
std::vector< std::string > _fNames
ETA _fNames is set automatically in the covariance class to be something like param_i,...
std::vector< std::pair< double, double > > CircularBoundsValues
Circular bounds for each parameter (lower, upper)
double * corr_throw
Result of multiplication of Cholesky matrix and randParams.
bool GetFlatPrior(const int i) const
Get if param has flat prior or not.
std::string GetName() const
Get name of covariance.
double GetParPreFit(const int i) const
Get prior parameter value.
void SetParCurrProp(const int i, const double val)
Set current parameter value.
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 SetSingleParameter(const int parNo, const double parVal)
Set value of single param to a given value.
void SetPar(const int i, const double val)
Set all the covariance matrix parameters to a user-defined value.
void SetIndivStepScale(const int ParameterIndex, const double StepScale)
DB Function to set fIndivStepScale from a vector (Can be used from execs and inside covariance constr...
void SetIndivStepScaleForSkippedAdaptParams()
Set individual step scale for parameters which are skipped during adaption to initial values.
double GetDiagonalError(const int i) const
Get diagonal error for ith parameter.
ParameterHandlerBase()=default
void SetSubThrowMatrix(int first_index, int last_index, TMatrixDSym const &subcov)
void SetTune(const std::string &TuneName)
KS: Set proposed parameter values vector to be base on tune values, for example set proposed values t...
bool pca
perform PCA or not
std::vector< double > _fIndivStepScale
Individual step scale used by MCMC algorithm.
void PrintPreFitValues() const
Print prior value for every parameter.
void QueueFunctionalFlip(std::vector< PendingFunctionalFlipProposal > &PendingFunctionalFlipParameters, const YAML::Node &param, const int index, const std::string &group_name)
Queue a functional flip until all parameters have been loaded.
void SpecialStepProposal()
Perform Special Step Proposal.
void PrintPreFitCurrPropValues() const
Print prior, current and proposed value for each parameter.
void CorrelateSteps() _noexcept_
Use Cholesky throw matrix for better step proposal.
void MakePosDef(TMatrixDSym *cov=nullptr, bool verbose=true)
Make matrix positive definite by adding small values to diagonal, necessary for inverting matrix.
int CheckBounds() const _noexcept_
Check if parameters were proposed outside physical boundary.
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 FormatDouble(const double value, const int precision)
Convert double into string for precision, useful for playing with yaml if you don't want to have in c...
@ Right
Align text to the right.
@ Left
Align text to the left.
double Uniform(const double min=0.0, const double max=1.0)
Generate a uniform random number in [min, max).
Definition: Random.h:116
double Gaus(const double mean=0.0, const double sigma=1.0)
Generate a Gaussian random number.
Definition: Random.h:137
constexpr static const double _LARGE_LOGL_
Large Likelihood is used it parameter go out of physical boundary, this indicates in MCMC that such s...
Definition: Core.h:80
void MatrixVectorMulti(double *_restrict_ VecMulti, double **_restrict_ matrix, const double *_restrict_ vector, const int n)
KS: Custom function to perform multiplication of matrix and vector with multithreading.
double float_t
Definition: Core.h:37
double MatrixVectorMultiSingle(double **_restrict_ matrix, const double *_restrict_ vector, const int Length, const int i)
KS: Custom function to perform multiplication of matrix and single element which is thread safe.
int MakeMatrixPosDef(TMatrixDSym *cov)
Makes sure that matrix is positive-definite by adding a small number to on-diagonal elements.
constexpr static const int _BAD_INT_
Default value used for int initialisation.
Definition: Core.h:55
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.
std::vector< std::vector< double > > GetCholeskyDecomposedMatrix(const TMatrixDSym &matrix, const std::string &matrixName)
Computes Cholesky decomposition of a symmetric positive definite matrix using custom function which c...
Struct to hold information about a group of parameters that flip together at the same time.
std::vector< int > FlipParameterIndex
Indices of parameters with flip symmetry.
std::vector< double > FlipParameterPoint
Central points around which parameters are flipped.
std::vector< FunctionalFlipProposal > FunctionalFlipParameters
Formula-driven flips that should be applied when this group flips.
Configuration for a formula-based functional flip.
std::vector< int > argument_indices
parameter indices passed to evaluator
std::vector< std::string > argument_names
Parameter names that are passed to evaluator.
std::unique_ptr< TF1 > evaluator
function used to evaluate flipping formula
Configuration for a pending functional flip awaiting all parameters to be initialised.