Tomographer  v5.2
Tomographer C++ Framework Documentation
mhrw_valuehist_tools.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_MHRW_VALUEHIST_TOOLS_H
29 #define TOMOGRAPHER_MHRW_VALUEHIST_TOOLS_H
30 
31 
32 #include <iostream>
33 #include <iomanip>
34 
36 #include <tomographer/tools/cxxutil.h> // tomographer_assert()
39 #include <tomographer/mhrwtasks.h>
40 
41 #include <boost/math/constants/constants.hpp>
42 
43 
55 namespace Tomographer {
56 namespace MHRWTasks {
57 namespace ValueHistogramTools {
58 
59 
60 
61 
68 template<typename RawHistogramType_, typename ScaledHistogramType_>
69 struct TOMOGRAPHER_EXPORT MHRWStatsResultsBaseSimple
70 {
71  typedef RawHistogramType_ RawHistogramType;
72  typedef ScaledHistogramType_ ScaledHistogramType;
73 
74  MHRWStatsResultsBaseSimple(RawHistogramType && val)
75  : raw_histogram(std::move(val)),
76  histogram(raw_histogram.params)
77  {
78  typedef typename ScaledHistogramType::CountType CountRealType;
79  CountRealType ncounts = raw_histogram.totalCounts();
80  histogram.load(raw_histogram.bins.template cast<CountRealType>() / ncounts,
81  raw_histogram.off_chart / ncounts);
82  }
83 
84  RawHistogramType raw_histogram;
85 
86  ScaledHistogramType histogram;
87 };
88 
89 
90 
91 
92 
93 
94 // -----------------------------------------------
95 
96 
97 namespace tomo_internal {
98 //
99 // version WITHOUT binning analysis:
100 //
101 template<typename CDataBaseType, bool UseBinningAnalysis>
102 struct valuehist_types
103 {
104  typedef Histogram<typename CDataBaseType::ValueCalculator::ValueType,
105  typename CDataBaseType::HistCountIntType> HistogramType;
106 
107  // useful types
108 
109  // we know that ValueHistogramMHRWStatsCollector<ValueCalculator,...,HistogramType>::ResultType is HistogramType
110  typedef HistogramType ValueStatsCollectorResultType;
111  typedef typename HistogramType::Params HistogramParams;
112  typedef typename CDataBaseType::CountRealType CountRealType;
114 
115  // base type for user cdata to use as MHRWStatsResults member
117  MHRWStatsResultsBaseType;
118 
119  // the correct histogram aggregator type
121 };
122 //
123 // version WITH binning analysis:
124 //
125 template<typename CDataBaseType>
126 struct valuehist_types<CDataBaseType, true>
127 {
128  // useful types
129 
130  typedef typename CDataBaseType::CountRealType CountRealType;
131 
134  typename CDataBaseType::ValueCalculator,
135  typename CDataBaseType::HistCountIntType,
136  CountRealType,
137  Eigen::Dynamic,
138  Eigen::Dynamic
139  > BinningMHRWStatsCollectorParams;
140 
141  typedef typename BinningMHRWStatsCollectorParams::Result ValueStatsCollectorResultType;
142  typedef typename BinningMHRWStatsCollectorParams::HistogramType HistogramType;
143  typedef typename BinningMHRWStatsCollectorParams::HistogramParams HistogramParams;
144 
145  // base type for user cdata to use as MHRWStatsResults member
146  typedef ValueStatsCollectorResultType MHRWStatsResultsBaseType;
147 
148  // the correct histogram aggregator type
150 };
151 } // namespace tomo_internal
152 
153 
154 // ------------------------------------------------
155 
156 
157 
228 template<typename ValueCalculator_,
229  bool UseBinningAnalysis_ = true,
230  typename MHWalkerParams_ = MHWalkerParamsStepSize<double>,
231  typename RngSeedType_ = std::mt19937::result_type,
232  typename IterCountIntType_ = int,
233  typename CountRealType_ = double,
234  typename HistCountIntType_ = IterCountIntType_>
235 struct TOMOGRAPHER_EXPORT CDataBase
236  : public MHRWTasks::CDataBase<MHWalkerParams_, IterCountIntType_, RngSeedType_>,
237  public virtual Tools::NeedOwnOperatorNew<ValueCalculator_>::ProviderType
238 {
241 
244 
246  typedef typename Base::RngSeedType RngSeedType;
247 
250 
252  typedef HistCountIntType_ HistCountIntType;
253 
257  typedef ValueCalculator_ ValueCalculator;
259  typedef CountRealType_ CountRealType;
260 
262  static constexpr bool UseBinningAnalysis = UseBinningAnalysis_;
263 
276 
289 
305 
310 
313 
314 
316  TOMOGRAPHER_ENABLED_IF(!UseBinningAnalysis)
317  CDataBase(const ValueCalculator & valcalc_, HistogramParams histogram_params_,
318  MHRWParamsType p, RngSeedType base_seed = 0)
319  : Base(std::move(p), base_seed), valcalc(valcalc_), histogram_params(histogram_params_),
320  binningNumLevels()
321  {
322  }
323 
325  TOMOGRAPHER_ENABLED_IF(UseBinningAnalysis)
326  CDataBase(const ValueCalculator & valcalc_, HistogramParams histogram_params_, int binning_num_levels_,
327  MHRWParamsType p, RngSeedType base_seed = 0)
328  : Base(std::move(p), base_seed), valcalc(valcalc_), histogram_params(histogram_params_),
329  binningNumLevels(binning_num_levels_)
330  {
331  }
332 
339 
340 
349  template<typename LoggerType, TOMOGRAPHER_ENABLED_IF_TMPL(!UseBinningAnalysis)>
351  createValueStatsCollector(LoggerType & logger) const
352  {
354  histogram_params,
355  valcalc,
356  logger
357  );
358  }
359 
368  template<typename LoggerType, TOMOGRAPHER_ENABLED_IF_TMPL(UseBinningAnalysis)>
370  typename tomo_internal::valuehist_types<CDataBase, true>::BinningMHRWStatsCollectorParams,
371  LoggerType>
372  createValueStatsCollector(LoggerType & logger) const
373  {
374  typedef typename tomo_internal::valuehist_types<CDataBase, true>::BinningMHRWStatsCollectorParams
375  BinningMHRWStatsCollectorParams;
376 
378  histogram_params,
379  valcalc,
380  binningNumLevels.value,
381  logger
382  );
383  }
384 
385 
388 
389 
398  template<typename TaskResultType>
399  AggregatedHistogramType aggregateResultHistograms(const std::vector<TaskResultType*> & task_result_list)
400  {
401  return AggregatedHistogramType::aggregate(
402  histogram_params,
403  task_result_list,
404  [](const TaskResultType * task_result)
405  -> const typename AggregatedHistogramType::HistogramType &
406  {
407  // .histogram is already the "scaled histogram". This works both
408  // for the "simple" version as well as for the
409  // "binning-analysis-error-bar" version.
410  return task_result->stats_results.histogram;
411  });
412  }
413 
414 
415 };
416 // define static members:
417 template<typename ValueCalculator_, bool UseBinningAnalysis_,
418  typename MHWalkerParams_, typename RngSeedType_,
419  typename IterCountIntType_, typename CountRealType_,
420  typename HistCountIntType_>
421 constexpr bool CDataBase<ValueCalculator_,UseBinningAnalysis_,MHWalkerParams_,RngSeedType_,
422  IterCountIntType_,CountRealType_,HistCountIntType_>::UseBinningAnalysis;
423 
424 
425 
426 
427 
428 
429 // ---------------------------------------------------------
430 
431 
432 
433 
434 
435 
436 
437 
438 
439 
440 
441 
442 namespace tomo_internal {
443 
444 template<typename StatsResultsType, typename = void>
445 struct maybe_show_error_summary_helper {
446  static inline void print(std::ostream & , const StatsResultsType & ) { }
447 };
448 template<typename StatsResultsType>
449 struct maybe_show_error_summary_helper<
450  StatsResultsType,
451  typename std::enable_if<
452  !std::is_same<
453  decltype(((StatsResultsType*)NULL)->errorBarConvergenceSummary()),
454  void
455  >::value
456  >::type
457  >
458 {
459  static inline void print(std::ostream & stream, const StatsResultsType & stats_results)
460  {
461  stream << " error bars: " << stats_results.errorBarConvergenceSummary() << "\n";
462  }
463 };
464 template<typename StatsResultsType>
465 inline void maybe_show_error_summary(std::ostream & stream, const StatsResultsType & stats_results)
466 {
467  maybe_show_error_summary_helper<StatsResultsType>::print(stream, stats_results) ;
468 }
469 
470 
471 template<typename TaskResultType>
472 inline void print_hist_short_bar_summary(std::ostream & stream, int dig_w, std::size_t j,
473  const TaskResultType * task_result, int columns)
474 {
475  const auto acceptance_ratio = task_result->acceptance_ratio;
477  streamstr("#" << std::setw(dig_w) << j << ": "),
478  task_result->stats_results.histogram,
479  Tomographer::Tools::fmts(" [accept ratio = %.2f]", acceptance_ratio),
480  false, columns);
481  if (acceptance_ratio > MHRWAcceptanceRatioRecommendedMax ||
482  acceptance_ratio < MHRWAcceptanceRatioRecommendedMin) {
483  stream << " *** Accept ratio out of recommended bounds ["
485  << "] ! Adapt step size ***\n";
486  }
487  maybe_show_error_summary(stream, task_result->stats_results);
488 }
489 
490 } // namespace tomo_internal
491 
492 
493 
494 
495 
496 
497 
511 template<typename CDataBaseType, typename TaskResultType, typename AggregatedHistogramType>
512 inline void printFinalReport(std::ostream & stream, const CDataBaseType & cdata,
513  const std::vector<TaskResultType*> & task_results,
514  const AggregatedHistogramType & aggregated_histogram,
515  int max_width = 0, bool print_histogram = true)
516 {
517  Tools::ConsoleFormatterHelper h(max_width); // possibly detect terminal width etc.
518 
519  // produce report on runs
520  stream << "\n"
521  << h.centerLine("Final Report of Runs")
522  << h.hrule()
523  ;
524  cdata.printBasicCDataMHRWInfo(stream);
525 
526  int dig_w = (int)std::ceil(std::log10((double)task_results.size()));
527  for (std::size_t j = 0; j < task_results.size(); ++j) {
528  tomo_internal::print_hist_short_bar_summary(stream, dig_w, j, task_results[j], (int)h.columns());
529  }
530  stream << h.hrule()
531  << "\n";
532 
533  if (print_histogram) {
534  // and the final histogram
535  stream << h.centerLine("Final Histogram")
536  << h.hrule();
537  histogramPrettyPrint(stream, aggregated_histogram.final_histogram, (int)h.columns());
538  stream << h.hrule()
539  << "\n";
540  }
541 }
542 
543 
544 
545 
546 
547 
548 
549 
550 
551 
552 } // namespace ValueHistogramTools
553 } // namespace MHRWTasks
554 } // namespace Tomographer
555 
556 
557 #endif
A StatsCollector which builds a histogram of values calculated with a ValueCalculator for each data s...
std::string centerLine(std::string x)
Produce a centered string.
Definition: fmt.h:431
void printFinalReport(std::ostream &stream, const CDataBaseType &cdata, const std::vector< TaskResultType *> &task_results, const AggregatedHistogramType &aggregated_histogram, int max_width=0, bool print_histogram=true)
Produce a final, human-readable report of the whole procedure.
tomo_internal::valuehist_types< CDataBase, UseBinningAnalysis >::ValueStatsCollectorResultType ValueStatsCollectorResultType
The result type of our stats collector.
MHRWTasks::CDataBase< MHWalkerParams_, IterCountIntType_, RngSeedType_ > Base
The MHRWTasks::CDataBase base class.
The parameters of a Histogram.
Definition: histogram.h:67
Base namespace for the Tomographer project.
Definition: densellh.h:45
void histogramShortBarWithInfo(std::ostream &str, std::string head, const HistogramType &hist, std::string tail, bool log_scale=true, int full_max_width=0)
Format the histogram as a one-line bar, with some surrounding info.
Definition: histogram.h:1786
T ceil(T... args)
std::size_t columns() const
The number of character columns (as specified to the constructor or detected)
Definition: fmt.h:423
An MHWalkerParams type which just stores a step size.
Definition: mhrw.h:93
Provide appropriate operator new() definitions for a structure which has a member of the given stored...
STL namespace.
constexpr const double MHRWAcceptanceRatioRecommendedMax
Maximal recommended acceptance ratio.
Definition: mhrw.h:83
MHRWParams< MHWalkerParams, IterCountIntType > MHRWParamsType
Type for the parameters of the random walk.
Multiprocessing tasks interface (see Multiprocessing Task Interfaces) for parallel Metropolis-Hasting...
Base::RngSeedType RngSeedType
Type of the seed for the pseudo-random number generator.
constexpr const double MHRWAcceptanceRatioRecommendedMin
Minimal recommended acceptance ratio.
Definition: mhrw.h:81
T log10(T... args)
Constant data structure for MH random walk tasks with a value histogram stats collector.
T setw(T... args)
Data needed to be accessible to the working code.
Definition: mhrwtasks.h:133
Traits-like class for ValueHistogramWithBinningMHRWStatsCollector.
void histogramPrettyPrint(std::ostream &str, const HistogramType &histogram, int max_width=0)
pretty-print the given histogram.
Definition: histogram.h:1683
Minimal tool for formatting console stuff with fixed line width.
Definition: fmt.h:407
Collect a histogram of values from a MH random walk, with binning analysis.
HistCountIntType_ HistCountIntType
The integer counting type in our underlying raw histogram type.
RngSeedType_ RngSeedType
Type used to specify the seed of the random number generator.
Definition: mhrwtasks.h:144
AggregatedHistogramType aggregateResultHistograms(const std::vector< TaskResultType *> &task_result_list)
Convenience function for aggregating histograms resulting from value-histogram tasks.
ValueHistogramWithBinningMHRWStatsCollector< typename tomo_internal::valuehist_types< CDataBase, true >::BinningMHRWStatsCollectorParams, LoggerType > createValueStatsCollector(LoggerType &logger) const
Create the stats collector (with binning analysis)
Stores a histogram.
Definition: histogram.h:213
ValueHistogramMHRWStatsCollector< ValueCalculator, LoggerType, HistogramType > createValueStatsCollector(LoggerType &logger) const
Create the stats collector (without binning analysis)
ValueCalculator_ ValueCalculator
The class which calculates the value we are collecting a histogram of (ValueCalculator Interface comp...
tomo_internal::valuehist_types< CDataBase, UseBinningAnalysis >::HistogramParams HistogramParams
The appropriate parameters type for the histogram reported by the task.
Some C++ utilities, with a tad of C++11 tricks.
T move(T... args)
HistogramType_ HistogramType
The histogram type corresponding to the result of a task.
Definition: histogram.h:1022
Base::IterCountIntType IterCountIntType
The integer type which serves to count the number of iterations (see MHRWParams)
Managing the need for specific overrides to operator new() for some types (especially Eigen types) ...
const ValueCalculator valcalc
The value calculator instance.
T size(T... args)
std::string fmts(const char *fmt,...)
printf- format to a std::string
Definition: fmt.h:128
STL class.
Base::MHWalkerParams MHWalkerParams
The MHWalkerParams required for our MHWalker (for instance a MHWalkerParamsStepSize) ...
VarValueDecoder< T >::RetType value(const Var &var)
Access the value of the given variable, as a C++ type.
Definition: ezmatio.h:878
tomo_internal::valuehist_types< CDataBase, UseBinningAnalysis >::HistogramType HistogramType
The histogram type reported by the task.
Stores the result of the value histogram stats collector (version without binning analysis) ...
const HistogramParams histogram_params
The parameters of the histogram that we are collecting.
tomo_internal::valuehist_types< CDataBase, UseBinningAnalysis >::MHRWStatsResultsBaseType MHRWStatsResultsBaseType
Stores result of the stats collector. May serve as base class for your own MHRWStatsResults class...
Definitions for MHRWStatsCollector Interface&#39;s.
IterCountIntType_ IterCountIntType
Type used to count the number of iterations.
Definition: mhrwtasks.h:136
#define streamstr(tokens)
Utility macro to format stream tokens to a std::string.
Definition: fmt.h:149
MHWalkerParams_ MHWalkerParams
Type used to specify the step size.
Definition: mhrwtasks.h:138
STL class.
Histogram aggregator, if each individual histogram already has error bars.
Definition: histogram.h:1159
Histogram aggregator, if each histogram doesn&#39;t have error bars.
Definition: histogram.h:1012
const Tools::StoreIfEnabled< int, UseBinningAnalysis > binningNumLevels
The number of levels in the binning analysis (only if we are using a binning analysis) ...
Utilities for logging messages.
CountRealType_ CountRealType
The real type which serves to average histogram counts (typically double)