Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
LikelihoodGradientJob.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * PB, Patrick Bos, Netherlands eScience Center, p.bos@esciencecenter.nl
5 *
6 * Copyright (c) 2021, CERN
7 *
8 * Redistribution and use in source and binary forms,
9 * with or without modification, are permitted according to the terms
10 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
11 */
12
14
20#include "RooMsgService.h"
21#include "RooMinimizer.h"
22
23#include "Minuit2/MnStrategy.h"
24
25namespace RooFit {
26namespace TestStatistics {
27
28LikelihoodGradientJob::LikelihoodGradientJob(std::shared_ptr<RooAbsL> likelihood,
29 std::shared_ptr<WrapperCalculationCleanFlags> calculation_is_clean,
30 std::size_t N_dim, RooMinimizer *minimizer)
31 : LikelihoodGradientWrapper(std::move(likelihood), std::move(calculation_is_clean), N_dim, minimizer), grad_(N_dim)
32{
33 // Note to future maintainers: take care when storing the minimizer_fcn pointer. The
34 // RooAbsMinimizerFcn subclasses may get cloned inside MINUIT, which means the pointer
35 // should also somehow be updated in this class.
36 N_tasks_ = N_dim;
37 minuit_internal_x_.reserve(N_dim);
38}
39
41 : MultiProcess::Job(other), LikelihoodGradientWrapper(other), grad_(other.grad_), gradf_(other.gradf_),
42 N_tasks_(other.N_tasks_), minuit_internal_x_(other.minuit_internal_x_)
43{
44}
45
47{
48 return new LikelihoodGradientJob(*this);
49}
50
52 const std::vector<ROOT::Fit::ParameterSettings> &parameter_settings)
53{
55}
56
58 ROOT::Math::IMultiGenFunction *function, const std::vector<ROOT::Fit::ParameterSettings> &parameter_settings)
59{
60 gradf_.SetInitialGradient(function, parameter_settings, grad_);
61}
62
64{
65 setStrategy(options.Strategy());
66 setErrorLevel(options.ErrorDef());
67}
68
70{
71 assert(istrat >= 0);
72 ROOT::Minuit2::MnStrategy strategy(static_cast<unsigned int>(istrat));
73
76 setNCycles(strategy.GradientNCycles());
77}
78
79void LikelihoodGradientJob::setStepTolerance(double step_tolerance) const
80{
81 gradf_.SetStepTolerance(step_tolerance);
82}
83
84void LikelihoodGradientJob::setGradTolerance(double grad_tolerance) const
85{
86 gradf_.SetGradTolerance(grad_tolerance);
87}
88
89void LikelihoodGradientJob::setNCycles(unsigned int ncycles) const
90{
91 gradf_.SetNCycles(ncycles);
92}
93
94void LikelihoodGradientJob::setErrorLevel(double error_level) const
95{
96 gradf_.SetErrorLevel(error_level);
97}
98
99///////////////////////////////////////////////////////////////////////////////
100/// Job overrides:
101
103{
104 run_derivator(task);
105}
106
107// SYNCHRONIZATION FROM WORKERS TO MASTER
108
110{
111 task_result_t task_result{id_, task, grad_[task]};
112 zmq::message_t message(sizeof(task_result_t));
113 memcpy(message.data(), &task_result, sizeof(task_result_t));
114 get_manager()->messenger().send_from_worker_to_master(std::move(message));
115}
116
118{
119 auto result = message.data<task_result_t>();
120 grad_[result->task_id] = result->grad;
122 bool job_completed = (N_tasks_at_workers_ == 0);
123 return job_completed;
124}
125
126// END SYNCHRONIZATION FROM WORKERS TO MASTER
127
128// SYNCHRONIZATION FROM MASTER TO WORKERS (STATE)
129
131{
132 // TODO optimization: only send changed parameters (now sending all)
133 zmq::message_t gradient_message(grad_.begin(), grad_.end());
134 zmq::message_t minuit_internal_x_message(minuit_internal_x_.begin(), minuit_internal_x_.end());
135 ++state_id_;
137 std::move(minuit_internal_x_message));
138}
139
141{
142 ++state_id_;
144}
145
147{
148 bool more;
149
151
153
154 if (more) {
155 auto gradient_message = get_manager()->messenger().receive_from_master_on_worker<zmq::message_t>(&more);
156 assert(more);
157 auto gradient_message_begin = gradient_message.data<ROOT::Minuit2::DerivatorElement>();
158 auto gradient_message_end =
159 gradient_message_begin + gradient_message.size() / sizeof(ROOT::Minuit2::DerivatorElement);
160 std::copy(gradient_message_begin, gradient_message_end, grad_.begin());
161
162 auto minuit_internal_x_message = get_manager()->messenger().receive_from_master_on_worker<zmq::message_t>(&more);
163 assert(!more);
164 auto minuit_internal_x_message_begin = minuit_internal_x_message.data<double>();
165 auto minuit_internal_x_message_end =
166 minuit_internal_x_message_begin + minuit_internal_x_message.size() / sizeof(double);
167 std::copy(minuit_internal_x_message_begin, minuit_internal_x_message_end, minuit_internal_x_.begin());
168
171 }
172}
173
174// END SYNCHRONIZATION FROM MASTER TO WORKERS (STATE)
175
176///////////////////////////////////////////////////////////////////////////////
177/// Calculation stuff (mostly duplicates of RooGradMinimizerFcn code):
178
179void LikelihoodGradientJob::run_derivator(unsigned int i_component) const
180{
181 // Calculate the derivative etc for these parameters
182 grad_[i_component] = gradf_.FastPartialDerivative(
183 minimizer_->getMultiGenFcn(), minimizer_->fitter()->Config().ParamsSettings(), i_component, grad_[i_component]);
184}
185
187{
188 if (get_manager()->process_manager().is_master()) {
189 isCalculating_ = true;
191
192 // master fills queue with tasks
193 for (std::size_t ix = 0; ix < N_tasks_; ++ix) {
194 MultiProcess::JobTask job_task{id_, state_id_, ix};
195 get_manager()->queue()->add(job_task);
196 }
198 // wait for task results back from workers to master (put into _grad)
200
201 calculation_is_clean_->gradient = true;
202 isCalculating_ = false;
204 }
205}
206
208{
209 if (get_manager()->process_manager().is_master()) {
210 if (!calculation_is_clean_->gradient) {
212 }
213
214 // put the results from _grad into *grad
215 for (Int_t ix = 0; ix < minimizer_->getNPar(); ++ix) {
216 grad[ix] = grad_[ix].derivative;
217 }
218 }
219}
220
221void LikelihoodGradientJob::fillGradientWithPrevResult(double *grad, double *previous_grad, double *previous_g2,
222 double *previous_gstep)
223{
224 if (get_manager()->process_manager().is_master()) {
225 for (std::size_t i_component = 0; i_component < N_tasks_; ++i_component) {
226 grad_[i_component] = {previous_grad[i_component], previous_g2[i_component], previous_gstep[i_component]};
227 }
228
229 if (!calculation_is_clean_->gradient) {
233 }
234
235 // put the results from _grad into *grad
236 for (Int_t ix = 0; ix < minimizer_->getNPar(); ++ix) {
237 grad[ix] = grad_[ix].derivative;
238 previous_g2[ix] = grad_[ix].second_derivative;
239 previous_gstep[ix] = grad_[ix].step_size;
240 }
241 }
242}
243
244void LikelihoodGradientJob::updateMinuitInternalParameterValues(const std::vector<double> &minuit_internal_x)
245{
246 minuit_internal_x_ = minuit_internal_x;
247}
248
250{
251 return true;
252}
253
254} // namespace TestStatistics
255} // namespace RooFit
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
const std::vector< ROOT::Fit::ParameterSettings > & ParamsSettings() const
get the vector of parameter settings (const method)
Definition FitConfig.h:86
const FitConfig & Config() const
access to the fit configuration (const method)
Definition Fitter.h:421
Documentation for the abstract class IBaseFunctionMultiDim.
Definition IFunction.h:61
double ErrorDef() const
error definition
API class for defining four levels of strategies: low (0), medium (1), high (2), very high (>=3); act...
Definition MnStrategy.h:27
double GradientStepTolerance() const
Definition MnStrategy.h:41
double GradientTolerance() const
Definition MnStrategy.h:42
unsigned int GradientNCycles() const
Definition MnStrategy.h:40
void SetupDifferentiate(const ROOT::Math::IBaseFunctionMultiDim *function, const double *cx, const std::vector< ROOT::Fit::ParameterSettings > &parameters)
This function sets internal state based on input parameters.
void SetNCycles(unsigned int value)
void SetInitialGradient(const ROOT::Math::IBaseFunctionMultiDim *function, const std::vector< ROOT::Fit::ParameterSettings > &parameters, std::vector< DerivatorElement > &gradient)
This function was not implemented as in Minuit2.
DerivatorElement FastPartialDerivative(const ROOT::Math::IBaseFunctionMultiDim *function, const std::vector< ROOT::Fit::ParameterSettings > &parameters, unsigned int i_component, const DerivatorElement &previous)
static bool getTimingAnalysis()
Definition Config.cxx:87
std::size_t id_
Definition Job.h:45
std::size_t state_id_
Definition Job.h:46
JobManager * get_manager()
Get JobManager instance; create and activate if necessary.
Definition Job.cxx:116
void gather_worker_results()
Wait for all tasks to be retrieved for the current Job.
Definition Job.cxx:130
value_t receive_from_master_on_worker(bool *more=nullptr)
Definition Messenger.h:176
void publish_from_master_to_workers(T &&item)
specialization that sends the final message
Definition Messenger.h:150
static void start_timer(std::string section_name)
static void end_timer(std::string section_name)
virtual void add(JobTask job_task)=0
Enqueue a task.
bool usesMinuitInternalValues() override
Implement usesMinuitInternalValues to return true when you want Minuit to send this class Minuit-inte...
void update_state() override
Virtual function to update any necessary state on workers.
std::vector< ROOT::Minuit2::DerivatorElement > grad_
void fillGradientWithPrevResult(double *grad, double *previous_grad, double *previous_g2, double *previous_gstep) override
void updateMinuitInternalParameterValues(const std::vector< double > &minuit_internal_x) override
Minuit passes in parameter values that may not conform to RooFit internal standards (like applying ra...
void synchronizeParameterSettings(ROOT::Math::IMultiGenFunction *function, const std::vector< ROOT::Fit::ParameterSettings > &parameter_settings) override
void run_derivator(unsigned int i_component) const
Calculation stuff (mostly duplicates of RooGradMinimizerFcn code):
void send_back_task_result_from_worker(std::size_t task) override
void synchronizeWithMinimizer(const ROOT::Math::MinimizerOptions &options) override
Synchronize minimizer settings with calculators in child classes.
LikelihoodGradientJob(std::shared_ptr< RooAbsL > likelihood, std::shared_ptr< WrapperCalculationCleanFlags > calculation_is_clean, std::size_t N_dim, RooMinimizer *minimizer)
void setStepTolerance(double step_tolerance) const
void setGradTolerance(double grad_tolerance) const
void evaluate_task(std::size_t task) override
Job overrides:
bool receive_task_result_on_master(const zmq::message_t &message) override
LikelihoodGradientJob * clone() const override
Virtual base class for implementation of likelihood gradient calculation strategies.
std::shared_ptr< WrapperCalculationCleanFlags > calculation_is_clean_
virtual void synchronizeParameterSettings(const std::vector< ROOT::Fit::ParameterSettings > &parameter_settings)
RooMinimizer is a wrapper class around ROOT::Fit:Fitter that provides a seamless interface between th...
ROOT::Math::IMultiGenFunction * getMultiGenFcn() const
ROOT::Fit::Fitter * fitter()
Return underlying ROOT fitter object.
int getNPar() const
std::size_t State
Definition types.h:23
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition JSONIO.h:26
combined job_object, state and task identifier type
Definition types.h:25