Tomographer  v3.0
Tomographer C++ Framework Documentation
mhrw_valuehist_tasks.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_TASKS_H
29 #define TOMOGRAPHER_MHRW_VALUEHIST_TASKS_H
30 
31 #include <iostream>
32 #include <iomanip>
33 
35 #include <tomographer/tools/cxxutil.h> // tomographer_assert()
38 #include <tomographer/mhrwtasks.h>
39 
40 #include <boost/math/constants/constants.hpp>
41 
42 
51 namespace Tomographer {
52 namespace MHRWTasks {
53 namespace ValueHistogramTasks {
54 
55 
56 namespace tomo_internal {
57 template<typename CDataBaseType, bool UseBinningAnalysis>
58 struct histogram_types {// version WITHOUT binning analysis:
59  typedef UniformBinsHistogram<typename CDataBaseType::ValueCalculator::ValueType,
60  typename CDataBaseType::HistCountIntType> HistogramType;
62  typedef HistogramType MHRWStatsCollectorResultType;
63  typedef typename HistogramType::Params HistogramParams;
64 };
65 template<typename CDataBaseType>
66 struct histogram_types<CDataBaseType, true> {// version WITH binning analysis:
69  typename CDataBaseType::ValueCalculator, typename CDataBaseType::HistCountIntType,
70  typename CDataBaseType::CountRealType, Eigen::Dynamic, Eigen::Dynamic
71  > BinningMHRWStatsCollectorParams;
72  //
73  typedef typename BinningMHRWStatsCollectorParams::Result MHRWStatsCollectorResultType;
74  typedef typename BinningMHRWStatsCollectorParams::HistogramType HistogramType;
75  typedef typename BinningMHRWStatsCollectorParams::HistogramParams HistogramParams;
76 };
77 } // namespace tomo_internal
78 
79 
80 
81 
82 // ------------------------------------------------
83 
84 
85 
86 
87 namespace tomo_internal {
88 template<typename HistogramType>
89 void print_hist_short_bar_with_accept_info(std::ostream & str, int dig_w, int j, const HistogramType & hist,
90  double acceptance_ratio, int columns)
91 {
93  streamstr("#" << std::setw(dig_w) << j << ": "),
94  hist,
95  Tomographer::Tools::fmts(" [accept ratio = %.2f]", acceptance_ratio),
96  false, columns);
97  if (acceptance_ratio > MHRWAcceptanceRatioRecommendedMax ||
98  acceptance_ratio < MHRWAcceptanceRatioRecommendedMin) {
99  str << " *** Accept ratio out of recommended bounds ["<<MHRWAcceptanceRatioRecommendedMin
100  <<", "<<MHRWAcceptanceRatioRecommendedMax<<"] ! Adapt step size ***\n";
101  }
102 }
103 } // namespace tomo_internal
104 
105 
106 
107 
108 
109 
110 
111 
133 template<typename CDataBaseType_, typename LoggerType_>
135  : public virtual Tools::NeedOwnOperatorNew<
136  AveragedHistogram<UniformBinsHistogram<typename CDataBaseType_::HistogramType::Scalar,
137  typename CDataBaseType_::CountRealType>,
138  typename CDataBaseType_::CountRealType>
139  >::ProviderType
140 {
142  typedef CDataBaseType_ CDataBaseType;
144  typedef typename CDataBaseType::ValueCalculator ValueCalculator;
146  typedef typename CDataBaseType::CountRealType CountRealType;
148  typedef typename CDataBaseType::IterCountIntType IterCountIntType;
150  typedef typename CDataBaseType::StepRealType StepRealType;
152  typedef LoggerType_ LoggerType;
153 
158  typedef typename CDataBaseType::HistogramType HistogramType;
160  typedef typename CDataBaseType::HistogramParams HistogramParams;
174 
177  typedef HistogramType MHRWStatsCollectorResultType;
178 
179  TOMO_STATIC_ASSERT_EXPR( CDataBaseType::UseBinningAnalysis == false ) ;
180 
190  : public MHRandomWalkTaskResult<MHRWStatsCollectorResultType,IterCountIntType,StepRealType>,
191  public virtual Tools::NeedOwnOperatorNew<ScaledHistogramType>::ProviderType
192  {
194 
195  RunTaskResult()
196  : Base(), histogram()
197  {
198  }
199 
200  template<typename BaseType, typename ScaledHistogramTypeRef>
201  RunTaskResult(BaseType&& b, ScaledHistogramTypeRef&& histogram_)
202  : Base(std::forward<BaseType>(b)), histogram(histogram_)
203  {
204  }
205 
214  const ScaledHistogramType histogram;
215  };
216 
218 
219 
224  ResultsCollectorSimple(LoggerType & logger_)
225  : _finalized(false), _finalhistogram(HistogramParams()),
226  _collected_runtaskresults(),
227  _llogger("MHRWTasks::ValueHistogramTasks::ResultsCollectorSimple", logger_)
228  {
229  }
230 
232  {
233  for (std::size_t j = 0; j < _collected_runtaskresults.size(); ++j) {
234  if (_collected_runtaskresults[j] != NULL) {
235  delete _collected_runtaskresults[j];
236  }
237  }
238  }
239 
246  inline bool isFinalized() const { return _finalized; }
247 
258  inline FinalHistogramType finalHistogram() const {
259  tomographer_assert(isFinalized() && "You may only call finalHistogram() after the runs have been finalized.");
260  return _finalhistogram;
261  }
262 
268  inline std::size_t numTasks() const {
269  tomographer_assert(isFinalized() && "You may only call numTasks() after the runs have been finalized.");
270  return _collected_runtaskresults.size();
271  }
272 
281  inline const RunTaskResultList & collectedRunTaskResults() const {
282  tomographer_assert(isFinalized() && "You may only call collectedRunTaskResults() after the runs have been finalized.");
283  return _collected_runtaskresults;
284  }
285 
297  inline const RunTaskResult * collectedRunTaskResult(std::size_t task_no) const {
298  tomographer_assert(isFinalized() && "You may only call collectedRunTaskResult(std::size_t) after the runs have been finalized.");
299  tomographer_assert(task_no < _collected_runtaskresults.size());
300  return _collected_runtaskresults[task_no];
301  }
302 
315  template<typename RealType = double>
316  inline void printHistogramCsv(std::ostream & stream, std::string sep = "\t", std::string linesep = "\n", int precision = 10)
317  {
318  // ### Q: why the RealType template parameter??
319  stream << "Value" << sep << "Counts" << sep << "Error" << linesep
320  << std::scientific << std::setprecision(precision);
321  for (int kk = 0; kk < _finalhistogram.bins.size(); ++kk) {
322  stream << RealType(_finalhistogram.params.binLowerValue(kk)) << sep
323  << RealType(_finalhistogram.bins(kk)) << sep
324  << RealType(_finalhistogram.delta(kk)) << linesep;
325  }
326  }
327 
342  inline void printFinalReport(std::ostream & str, const CDataBaseType & cdata,
343  int max_width = 0, bool print_histogram = true)
344  {
345  Tools::ConsoleFormatterHelper h(max_width); // possibly detect terminal width etc.
346 
347  const auto& res = *this;
348 
349  const RunTaskResultList & collresults = res.collectedRunTaskResults();
350  const FinalHistogramType finalhistogram = res.finalHistogram();
351  str << "\n"
352  << h.centerLine("Final Report of Runs")
353  << h.hrule()
354  ;
355  cdata.printBasicCDataMHRWInfo(str);
356  int dig_w = (int)std::ceil(std::log10(res.numTasks()));
357  for (std::size_t j = 0; j < res.numTasks(); ++j) {
358  tomo_internal::print_hist_short_bar_with_accept_info(str, dig_w, j, collresults[j]->histogram,
359  collresults[j]->acceptance_ratio, h.columns());
360  }
361  str << h.hrule()
362  << "\n";
363 
364  if (print_histogram) {
365  // and the final histogram
366  str << h.centerLine("Final Histogram")
367  << h.hrule();
368  histogramPrettyPrint(str, finalhistogram, h.columns());
369  str << h.hrule()
370  << "\n";
371  }
372  }
373 
374 
375 
376 private:
377  bool _finalized;
378  FinalHistogramType _finalhistogram;
379 
380  RunTaskResultList _collected_runtaskresults;
381 
383 
384 public:
385 
386  // these functions will be called by the task manager/dispatcher
387 
389  template<typename Cnt, typename CData>
390  inline void init(Cnt num_total_runs, Cnt /*n_chunk*/, const CData * pcdata)
391  {
392  tomographer_assert(!isFinalized() && "init() called after results have been finalized!");
393 
394  _collected_runtaskresults.resize(num_total_runs, NULL);
395  _finalhistogram.reset(pcdata->histogram_params);
396  }
398  template<typename Cnt, typename TaskResultType, typename CData>
399  inline void collectResult(Cnt task_no, TaskResultType&& taskresult, const CData * /*pcdata*/)
400  {
401  tomographer_assert(!isFinalized() && "collectResult() called after results have been finalized!");
402 
403  auto logger = _llogger.subLogger(TOMO_ORIGIN);
404  logger.debug([&](std::ostream & str) {
405  str << "Got task result. Histogram is:\n" << taskresult.stats_collector_result.prettyPrint();
406  });
407 
408  // Scale this histogram using the number of samples, so that the scaling of the
409  // histogram coincides to that used by the binning analysis. This so we can compare
410  // those histograms obtained by the two procedures.
411  //
412  // NOTE: This does not normalize the histogram to unit area. Use \ref
413  // UniformBinsHistogram::normalized() for that.
414  //
415  ScaledHistogramType thishistogram = taskresult.stats_collector_result;
416  typename ScaledHistogramType::CountType numsamples =
417  thishistogram.bins.sum() + thishistogram.off_chart;
418  thishistogram.bins /= numsamples;
419  thishistogram.off_chart /= numsamples;
420 
421  _finalhistogram.addHistogram(thishistogram);
422  _collected_runtaskresults[task_no]
423  = new RunTaskResult(std::forward<TaskResultType>(taskresult), std::move(thishistogram));
424  }
431  template<typename Cnt, typename CData>
432  inline void runsFinished(Cnt, const CData *)
433  {
434  tomographer_assert(!isFinalized() && "runsFinished() called after results have been finalized!");
435 
436  _finalized = true;
437  _finalhistogram.finalize();
438  }
439 
440 }; // struct ResultsCollectorSimple
441 
442 
443 
444 
445 
477 template<typename CDataBaseType_, typename LoggerType_>
479  : public virtual Tools::NeedOwnOperatorNew<
480  UniformBinsHistogram<typename CDataBaseType_::HistogramType::Scalar,
481  typename CDataBaseType_::CountRealType>
482  >::ProviderType
483 {
485  typedef CDataBaseType_ CDataBaseType;
487  typedef typename CDataBaseType::ValueCalculator ValueCalculator;
489  typedef typename CDataBaseType::CountRealType CountRealType;
491  typedef typename CDataBaseType::IterCountIntType IterCountIntType;
493  typedef typename CDataBaseType::StepRealType StepRealType;
495  typedef LoggerType_ LoggerType;
496 
502  typedef typename tomo_internal::histogram_types<CDataBaseType_,true>::BinningMHRWStatsCollectorParams
504 
509  typedef typename BinningMHRWStatsCollectorParams::BinningAnalysisParamsType BinningAnalysisParamsType;
510 
517  typedef typename BinningMHRWStatsCollectorParams::Result MHRWStatsCollectorResultType;
518 
523  typedef typename CDataBaseType::HistogramType HistogramType;
528  typedef typename CDataBaseType::HistogramParams HistogramParams;
529 
532 
543 
553 
554 
555  TOMO_STATIC_ASSERT_EXPR( CDataBaseType::UseBinningAnalysis ) ;
556 
562  : _finalized(false), _finalhistogram(), _simplefinalhistogram(),
563  _collected_runtaskresults(),
564  _llogger("MHRWTasks::ValueHistogramTasks::ResultsCollectorWithBinningAnalysis", logger_)
565  {
566  }
567 
569  {
570  for (std::size_t j = 0; j < _collected_runtaskresults.size(); ++j) {
571  if (_collected_runtaskresults[j] != NULL) {
572  delete _collected_runtaskresults[j];
573  }
574  }
575  }
576 
583  inline bool isFinalized() const { return _finalized; }
584 
595  inline FinalHistogramType finalHistogram() const {
596  tomographer_assert(isFinalized() && "You may only call finalHistogram() after the runs have been finalized.");
597  return _finalhistogram;
598  }
599 
612  inline SimpleFinalHistogramType simpleFinalHistogram() const {
613  tomographer_assert(isFinalized() && "You may only call simpleFinalHistogram() after the runs have been finalized.");
614  return _simplefinalhistogram;
615  }
616 
622  inline std::size_t numTasks() const {
623  tomographer_assert(isFinalized() && "You may only call numTasks() after the runs have been finalized.");
624  return _collected_runtaskresults.size();
625  }
626 
635  inline const RunTaskResultList & collectedRunTaskResults() const {
636  tomographer_assert(isFinalized() && "You may only call collectedRunTaskResults() after the runs have been finalized.");
637  return _collected_runtaskresults;
638  }
639 
651  inline const RunTaskResult * collectedRunTaskResult(std::size_t task_no) const {
652  tomographer_assert(isFinalized() && "You may only call collectedRunTaskResult(std::size_t) after the runs have been finalized.");
653  tomographer_assert(task_no < _collected_runtaskresults.size());
654  return _collected_runtaskresults[task_no];
655  }
656 
657 
671  template<typename RealType = double>
672  inline void printHistogramCsv(std::ostream & stream, std::string sep = "\t", std::string linesep = "\n",
673  int precision = 10)
674  {
675  // ### Q: why the RealType template parameter??
676  stream << "Value" << sep << "Counts" << sep << "Error" << sep << "SimpleError" << linesep
677  << std::scientific << std::setprecision(precision);
678  for (int kk = 0; kk < _finalhistogram.bins.size(); ++kk) {
679  stream << RealType(_finalhistogram.params.binLowerValue(kk)) << sep
680  << RealType(_finalhistogram.bins(kk)) << sep
681  << RealType(_finalhistogram.delta(kk)) << sep
682  << RealType(_simplefinalhistogram.delta(kk)) << linesep;
683  }
684  }
685 
699  inline void printFinalReport(std::ostream & str, const CDataBaseType & cdata,
700  int max_width = 0, bool print_histogram = true)
701  {
702  Tools::ConsoleFormatterHelper h(max_width); // possibly detect terminal width etc.
703 
704  const auto& res = *this;
705 
706  // produce report on runs
707  const RunTaskResultList & collresults = res.collectedRunTaskResults();
708  const FinalHistogramType finalhistogram = res.finalHistogram();
709  str << "\n"
710  << h.centerLine("Final Report of Runs")
711  << h.hrule()
712  ;
713  cdata.printBasicCDataMHRWInfo(str);
714  int dig_w = (int)std::ceil(std::log10(res.numTasks()));
715  for (std::size_t j = 0; j < res.numTasks(); ++j) {
716  const auto& stats_coll_result = collresults[j]->stats_collector_result;
717 
718  tomo_internal::print_hist_short_bar_with_accept_info(str, dig_w, j, stats_coll_result.hist,
719  collresults[j]->acceptance_ratio, h.columns());
720 
721  // error bars stats:
722  const int nbins = stats_coll_result.converged_status.size();
723  const int n_conv = stats_coll_result.converged_status
724  .cwiseEqual(BinningAnalysisParamsType::CONVERGED).count();
725  Eigen::ArrayXi unkn_arr = (stats_coll_result.converged_status
726  .cwiseEqual(BinningAnalysisParamsType::UNKNOWN_CONVERGENCE))
727  .template cast<int>();
728  // little heuristic to see whether the "unknown" converged error bars are isolated or not
729  const int n_unknown = unkn_arr.count();
730  const int n_unknown_followingotherunknown
731  = unkn_arr.segment(0,nbins-1).cwiseProduct(unkn_arr.segment(1,nbins-1)).count();
732  const int n_unknown_isolated = n_unknown - n_unknown_followingotherunknown;
733  const int n_notconv = stats_coll_result.converged_status
734  .cwiseEqual(BinningAnalysisParamsType::NOT_CONVERGED).count();
735  str << " error bars: " << n_conv << " converged / "
736  << n_unknown << " maybe (" << n_unknown_isolated << " isolated) / "
737  << n_notconv << " not converged\n";
738  }
739  str << h.hrule()
740  << "\n";
741 
742  if (print_histogram) {
743  // and the final histogram
744  str << h.centerLine("Final Histogram")
745  << h.hrule();
746  histogramPrettyPrint(str, finalhistogram, h.columns());
747  str << h.hrule()
748  << "\n";
749  }
750  }
751 
752 
753 private:
754  bool _finalized;
755  FinalHistogramType _finalhistogram;
756  SimpleFinalHistogramType _simplefinalhistogram;
757 
758  RunTaskResultList _collected_runtaskresults;
759 
761 
762 
763 public:
764 
766  template<typename Cnt, typename CData>
767  inline void init(Cnt num_total_runs, Cnt /*n_chunk*/, const CData * pcdata)
768  {
769  tomographer_assert(!isFinalized() && "init() called after results have been finalized!");
770 
771  _collected_runtaskresults.resize(num_total_runs, NULL);
772  _finalhistogram.reset(pcdata->histogram_params);
773  _simplefinalhistogram.reset(pcdata->histogram_params);
774  }
775 
777  template<typename Cnt, typename TaskResultType, typename CData>
778  inline void collectResult(Cnt task_no, TaskResultType && taskresult, const CData *)
779  {
780  tomographer_assert(!isFinalized() && "collectResult() called after results have been finalized!");
781 
782  auto logger = _llogger.subLogger(TOMO_ORIGIN);
783 
784  auto stats_coll_result = taskresult.stats_collector_result;
785 
786  logger.debug([&](std::ostream & str) {
787  str << "(). Got task result. Histogram (w/ error bars from binning analysis):\n"
788  << stats_coll_result.hist.prettyPrint();
789  });
790 
791  if ((stats_coll_result.converged_status !=
792  Eigen::ArrayXi::Constant(stats_coll_result.hist.numBins(), BinningAnalysisParamsType::CONVERGED)).any()) {
793  logger.debug([&,this](std::ostream & str) {
794  str << "Error bars have not converged! The error bars at different binning levels are:\n"
795  << stats_coll_result.error_levels << "\n"
796  << "\t-> convergence analysis: \n";
797  for (std::size_t k = 0; k < stats_coll_result.hist.numBins(); ++k) {
798  str << "\t val[" << std::setw(3) << k << "] = "
799  << std::setw(12) << stats_coll_result.hist.bins(k)
800  << " +- " << std::setw(12) << stats_coll_result.hist.delta(k);
801  if (stats_coll_result.converged_status(k) == BinningAnalysisParamsType::CONVERGED) {
802  str << " [CONVERGED]";
803  } else if (stats_coll_result.converged_status(k) == BinningAnalysisParamsType::NOT_CONVERGED) {
804  str << " [NOT CONVERGED]";
805  } else if (stats_coll_result.converged_status(k) == BinningAnalysisParamsType::UNKNOWN_CONVERGENCE) {
806  str << " [UNKNOWN]";
807  } else {
808  str << " [UNKNOWN CONVERGENCE STATUS: " << stats_coll_result.converged_status(k) << "]";
809  }
810  str << "\n";
811  }
812  });
813  }
814 
815  // because stats_coll_result is a histogram WITH error bars, addHistogram
816  // will do the right thing and take them into account.
817  _finalhistogram.addHistogram(stats_coll_result.hist);
818 
819  logger.debug("added histogram.");
820 
821  // this one is declared for histograms WITHOUT error bars (SimpleHistogramType is a
822  // UniformBinsHistogram), so it will just ignore the error bars.
823  logger.debug([&](std::ostream & str) {
824  str << "Simple histogram is:\n";
825  histogramPrettyPrint<SimpleScaledHistogramType>(str, stats_coll_result.hist);
826  });
827  _simplefinalhistogram.addHistogram(stats_coll_result.hist);
828 
829  _collected_runtaskresults[task_no] = new RunTaskResult(std::move(taskresult));
830 
831  logger.debug("done.");
832  }
833 
835  template<typename Cnt, typename CData>
836  inline void runsFinished(Cnt, const CData *)
837  {
838  tomographer_assert(!isFinalized() && "runs_finished() called after results have been finalized!");
839 
840  _finalized = true;
841  _finalhistogram.finalize();
842  _simplefinalhistogram.finalize();
843  }
844 
845 };
846 
847 
848 
849 
850 
851 
852 
853 // ------------------------------------------------
854 
855 
856 namespace tomo_internal {
857 template<typename CDataBaseType, typename LoggerType, bool UseBinningAnalysis>
858 struct ResultsCollectorTypeHelper {
860 };
861 template<typename CDataBaseType, typename LoggerType>
862 struct ResultsCollectorTypeHelper<CDataBaseType, LoggerType, true> {
864 };
865 } // namespace tomo_internal
866 
867 
868 
869 
937 template<typename ValueCalculator_, bool UseBinningAnalysis_ = true,
938  typename IterCountIntType_ = int, typename StepRealType_ = double,
939  typename CountRealType_ = double, typename HistCountIntType_ = IterCountIntType_>
940 struct CDataBase
941  : public MHRWTasks::CDataBase<IterCountIntType_, StepRealType_>,
942  public virtual Tools::NeedOwnOperatorNew<ValueCalculator_>::ProviderType
943 {
946 
951 
953  typedef HistCountIntType_ HistCountIntType;
954 
956  typedef ValueCalculator_ ValueCalculator;
958  typedef CountRealType_ CountRealType;
959 
961  static constexpr bool UseBinningAnalysis = UseBinningAnalysis_;
962 
975 
990 
994 
997 
998 
1000  TOMOGRAPHER_ENABLED_IF(!UseBinningAnalysis)
1001  CDataBase(const ValueCalculator & valcalc_, HistogramParams histogram_params_,
1002  MHRWParamsType p, int base_seed = 0)
1003  : Base(std::move(p), base_seed), valcalc(valcalc_), histogram_params(histogram_params_),
1004  binningNumLevels()
1005  {
1006  }
1007 
1009  TOMOGRAPHER_ENABLED_IF(UseBinningAnalysis)
1010  CDataBase(const ValueCalculator & valcalc_, HistogramParams histogram_params_, int binning_num_levels_,
1011  MHRWParamsType p, int base_seed = 0)
1012  : Base(std::move(p), base_seed), valcalc(valcalc_), histogram_params(histogram_params_),
1013  binningNumLevels(binning_num_levels_)
1014  {
1015  }
1016 
1023 
1024 
1030  template<typename LoggerType, TOMOGRAPHER_ENABLED_IF_TMPL(!UseBinningAnalysis)>
1032  createStatsCollector(LoggerType & logger) const
1033  {
1035  histogram_params,
1036  valcalc,
1037  logger
1038  );
1039  }
1040 
1046  template<typename LoggerType, TOMOGRAPHER_ENABLED_IF_TMPL(UseBinningAnalysis)>
1048  typename tomo_internal::histogram_types<CDataBase, true>::BinningMHRWStatsCollectorParams,
1049  LoggerType>
1050  createStatsCollector(LoggerType & logger) const
1051  {
1052  typedef typename tomo_internal::histogram_types<CDataBase, true>::BinningMHRWStatsCollectorParams
1053  BinningMHRWStatsCollectorParams;
1054 
1056  histogram_params,
1057  valcalc,
1058  binningNumLevels.value,
1059  logger
1060  );
1061  }
1062 
1078  template<typename LoggerType>
1080  typedef
1081 #ifndef TOMOGRAPHER_PARSED_BY_DOXYGEN
1082  typename
1083  tomo_internal::ResultsCollectorTypeHelper<CDataBase<ValueCalculator,UseBinningAnalysis,IterCountIntType,StepRealType,CountRealType,HistCountIntType>,
1084  LoggerType, UseBinningAnalysis>::type
1085 #else
1086  [...] // parsed by doxygen -- make this more readable
1087 #endif
1088  Type;
1089 
1090  typedef typename Type::RunTaskResult RunTaskResultType;
1091  };
1092 };
1093 // define static members:
1094 template<typename ValueCalculator_, bool UseBinningAnalysis_,
1095  typename IterCountIntType_, typename StepRealType_,
1096  typename CountRealType_, typename HistCountIntType_>
1098 
1099 
1100 
1101 
1102 
1103 
1104 
1105 
1106 
1107 } // namespace ValueHistogramTasks
1108 } // namespace MHRWTasks
1109 } // namespace Tomographer
1110 
1111 
1112 #endif
A StatsCollector which builds a histogram of values calculated with a ValueCalculator for each data s...
Eigen::Array< CountType, Eigen::Dynamic, 1 > bins
The counts for each bin.
Definition: histogram.h:233
#define TOMO_STATIC_ASSERT_EXPR(...)
Tool for static assertions without message.
Definition: cxxutil.h:62
const RunTaskResultList & collectedRunTaskResults() const
Return a list of the resulting report of each run task.
std::string centerLine(std::string x)
Produce a centered string.
Definition: fmt.h:428
void addHistogram(const HistogramType &histogram)
Add a new histogram in the data series.
Definition: histogram.h:751
CDataBaseType::StepRealType StepRealType
The real type which serves to describe the step size of the random walk (typically double) ...
std::size_t numTasks() const
Return the number of tasks that were run.
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:1329
void collectResult(Cnt task_no, TaskResultType &&taskresult, const CData *)
In compliance with ResultsCollector Interface.
LoggerType_ LoggerType
The logger type we can send messages to.
T ceil(T... args)
HistogramType MHRWStatsCollectorResultType
The result type of our ValueHistogramMHRWStatsCollector.
CountType_ CountType
The type that serves to count how many hits in each bin.
Definition: histogram.h:222
AveragedHistogram< ScaledHistogramType, CountRealType > FinalHistogramType
tomo_internal::histogram_types< CDataBaseType_, true >::BinningMHRWStatsCollectorParams BinningMHRWStatsCollectorParams
The parameters for the relevant ValueHistogramWithBinningMHRWStatsCollector.
const Tools::StoreIfEnabled< int, UseBinningAnalysis > binningNumLevels
The number of levels in the binning analysis (only if we are using a binning analysis) ...
const double MHRWAcceptanceRatioRecommendedMin
Minimal recommended acceptance ratio.
Definition: mhrw.h:195
MHRWParams< IterCountIntType, StepRealType > MHRWParamsType
Type for the parameters of the random walk.
ValueCalculator_ ValueCalculator
The class which calculates the value we are collecting a histogram of (ValueCalculator Interface comp...
Provide appropriate operator new() definitions for a structure which has a member of the given stored...
tomo_internal::histogram_types< CDataBase, UseBinningAnalysis >::MHRWStatsCollectorResultType MHRWStatsCollectorResultType
The result type of our stats collector.
ValueHistogramWithBinningMHRWStatsCollector< typename tomo_internal::histogram_types< CDataBase, true >::BinningMHRWStatsCollectorParams, LoggerType > createStatsCollector(LoggerType &logger) const
Create the stats collector (with binning analysis)
STL namespace.
MHRWTasks::CDataBase< IterCountIntType_, StepRealType_ > Base
The MHRWTasks::CDataBase base class.
Multiprocessing tasks interface (see Multiprocessing Task Interfaces) for parallel Metropolis-Hasting...
T log10(T... args)
#define TOMO_ORIGIN
Use this as argument for a Tomographer::Logger::LocalLogger constructor .
Definition: loggers.h:1659
std::vector< RunTaskResult * > RunTaskResultList
A list which will store the result of each task.
void runsFinished(Cnt, const CData *)
In compliance with ResultsCollector Interface — finalizes the results.
void init(Cnt num_total_runs, Cnt, const CData *pcdata)
In compliance with ResultsCollector Interface.
T setw(T... args)
T resize(T... args)
STL class.
FinalHistogramType finalHistogram() const
The final histogram, with error bars.
BinningMHRWStatsCollectorParams::Result MHRWStatsCollectorResultType
The result type of our stats collector.
LocalLogger< LocalLogger< BaseLoggerType > > subLogger(const std::string &new_prefix)
Create a sub-logger.
Definition: loggers.h:1896
CDataBaseType_ CDataBaseType
The structure which hold the constant shared data describing what we have to do.
Data needed to be accessible to the working code.
Definition: mhrwtasks.h:64
CDataBaseType::IterCountIntType IterCountIntType
The integer type which serves to count the number of iterations (see MHRWParams)
const HistogramParams histogram_params
The parameters of the histogram that we are collecting.
ValueHistogramMHRWStatsCollector< ValueCalculator, LoggerType, HistogramType > createStatsCollector(LoggerType &logger) const
Create the stats collector (without binning analysis)
Traits-like class for ValueHistogramWithBinningMHRWStatsCollector.
MHRandomWalkTaskResult< MHRWStatsCollectorResultType, IterCountIntType, StepRealType > RunTaskResult
Stores information about the result of a task run.
void printFinalReport(std::ostream &str, const CDataBaseType &cdata, int max_width=0, bool print_histogram=true)
Produce a final, human-readable report of the whole procedure.
void histogramPrettyPrint(std::ostream &str, const HistogramType &histogram, int max_width=0)
pretty-print the given histogram.
Definition: histogram.h:1226
Constant data structure for MH random walk tasks with a value histogram stats collector.
Minimal tool for formatting console stuff with fixed line width.
Definition: fmt.h:404
Collect a histogram of values from a MH random walk, with binning analysis.
const double MHRWAcceptanceRatioRecommendedMax
Maximal recommended acceptance ratio.
Definition: mhrw.h:197
CDataBaseType::ValueCalculator ValueCalculator
The class which calculates the value we are collecting a histogram of (ValueCalculator Interface comp...
const ValueCalculator valcalc
The value calculator instance.
CDataBaseType::ValueCalculator ValueCalculator
The class which calculates the value we are collecting a histogram of (ValueCalculator Interface comp...
Base::StepRealType StepRealType
The real type which serves to describe the step size of the random walk (typically double) ...
AveragedHistogram< HistogramType, CountRealType > FinalHistogramType
The final histogram, properly averaged.
void printFinalReport(std::ostream &str, const CDataBaseType &cdata, int max_width=0, bool print_histogram=true)
Produce a final, human-readable report of the whole procedure.
Some C++ utilities, with a tad of C++11 tricks.
IterCountIntType_ IterCountIntType
Type used to count the number of iterations.
Definition: mhrwtasks.h:79
CDataBaseType::HistogramParams HistogramParams
The parameters type used to describe our histogram range and number of bins.
CDataBaseType::CountRealType CountRealType
The real type which serves to average histogram counts (typically double)
T move(T... args)
tomo_internal::histogram_types< CDataBase, UseBinningAnalysis >::HistogramParams HistogramParams
The appropriate parameters type for the histogram reported by the task.
void reset(const Params &params_)
Resets the data and sets new params.
Definition: histogram.h:713
void init(Cnt num_total_runs, Cnt, const CData *pcdata)
In compliance with ResultsCollector Interface.
T scientific(T... args)
tomo_internal::histogram_types< CDataBase, UseBinningAnalysis >::HistogramType HistogramType
The histogram type reported by the task.
StepRealType_ StepRealType
Type used to specify the step size.
Definition: mhrwtasks.h:81
CDataBaseType::HistogramType HistogramType
The histogram type corresponding to the result of a task.
void collectResult(Cnt task_no, TaskResultType &&taskresult, const CData *)
In compliance with ResultsCollector Interface.
Managing the need for specific overrides to operator new() for some types (especially Eigen types) ...
HistCountIntType_ HistCountIntType
The integer counting type in our underlying raw histogram type.
UniformBinsHistogram< typename HistogramType::Scalar, CountRealType > ScaledHistogramType
The type of the histogram resulting from a single task, but scaled so that each bin value corresponds...
T size(T... args)
CDataBaseType::StepRealType StepRealType
The real type which serves to describe the step size of the random walk (typically double) ...
const RunTaskResultList & collectedRunTaskResults() const
Return a list of the resulting report of each run task.
std::string fmts(const char *fmt,...)
printf- format to a std::string
Definition: fmt.h:125
CDataBaseType::HistogramParams HistogramParams
The histogram parameters type reported by each task.
CDataBaseType::IterCountIntType IterCountIntType
The integer type which serves to count the number of iterations (see MHRWParams)
BinningMHRWStatsCollectorParams::BinningAnalysisParamsType BinningAnalysisParamsType
The parameters for the corresponding BinningAnalysis type.
UniformBinsHistogramParams< Scalar_ > Params
The type for specifying parameters of this histogram (limits, number of bins)
Definition: histogram.h:228
void printHistogramCsv(std::ostream &stream, std::string sep="\, std::string linesep="\", int precision=10)
Produce a comma-separated-value (CSV) representation of the final histogram.
UniformBinsHistogram< typename HistogramType::Scalar, CountRealType > SimpleScaledHistogramType
The "simple" histogram, as if without binning analysis.
std::size_t numTasks() const
Return the number of tasks that were run.
The parameters of a UniformBinsHistogram.
Definition: histogram.h:68
void printHistogramCsv(std::ostream &stream, std::string sep="\, std::string linesep="\", int precision=10)
Produce a comma-separated-value (CSV) representation of the final histogram.
Results collector, if no binning analysis is being used.
Definitions for MHRWStatsCollector Interface&#39;s.
const RunTaskResult * collectedRunTaskResult(std::size_t task_no) const
Return a list of the resulting report of one specific run task.
#define streamstr(tokens)
Utility macro to format stream tokens to a std::string.
Definition: fmt.h:146
CountType off_chart
The number of points that fell outside of the given range.
Definition: histogram.h:235
CDataBaseType::CountRealType CountRealType
The real type which serves to average histogram counts (typically double)
void runsFinished(Cnt, const CData *)
In compliance with ResultsCollector Interface.
AveragedHistogram< SimpleScaledHistogramType, double > SimpleFinalHistogramType
Properly averaged "simple" histogram, with naive statistical standard deviation error bars from the s...
Stores a histogram.
Definition: histogram.h:211
bool isFinalized() const
Returns TRUE after all runs have finished and results processed.
bool isFinalized() const
Returns TRUE after all runs have finished and results processed.
T setprecision(T... args)
STL class.
const RunTaskResult * collectedRunTaskResult(std::size_t task_no) const
Return a list of the resulting report of one specific run task.
int columns() const
The number of character columns (as specified to the constructor)
Definition: fmt.h:420
Base::IterCountIntType IterCountIntType
The integer type which serves to count the number of iterations (see MHRWParams)
CDataBaseType_ CDataBaseType
The structure which hold the constant shared data describing what we have to do.
CountRealType_ CountRealType
The real type which serves to average histogram counts (typically double)
CDataBaseType::HistogramType HistogramType
The histogram type reported by each task.
SimpleFinalHistogramType simpleFinalHistogram() const
The final histogram, with naive error bars ignoring the binning analysis.
Utilities for logging messages.
void finalize()
Finalize the averaging procedure.
Definition: histogram.h:783
FinalHistogramType finalHistogram() const
The final histogram, with all the error bars combined.