Tomographer  v5.2
Tomographer C++ Framework Documentation
mhrwvalueerrorbinsconvergedcontroller.h
Go to the documentation of this file.
1 /* This file is part of the Tomographer project, which is distributed under the
2  * terms of the MIT license.
3  *
4  * The MIT License (MIT)
5  *
6  * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist
7  * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25  * SOFTWARE.
26  */
27 
28 #ifndef _TOMOGRAPHER_MHRWVALUEERRORBINSCONVERGEDCONTROLLER_H
29 #define _TOMOGRAPHER_MHRWVALUEERRORBINSCONVERGEDCONTROLLER_H
30 
31 #include <cstddef>
32 #include <cmath>
33 #include <cstdlib>
34 
35 #include <algorithm> // std::max
36 #include <limits>
37 #include <random>
38 #include <iomanip>
39 
41 #include <tomographer/tools/fmt.h>
44 #include <tomographer/mhrw.h>
46 
47 
57 namespace Tomographer {
58 
59 
66 template<typename ValueHistogramWithBinningMHRWStatsCollectorType_,
67  typename IterCountIntType_,
68  typename BaseLoggerType_>
69 class TOMOGRAPHER_EXPORT MHRWValueErrorBinsConvergedController
70 {
71 public:
72  // we never have to adjust the params, we just forbid from stopping too early in the
73  // allowDoneRuns() callback
74  enum { AdjustmentStrategy = MHRWControllerDoNotAdjust };
75 
76  typedef ValueHistogramWithBinningMHRWStatsCollectorType_
77  ValueHistogramWithBinningMHRWStatsCollectorType;
78 
79  typedef IterCountIntType_ IterCountIntType;
80 
81  typedef BaseLoggerType_ BaseLoggerType;
82 
83 private:
84  const ValueHistogramWithBinningMHRWStatsCollectorType & value_stats_collector;
85 
86  const IterCountIntType check_frequency_sweeps;
87 
88  IterCountIntType last_forbidden_iter_number;
89 
90  const Eigen::Index max_allowed_unknown;
91  const Eigen::Index max_allowed_unknown_notisolated;
92  const Eigen::Index max_allowed_not_converged;
93 
94  const double max_add_run_iters;
95 
97 
98 public:
105  const ValueHistogramWithBinningMHRWStatsCollectorType & value_stats_collector_,
106  BaseLoggerType & baselogger_,
107  IterCountIntType check_frequency_sweeps_ = 1024,
108  Eigen::Index max_allowed_unknown_ = 0,
109  Eigen::Index max_allowed_unknown_notisolated_ = 0,
110  Eigen::Index max_allowed_not_converged_ = 0,
111  double max_add_run_iters_ = 1.5
112  )
113  : value_stats_collector(value_stats_collector_),
114  check_frequency_sweeps(check_frequency_sweeps_),
115  last_forbidden_iter_number(0),
116  max_allowed_unknown(max_allowed_unknown_),
117  max_allowed_unknown_notisolated(max_allowed_unknown_notisolated_),
118  max_allowed_not_converged(max_allowed_not_converged_),
119  max_add_run_iters(max_add_run_iters_),
120  llogger("Tomographer::MHRWValueErrorBinsConvergedAdjuster", baselogger_)
121  {
122  }
123 
124  template<typename MHRWParamsType, typename MHWalker, typename MHRandomWalkType>
125  inline void init(MHRWParamsType & /*params*/, const MHWalker & /*mhwalker*/,
126  const MHRandomWalkType & /*mhrw*/) const
127  {
128  }
129 
130  template<typename MHRWParamsType, typename MHWalker, typename CountIntType, typename MHRandomWalkType>
131  bool allowDoneThermalization(const MHRWParamsType & /*params*/, const MHWalker & /*mhwalker*/,
132  CountIntType /*iter_k*/, const MHRandomWalkType & /*mhrw*/) const
133  {
134  return true;
135  }
136 
137  template<typename MHRWParamsType, typename MHWalker, typename MHRandomWalkType>
138  bool allowDoneRuns(const MHRWParamsType & params, const MHWalker & /*mhwalker*/,
139  IterCountIntType iter_k, const MHRandomWalkType & /*mhrw*/)
140  {
141 
142  if (check_frequency_sweeps == 0) {
143  // controller is manually disabled by setting check_frequency_sweeps=0
144  return true;
145  }
146 
147  auto logger = llogger.subLogger(TOMO_ORIGIN);
148 
149  if (last_forbidden_iter_number > 0 &&
150  (iter_k-last_forbidden_iter_number) < params.n_sweep*check_frequency_sweeps) {
151  // not enough new samples since last time we rejected to finish the random walk
152  return false;
153  }
154 
155  logger.longdebug([&](std::ostream & stream) {
156  stream << "params=" << params << ", iter_k=" << iter_k
157  << ", max_add_run_iters=" << max_add_run_iters;
158  });
159 
160  // if we have exceeded the maximum number of run iterations, emit a warning
161  // and stop (max_add_run_iters < 0 disables this feature)
162  if (max_add_run_iters > 0 && iter_k > max_add_run_iters * params.n_run * params.n_sweep) {
163  logger.warning([&](std::ostream & stream) {
164  stream << "Ending random walk after reaching maximum sweep number "
165  << iter_k/params.n_sweep <<" ("
166  << 100.0*iter_k/(params.n_sweep*params.n_run) << "% of set run length)";
167  }) ;
168  return true;
169  }
170 
171  // re-check if the error bars have converged
172 
173  // do a convergence analysis of the error bars
174  const auto& binning_analysis = value_stats_collector.getBinningAnalysis();
175  const auto binmeans = value_stats_collector.binMeans();
176 
177  const auto error_levels = binning_analysis.calcErrorLevels(binmeans);
178  const auto conv_status = binning_analysis.determineErrorConvergence(error_levels);
179 
180  const auto conv_summary = BinningErrorBarConvergenceSummary::fromConvergedStatus(conv_status);
181 
182  logger.longdebug([&](std::ostream & stream) { stream << "Convergence summary = " << conv_summary; }) ;
183 
184  if (conv_summary.n_not_converged > max_allowed_not_converged ||
185  conv_summary.n_unknown > max_allowed_unknown ||
186  (conv_summary.n_unknown-conv_summary.n_unknown_isolated) > max_allowed_unknown_notisolated) {
187  // too many unconverged error bars, continue running
188  return false;
189  }
190 
191  // all ok
192  return true;
193  }
194 
195  template<typename MHRWParamsType, typename MHWalker, typename MHRandomWalkType>
196  inline void thermalizingDone(const MHRWParamsType & /*params*/, const MHWalker & /*mhwalker*/,
197  const MHRandomWalkType & /*mhrw*/) const
198  {
199  }
200 
201  template<typename MHRWParamsType, typename MHWalker, typename MHRandomWalkType>
202  inline void done(MHRWParamsType & /*params*/, const MHWalker & /*mhwalker*/,
203  const MHRandomWalkType & /*mhrw*/) const
204  {
205  }
206 };
207 
208 
214 template<typename IterCountIntType_ = int,
215  // these types are deduced from the args anyway:
216  typename ValueHistogramWithBinningMHRWStatsCollectorType_ = void,
217  typename BaseLoggerType_ = void>
218 inline MHRWValueErrorBinsConvergedController<ValueHistogramWithBinningMHRWStatsCollectorType_,
219  IterCountIntType_,
220  BaseLoggerType_>
222  const ValueHistogramWithBinningMHRWStatsCollectorType_ & value_stats_collector_,
223  BaseLoggerType_ & baselogger_,
224  IterCountIntType_ check_frequency_sweeps_ = 1024,
225  Eigen::Index max_allowed_unknown_ = 0,
226  Eigen::Index max_allowed_unknown_notisolated_ = 0,
227  Eigen::Index max_allowed_not_converged_ = 0,
228  double max_add_run_iters = 1.5
229  )
230 {
231  return MHRWValueErrorBinsConvergedController<ValueHistogramWithBinningMHRWStatsCollectorType_,
232  IterCountIntType_,
233  BaseLoggerType_>(
234  value_stats_collector_,
235  baselogger_,
236  check_frequency_sweeps_,
237  max_allowed_unknown_,
238  max_allowed_unknown_notisolated_,
239  max_allowed_not_converged_,
240  max_add_run_iters
241  ) ;
242 }
243 
244 
245 
246 
247 } // namespace Tomographer
248 
249 
250 
251 #endif
Utilities for formatting strings.
static BinningErrorBarConvergenceSummary fromConvergedStatus(const Eigen::Ref< const Eigen::ArrayXi > &converged_status)
Construct a summary object from a list of converged status obtained from BinningAnalysis::determineEr...
Definition: mhrw_bin_err.h:131
A MHRWController Interface which stops the random walk after enough samples have been taken to make a...
Base namespace for the Tomographer project.
Definition: densellh.h:45
#define TOMO_ORIGIN
Use this as argument for a Tomographer::Logger::LocalLogger constructor .
Definition: loggers.h:1528
LocalLogger< LocalLogger< BaseLoggerType > > subLogger(std::string new_prefix)
Create a sub-logger.
Definition: loggers.h:1766
Never adjust the parameters of the random walk.
Definition: mhrw.h:190
MHRWValueErrorBinsConvergedController(const ValueHistogramWithBinningMHRWStatsCollectorType &value_stats_collector_, BaseLoggerType &baselogger_, IterCountIntType check_frequency_sweeps_=1024, Eigen::Index max_allowed_unknown_=0, Eigen::Index max_allowed_unknown_notisolated_=0, Eigen::Index max_allowed_not_converged_=0, double max_add_run_iters_=1.5)
Constructor.
Some C++ utilities, with a tad of C++11 tricks.
Managing the need for specific overrides to operator new() for some types (especially Eigen types) ...
MHRWValueErrorBinsConvergedController< ValueHistogramWithBinningMHRWStatsCollectorType_, IterCountIntType_, BaseLoggerType_ > mkMHRWValueErrorBinsConvergedController(const ValueHistogramWithBinningMHRWStatsCollectorType_ &value_stats_collector_, BaseLoggerType_ &baselogger_, IterCountIntType_ check_frequency_sweeps_=1024, Eigen::Index max_allowed_unknown_=0, Eigen::Index max_allowed_unknown_notisolated_=0, Eigen::Index max_allowed_not_converged_=0, double max_add_run_iters=1.5)
Convenience function to create a MHRWValueErrorBinsConvergedController (using template argument deduc...
Definitions for MHRWStatsCollector Interface&#39;s.
Routines for performing a Metropolis-Hastings random walk.
STL class.
Utilities for logging messages.