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),
32 grad_(N_dim),
33 N_tasks_(N_dim)
34{
35 // Note to future maintainers: take care when storing the minimizer_fcn pointer. The
36 // RooAbsMinimizerFcn subclasses may get cloned inside MINUIT, which means the pointer
37 // should also somehow be updated in this class.
38
39 minuit_internal_x_.reserve(N_dim);
40}
41
43 : MultiProcess::Job(other), LikelihoodGradientWrapper(other), grad_(other.grad_), gradf_(other.gradf_),
44 N_tasks_(other.N_tasks_), minuit_internal_x_(other.minuit_internal_x_)
45{
46}
47
49{
50 return new LikelihoodGradientJob(*this);
51}
52
54 const std::vector<ROOT::Fit::ParameterSettings> &parameter_settings)
55{
57}
58
60 ROOT::Math::IMultiGenFunction *function, const std::vector<ROOT::Fit::ParameterSettings> &parameter_settings)
61{
62 gradf_.SetInitialGradient(function, parameter_settings, grad_);
63}
64
66{
67 setStrategy(options.Strategy());
68 setErrorLevel(options.ErrorDef());
69}
70
72{
73 assert(istrat >= 0);
74 ROOT::Minuit2::MnStrategy strategy(static_cast<unsigned int>(istrat));
75
78 setNCycles(strategy.GradientNCycles());
79}
80
81void LikelihoodGradientJob::setStepTolerance(double step_tolerance) const
82{
83 gradf_.SetStepTolerance(step_tolerance);
84}
85
86void LikelihoodGradientJob::setGradTolerance(double grad_tolerance) const
87{
88 gradf_.SetGradTolerance(grad_tolerance);
89}
90
91void LikelihoodGradientJob::setNCycles(unsigned int ncycles) const
92{
93 gradf_.SetNCycles(ncycles);
94}
95
96void LikelihoodGradientJob::setErrorLevel(double error_level) const
97{
98 gradf_.SetErrorLevel(error_level);
99}
100
101///////////////////////////////////////////////////////////////////////////////
102/// Job overrides:
103
105{
106 run_derivator(task);
107}
108
109// SYNCHRONIZATION FROM WORKERS TO MASTER
110
112{
113 task_result_t task_result{id_, task, grad_[task]};
114 zmq::message_t message(sizeof(task_result_t));
115 memcpy(message.data(), &task_result, sizeof(task_result_t));
116 get_manager()->messenger().send_from_worker_to_master(std::move(message));
117}
118
120{
121 auto result = message.data<task_result_t>();
122 grad_[result->task_id] = result->grad;
124 bool job_completed = (N_tasks_at_workers_ == 0);
125 return job_completed;
126}
127
128// END SYNCHRONIZATION FROM WORKERS TO MASTER
129
130// SYNCHRONIZATION FROM MASTER TO WORKERS (STATE)
131
133{
134 // TODO optimization: only send changed parameters (now sending all)
135 zmq::message_t gradient_message(grad_.begin(), grad_.end());
136 zmq::message_t minuit_internal_x_message(minuit_internal_x_.begin(), minuit_internal_x_.end());
137 ++state_id_;
139 std::move(minuit_internal_x_message));
140}
141
143{
144 ++state_id_;
146}
147
149{
150 bool more;
151
153
155
156 if (more) {
157 auto gradient_message = get_manager()->messenger().receive_from_master_on_worker<zmq::message_t>(&more);
158 assert(more);
159 auto gradient_message_begin = gradient_message.data<ROOT::Minuit2::DerivatorElement>();
160 auto gradient_message_end =
161 gradient_message_begin + gradient_message.size() / sizeof(ROOT::Minuit2::DerivatorElement);
162 std::copy(gradient_message_begin, gradient_message_end, grad_.begin());
163
164 auto minuit_internal_x_message = get_manager()->messenger().receive_from_master_on_worker<zmq::message_t>(&more);
165 assert(!more);
166 auto minuit_internal_x_message_begin = minuit_internal_x_message.data<double>();
167 auto minuit_internal_x_message_end =
168 minuit_internal_x_message_begin + minuit_internal_x_message.size() / sizeof(double);
169 std::copy(minuit_internal_x_message_begin, minuit_internal_x_message_end, minuit_internal_x_.begin());
170
173 }
174}
175
176// END SYNCHRONIZATION FROM MASTER TO WORKERS (STATE)
177
178///////////////////////////////////////////////////////////////////////////////
179/// Calculation stuff (mostly duplicates of RooGradMinimizerFcn code):
180
181void LikelihoodGradientJob::run_derivator(unsigned int i_component) const
182{
183 // Calculate the derivative etc for these parameters
184 grad_[i_component] = gradf_.FastPartialDerivative(
185 minimizer_->getMultiGenFcn(), minimizer_->fitter()->Config().ParamsSettings(), i_component, grad_[i_component]);
186}
187
189{
190 if (get_manager()->process_manager().is_master()) {
191 isCalculating_ = true;
193
194 // master fills queue with tasks
195 for (std::size_t ix = 0; ix < N_tasks_; ++ix) {
196 MultiProcess::JobTask job_task{id_, state_id_, ix};
197 get_manager()->queue()->add(job_task);
198 }
200 // wait for task results back from workers to master (put into _grad)
202
203 calculation_is_clean_->gradient = true;
204 isCalculating_ = false;
206 }
207}
208
210{
211 if (get_manager()->process_manager().is_master()) {
212 if (!calculation_is_clean_->gradient) {
214 }
215
216 // put the results from _grad into *grad
217 for (Int_t ix = 0; ix < minimizer_->getNPar(); ++ix) {
218 grad[ix] = grad_[ix].derivative;
219 }
220 }
221}
222
223void LikelihoodGradientJob::fillGradientWithPrevResult(double *grad, double *previous_grad, double *previous_g2,
224 double *previous_gstep)
225{
226 if (get_manager()->process_manager().is_master()) {
227 for (std::size_t i_component = 0; i_component < N_tasks_; ++i_component) {
228 grad_[i_component] = {previous_grad[i_component], previous_g2[i_component], previous_gstep[i_component]};
229 }
230
231 if (!calculation_is_clean_->gradient) {
235 }
236
237 // put the results from _grad into *grad
238 for (Int_t ix = 0; ix < minimizer_->getNPar(); ++ix) {
239 grad[ix] = grad_[ix].derivative;
240 previous_g2[ix] = grad_[ix].second_derivative;
241 previous_gstep[ix] = grad_[ix].step_size;
242 }
243 }
244}
245
246void LikelihoodGradientJob::updateMinuitInternalParameterValues(const std::vector<double> &minuit_internal_x)
247{
248 minuit_internal_x_ = minuit_internal_x;
249}
250
252{
253 return true;
254}
255
256} // namespace TestStatistics
257} // namespace RooFit
RooAbsReal & function()
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:422
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:110
void gather_worker_results()
Wait for all tasks to be retrieved for the current Job.
Definition Job.cxx:124
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)
Wrapper class around ROOT::Fit:Fitter that provides a seamless interface between the minimizer functi...
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