Loading [MathJax]/extensions/tex2jax.js
Tomographerv4.1
Tomographer C++ Framework Documentation
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
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 TOMOGRAPHER_EXPORT
90 void print_hist_short_bar_with_accept_info(std::ostream & str, int dig_w, std::size_t j, const HistogramType & hist,
91  double acceptance_ratio, int columns)
92 {
94  streamstr("#" << std::setw(dig_w) << j << ": "),
95  hist,
96  Tomographer::Tools::fmts(" [accept ratio = %.2f]", acceptance_ratio),
97  false, columns);
98  if (acceptance_ratio > MHRWAcceptanceRatioRecommendedMax ||
99  acceptance_ratio < MHRWAcceptanceRatioRecommendedMin) {
100  str << " *** Accept ratio out of recommended bounds ["<<MHRWAcceptanceRatioRecommendedMin
101  <<", "<<MHRWAcceptanceRatioRecommendedMax<<"] ! Adapt step size ***\n";
102  }
103 }
104 } // namespace tomo_internal
105 
106 
107 
108 
109 
110 
111 
112 
134 template<typename CDataBaseType_, typename LoggerType_>
135 TOMOGRAPHER_EXPORT struct ResultsCollectorSimple
136  : public virtual Tools::NeedOwnOperatorNew<
137  AveragedHistogram<UniformBinsHistogram<typename CDataBaseType_::HistogramType::Scalar,
138  typename CDataBaseType_::CountRealType>,
139  typename CDataBaseType_::CountRealType>
140  >::ProviderType
141 {
143  typedef CDataBaseType_ CDataBaseType;
145  typedef typename CDataBaseType::ValueCalculator ValueCalculator;
147  typedef typename CDataBaseType::CountRealType CountRealType;
149  typedef typename CDataBaseType::IterCountIntType IterCountIntType;
151  typedef typename CDataBaseType::StepRealType StepRealType;
153  typedef LoggerType_ LoggerType;
154 
159  typedef typename CDataBaseType::HistogramType HistogramType;
161  typedef typename CDataBaseType::HistogramParams HistogramParams;
175 
178  typedef HistogramType MHRWStatsCollectorResultType;
179 
180  TOMO_STATIC_ASSERT_EXPR( CDataBaseType::UseBinningAnalysis == false ) ;
181 
191  : public MHRandomWalkTaskResult<MHRWStatsCollectorResultType,IterCountIntType,StepRealType>,
192  public virtual Tools::NeedOwnOperatorNew<ScaledHistogramType>::ProviderType
193  {
195 
196  RunTaskResult()
197  : Base(), histogram()
198  {
199  }
200 
201  template<typename BaseType, typename ScaledHistogramTypeRef>
202  RunTaskResult(BaseType&& b, ScaledHistogramTypeRef&& histogram_)
203  : Base(std::forward<BaseType>(b)), histogram(histogram_)
204  {
205  }
206 
215  const ScaledHistogramType histogram;
216  };
217 
219 
220 
225  ResultsCollectorSimple(LoggerType & logger_)
226  : _finalized(false), _finalhistogram(HistogramParams()),
227  _collected_runtaskresults(),
228  _llogger("MHRWTasks::ValueHistogramTasks::ResultsCollectorSimple", logger_)
229  {
230  }
231 
233  {
234  for (std::size_t j = 0; j < _collected_runtaskresults.size(); ++j) {
235  if (_collected_runtaskresults[j] != NULL) {
236  delete _collected_runtaskresults[j];
237  }
238  }
239  }
240 
247  inline bool isFinalized() const { return _finalized; }
248 
259  inline FinalHistogramType finalHistogram() const {
260  tomographer_assert(isFinalized() && "You may only call finalHistogram() after the runs have been finalized.");
261  return _finalhistogram;
262  }
263 
269  inline std::size_t numTasks() const {
270  tomographer_assert(isFinalized() && "You may only call numTasks() after the runs have been finalized.");
271  return _collected_runtaskresults.size();
272  }
273 
282  inline const RunTaskResultList & collectedRunTaskResults() const {
283  tomographer_assert(isFinalized() && "You may only call collectedRunTaskResults() after the runs have been finalized.");
284  return _collected_runtaskresults;
285  }
286 
298  inline const RunTaskResult * collectedRunTaskResult(std::size_t task_no) const {
299  tomographer_assert(isFinalized() && "You may only call collectedRunTaskResult(std::size_t) after the runs have been finalized.");
300  tomographer_assert(task_no < _collected_runtaskresults.size());
301  return _collected_runtaskresults[task_no];
302  }
303 
316  template<typename RealType = double>
317  inline void printHistogramCsv(std::ostream & stream, std::string sep = "\t", std::string linesep = "\n", int precision = 10)
318  {
319  // ### Q: why the RealType template parameter??
320  stream << "Value" << sep << "Counts" << sep << "Error" << linesep
321  << std::scientific << std::setprecision(precision);
322  for (int kk = 0; kk < _finalhistogram.bins.size(); ++kk) {
323  stream << RealType(_finalhistogram.params.binLowerValue(kk)) << sep
324  << RealType(_finalhistogram.bins(kk)) << sep
325  << RealType(_finalhistogram.delta(kk)) << linesep;
326  }
327  }
328 
343  inline void printFinalReport(std::ostream & str, const CDataBaseType & cdata,
344  int max_width = 0, bool print_histogram = true)
345  {
346  Tools::ConsoleFormatterHelper h(max_width); // possibly detect terminal width etc.
347 
348  const auto& res = *this;
349 
350  const RunTaskResultList & collresults = res.collectedRunTaskResults();
351  const FinalHistogramType finalhistogram = res.finalHistogram();
352  str << "\n"
353  << h.centerLine("Final Report of Runs")
354  << h.hrule()
355  ;
356  cdata.printBasicCDataMHRWInfo(str);
357  int dig_w = (int)std::ceil(std::log10(res.numTasks()));
358  for (std::size_t j = 0; j < res.numTasks(); ++j) {
359  tomo_internal::print_hist_short_bar_with_accept_info(str, dig_w, j, collresults[j]->histogram,
360  collresults[j]->acceptance_ratio, h.columns());
361  }
362  str << h.hrule()
363  << "\n";
364 
365  if (print_histogram) {
366  // and the final histogram
367  str << h.centerLine("Final Histogram")
368  << h.hrule();
369  histogramPrettyPrint(str, finalhistogram, h.columns());
370  str << h.hrule()
371  << "\n";
372  }
373  }
374 
375 
376 
377 private:
378  bool _finalized;
379  FinalHistogramType _finalhistogram;
380 
381  RunTaskResultList _collected_runtaskresults;
382 
384 
385 public:
386 
387  // these functions will be called by the task manager/dispatcher
388 
390  template<typename Cnt, typename CData>
391  inline void init(Cnt num_total_runs, Cnt /*n_chunk*/, const CData * pcdata)
392  {
393  tomographer_assert(!isFinalized() && "init() called after results have been finalized!");
394 
395  _collected_runtaskresults.resize(num_total_runs, NULL);
396  _finalhistogram.reset(pcdata->histogram_params);
397  }
399  template<typename Cnt, typename TaskResultType, typename CData>
400  inline void collectResult(Cnt task_no, TaskResultType&& taskresult, const CData * /*pcdata*/)
401  {
402  tomographer_assert(!isFinalized() && "collectResult() called after results have been finalized!");
403 
404  auto logger = _llogger.subLogger(TOMO_ORIGIN);
405  logger.debug([&](std::ostream & str) {
406  str << "Got task result. Histogram is:\n" << taskresult.stats_collector_result.prettyPrint();
407  });
408 
409  // Scale this histogram using the number of samples, so that the scaling of the
410  // histogram coincides to that used by the binning analysis. This so we can compare
411  // those histograms obtained by the two procedures.
412  //
413  // NOTE: This does not normalize the histogram to unit area. Use \ref
414  // UniformBinsHistogram::normalized() for that.
415  //
416  ScaledHistogramType thishistogram = taskresult.stats_collector_result;
417  typename ScaledHistogramType::CountType numsamples =
418  thishistogram.bins.sum() + thishistogram.off_chart;
419  thishistogram.bins /= numsamples;
420  thishistogram.off_chart /= numsamples;
421 
422  _finalhistogram.addHistogram(thishistogram);
423  _collected_runtaskresults[task_no]
424  = new RunTaskResult(std::forward<TaskResultType>(taskresult), std::move(thishistogram));
425  }
432  template<typename Cnt, typename CData>
433  inline void runsFinished(Cnt, const CData *)
434  {
435  tomographer_assert(!isFinalized() && "runsFinished() called after results have been finalized!");
436 
437  _finalized = true;
438  _finalhistogram.finalize();
439  }
440 
441 }; // struct ResultsCollectorSimple
442 
443 
444 
445 
446 
478 template<typename CDataBaseType_, typename LoggerType_>
479 TOMOGRAPHER_EXPORT struct ResultsCollectorWithBinningAnalysis
480  : public virtual Tools::NeedOwnOperatorNew<
481  UniformBinsHistogram<typename CDataBaseType_::HistogramType::Scalar,
482  typename CDataBaseType_::CountRealType>
483  >::ProviderType
484 {
486  typedef CDataBaseType_ CDataBaseType;
488  typedef typename CDataBaseType::ValueCalculator ValueCalculator;
490  typedef typename CDataBaseType::CountRealType CountRealType;
492  typedef typename CDataBaseType::IterCountIntType IterCountIntType;
494  typedef typename CDataBaseType::StepRealType StepRealType;
496  typedef LoggerType_ LoggerType;
497 
503  typedef typename tomo_internal::histogram_types<CDataBaseType_,true>::BinningMHRWStatsCollectorParams
505 
510  typedef typename BinningMHRWStatsCollectorParams::BinningAnalysisParamsType BinningAnalysisParamsType;
511 
518  typedef typename BinningMHRWStatsCollectorParams::Result MHRWStatsCollectorResultType;
519 
524  typedef typename CDataBaseType::HistogramType HistogramType;
529  typedef typename CDataBaseType::HistogramParams HistogramParams;
530 
533 
544 
554 
555 
556  TOMO_STATIC_ASSERT_EXPR( CDataBaseType::UseBinningAnalysis ) ;
557 
563  : _finalized(false), _finalhistogram(), _simplefinalhistogram(),
564  _collected_runtaskresults(),
565  _llogger("MHRWTasks::ValueHistogramTasks::ResultsCollectorWithBinningAnalysis", logger_)
566  {
567  }
568 
570  {
571  for (std::size_t j = 0; j < _collected_runtaskresults.size(); ++j) {
572  if (_collected_runtaskresults[j] != NULL) {
573  delete _collected_runtaskresults[j];
574  }
575  }
576  }
577 
584  inline bool isFinalized() const { return _finalized; }
585 
596  inline FinalHistogramType finalHistogram() const {
597  tomographer_assert(isFinalized() && "You may only call finalHistogram() after the runs have been finalized.");
598  return _finalhistogram;
599  }
600 
613  inline SimpleFinalHistogramType simpleFinalHistogram() const {
614  tomographer_assert(isFinalized() && "You may only call simpleFinalHistogram() after the runs have been finalized.");
615  return _simplefinalhistogram;
616  }
617 
623  inline std::size_t numTasks() const {
624  tomographer_assert(isFinalized() && "You may only call numTasks() after the runs have been finalized.");
625  return _collected_runtaskresults.size();
626  }
627 
636  inline const RunTaskResultList & collectedRunTaskResults() const {
637  tomographer_assert(isFinalized() && "You may only call collectedRunTaskResults() after the runs have been finalized.");
638  return _collected_runtaskresults;
639  }
640 
652  inline const RunTaskResult * collectedRunTaskResult(std::size_t task_no) const {
653  tomographer_assert(isFinalized() && "You may only call collectedRunTaskResult(std::size_t) after the runs have been finalized.");
654  tomographer_assert(task_no < _collected_runtaskresults.size());
655  return _collected_runtaskresults[task_no];
656  }
657 
658 
672  template<typename RealType = double>
673  inline void printHistogramCsv(std::ostream & stream, std::string sep = "\t", std::string linesep = "\n",
674  int precision = 10)
675  {
676  // ### Q: why the RealType template parameter??
677  stream << "Value" << sep << "Counts" << sep << "Error" << sep << "SimpleError" << linesep
678  << std::scientific << std::setprecision(precision);
679  for (int kk = 0; kk < _finalhistogram.bins.size(); ++kk) {
680  stream << RealType(_finalhistogram.params.binLowerValue(kk)) << sep
681  << RealType(_finalhistogram.bins(kk)) << sep
682  << RealType(_finalhistogram.delta(kk)) << sep
683  << RealType(_simplefinalhistogram.delta(kk)) << linesep;
684  }
685  }
686 
700  inline void printFinalReport(std::ostream & str, const CDataBaseType & cdata,
701  int max_width = 0, bool print_histogram = true)
702  {
703  Tools::ConsoleFormatterHelper h(max_width); // possibly detect terminal width etc.
704 
705  const auto& res = *this;
706 
707  // produce report on runs
708  const RunTaskResultList & collresults = res.collectedRunTaskResults();
709  const FinalHistogramType finalhistogram = res.finalHistogram();
710  str << "\n"
711  << h.centerLine("Final Report of Runs")
712  << h.hrule()
713  ;
714  cdata.printBasicCDataMHRWInfo(str);
715  int dig_w = (int)std::ceil(std::log10(res.numTasks()));
716  for (std::size_t j = 0; j < res.numTasks(); ++j) {
717  const auto& stats_coll_result = collresults[j]->stats_collector_result;
718 
719  tomo_internal::print_hist_short_bar_with_accept_info(str, dig_w, j, stats_coll_result.hist,
720  collresults[j]->acceptance_ratio, h.columns());
721 
722  // error bars stats:
723  const auto nbins = stats_coll_result.converged_status.size();
724  const auto n_conv = stats_coll_result.converged_status
725  .cwiseEqual(BinningAnalysisParamsType::CONVERGED).count();
726  Eigen::ArrayXi unkn_arr = (stats_coll_result.converged_status
727  .cwiseEqual(BinningAnalysisParamsType::UNKNOWN_CONVERGENCE))
728  .template cast<int>();
729  // little heuristic to see whether the "unknown" converged error bars are isolated or not
730  const auto n_unknown = unkn_arr.count();
731  const auto n_unknown_followingotherunknown
732  = unkn_arr.segment(0,nbins-1).cwiseProduct(unkn_arr.segment(1,nbins-1)).count();
733  const auto n_unknown_isolated = n_unknown - n_unknown_followingotherunknown;
734  const auto n_notconv = stats_coll_result.converged_status
735  .cwiseEqual(BinningAnalysisParamsType::NOT_CONVERGED).count();
736  str << " error bars: " << n_conv << " converged / "
737  << n_unknown << " maybe (" << n_unknown_isolated << " isolated) / "
738  << n_notconv << " not converged\n";
739  }
740  str << h.hrule()
741  << "\n";
742 
743  if (print_histogram) {
744  // and the final histogram
745  str << h.centerLine("Final Histogram")
746  << h.hrule();
747  histogramPrettyPrint(str, finalhistogram, h.columns());
748  str << h.hrule()
749  << "\n";
750  }
751  }
752 
753 
754 private:
755  bool _finalized;
756  FinalHistogramType _finalhistogram;
757  SimpleFinalHistogramType _simplefinalhistogram;
758 
759  RunTaskResultList _collected_runtaskresults;
760 
762 
763 
764 public:
765 
767  template<typename Cnt, typename CData>
768  inline void init(Cnt num_total_runs, Cnt /*n_chunk*/, const CData * pcdata)
769  {
770  tomographer_assert(!isFinalized() && "init() called after results have been finalized!");
771 
772  _collected_runtaskresults.resize(num_total_runs, NULL);
773  _finalhistogram.reset(pcdata->histogram_params);
774  _simplefinalhistogram.reset(pcdata->histogram_params);
775  }
776 
778  template<typename Cnt, typename TaskResultType, typename CData>
779  inline void collectResult(Cnt task_no, TaskResultType && taskresult, const CData *)
780  {
781  tomographer_assert(!isFinalized() && "collectResult() called after results have been finalized!");
782 
783  auto logger = _llogger.subLogger(TOMO_ORIGIN);
784 
785  auto stats_coll_result = taskresult.stats_collector_result;
786 
787  logger.debug([&](std::ostream & str) {
788  str << "(). Got task result. Histogram (w/ error bars from binning analysis):\n"
789  << stats_coll_result.hist.prettyPrint();
790  });
791 
792  if ((stats_coll_result.converged_status !=
793  Eigen::ArrayXi::Constant(stats_coll_result.hist.numBins(), BinningAnalysisParamsType::CONVERGED)).any()) {
794  logger.debug([&,this](std::ostream & str) {
795  str << "Error bars have not converged! The error bars at different binning levels are:\n"
796  << stats_coll_result.error_levels << "\n"
797  << "\t-> convergence analysis: \n";
798  for (std::size_t k = 0; k < stats_coll_result.hist.numBins(); ++k) {
799  str << "\t val[" << std::setw(3) << k << "] = "
800  << std::setw(12) << stats_coll_result.hist.bins(k)
801  << " +- " << std::setw(12) << stats_coll_result.hist.delta(k);
802  if (stats_coll_result.converged_status(k) == BinningAnalysisParamsType::CONVERGED) {
803  str << " [CONVERGED]";
804  } else if (stats_coll_result.converged_status(k) == BinningAnalysisParamsType::NOT_CONVERGED) {
805  str << " [NOT CONVERGED]";
806  } else if (stats_coll_result.converged_status(k) == BinningAnalysisParamsType::UNKNOWN_CONVERGENCE) {
807  str << " [UNKNOWN]";
808  } else {
809  str << " [UNKNOWN CONVERGENCE STATUS: " << stats_coll_result.converged_status(k) << "]";
810  }
811  str << "\n";
812  }
813  });
814  }
815 
816  // because stats_coll_result is a histogram WITH error bars, addHistogram
817  // will do the right thing and take them into account.
818  _finalhistogram.addHistogram(stats_coll_result.hist);
819 
820  logger.debug("added histogram.");
821 
822  // this one is declared for histograms WITHOUT error bars (SimpleHistogramType is a
823  // UniformBinsHistogram), so it will just ignore the error bars.
824  logger.debug([&](std::ostream & str) {
825  str << "Simple histogram is:\n";
826  histogramPrettyPrint<SimpleScaledHistogramType>(str, stats_coll_result.hist);
827  });
828  _simplefinalhistogram.addHistogram(stats_coll_result.hist);
829 
830  _collected_runtaskresults[task_no] = new RunTaskResult(std::move(taskresult));
831 
832  logger.debug("done.");
833  }
834 
836  template<typename Cnt, typename CData>
837  inline void runsFinished(Cnt, const CData *)
838  {
839  tomographer_assert(!isFinalized() && "runs_finished() called after results have been finalized!");
840 
841  _finalized = true;
842  _finalhistogram.finalize();
843  _simplefinalhistogram.finalize();
844  }
845 
846 };
847 
848 
849 
850 
851 
852 
853 
854 // ------------------------------------------------
855 
856 
857 namespace tomo_internal {
858 template<typename CDataBaseType, typename LoggerType, bool UseBinningAnalysis>
859 struct ResultsCollectorTypeHelper {
861 };
862 template<typename CDataBaseType, typename LoggerType>
863 struct ResultsCollectorTypeHelper<CDataBaseType, LoggerType, true> {
865 };
866 } // namespace tomo_internal
867 
868 
869 
870 
938 template<typename ValueCalculator_, bool UseBinningAnalysis_ = true,
939  typename IterCountIntType_ = int, typename StepRealType_ = double,
940  typename CountRealType_ = double, typename HistCountIntType_ = IterCountIntType_>
941 TOMOGRAPHER_EXPORT struct CDataBase
942  : public MHRWTasks::CDataBase<IterCountIntType_, StepRealType_>,
943  public virtual Tools::NeedOwnOperatorNew<ValueCalculator_>::ProviderType
944 {
947 
952 
954  typedef HistCountIntType_ HistCountIntType;
955 
957  typedef ValueCalculator_ ValueCalculator;
959  typedef CountRealType_ CountRealType;
960 
962  static constexpr bool UseBinningAnalysis = UseBinningAnalysis_;
963 
976 
991 
995 
998 
999 
1001  TOMOGRAPHER_ENABLED_IF(!UseBinningAnalysis)
1002  CDataBase(const ValueCalculator & valcalc_, HistogramParams histogram_params_,
1003  MHRWParamsType p, int base_seed = 0)
1004  : Base(std::move(p), base_seed), valcalc(valcalc_), histogram_params(histogram_params_),
1005  binningNumLevels()
1006  {
1007  }
1008 
1010  TOMOGRAPHER_ENABLED_IF(UseBinningAnalysis)
1011  CDataBase(const ValueCalculator & valcalc_, HistogramParams histogram_params_, int binning_num_levels_,
1012  MHRWParamsType p, int base_seed = 0)
1013  : Base(std::move(p), base_seed), valcalc(valcalc_), histogram_params(histogram_params_),
1014  binningNumLevels(binning_num_levels_)
1015  {
1016  }
1017 
1024 
1025 
1031  template<typename LoggerType, TOMOGRAPHER_ENABLED_IF_TMPL(!UseBinningAnalysis)>
1033  createStatsCollector(LoggerType & logger) const
1034  {
1036  histogram_params,
1037  valcalc,
1038  logger
1039  );
1040  }
1041 
1047  template<typename LoggerType, TOMOGRAPHER_ENABLED_IF_TMPL(UseBinningAnalysis)>
1049  typename tomo_internal::histogram_types<CDataBase, true>::BinningMHRWStatsCollectorParams,
1050  LoggerType>
1051  createStatsCollector(LoggerType & logger) const
1052  {
1053  typedef typename tomo_internal::histogram_types<CDataBase, true>::BinningMHRWStatsCollectorParams
1054  BinningMHRWStatsCollectorParams;
1055 
1057  histogram_params,
1058  valcalc,
1059  binningNumLevels.value,
1060  logger
1061  );
1062  }
1063 
1079  template<typename LoggerType>
1081  typedef
1082 #ifndef TOMOGRAPHER_PARSED_BY_DOXYGEN
1083  typename
1084  tomo_internal::ResultsCollectorTypeHelper<CDataBase<ValueCalculator,UseBinningAnalysis,IterCountIntType,StepRealType,CountRealType,HistCountIntType>,
1085  LoggerType, UseBinningAnalysis>::type
1086 #else
1087  [...] // parsed by doxygen -- make this more readable
1088 #endif
1089  Type;
1090 
1091  typedef typename Type::RunTaskResult RunTaskResultType;
1092  };
1093 };
1094 // define static members:
1095 template<typename ValueCalculator_, bool UseBinningAnalysis_,
1096  typename IterCountIntType_, typename StepRealType_,
1097  typename CountRealType_, typename HistCountIntType_>
1099 
1100 
1101 
1102 
1103 
1104 
1105 
1106 
1107 
1108 } // namespace ValueHistogramTasks
1109 } // namespace MHRWTasks
1110 } // namespace Tomographer
1111 
1112 
1113 #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:236
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:754
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:1332
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:225
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:1660
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:1898
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:1229
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.
#define TOMO_STATIC_ASSERT_EXPR(...)
Tool for static assertions without message.
Definition: cxxdefs.h:76
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:716
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:231
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:238
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
#define tomographer_assert(...)
Assertion test macro.
Definition: cxxdefs.h:83
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:786
FinalHistogramType finalHistogram() const
The final histogram, with all the error bars combined.