OGS
Histogram.cpp
Go to the documentation of this file.
1
11#include "Histogram.h"
12
13#include <cmath>
14#include <fstream>
15
16#include "BaseLib/Logging.h"
17
18namespace BaseLib
19{
20
21template <typename T>
22int Histogram<T>::write(std::string const& file_name,
23 std::string const& data_set_name,
24 std::string const& param_name) const
25{
26 if (file_name.empty())
27 {
28 ERR("No file name specified.");
29 return 1;
30 }
31
32 std::ofstream out(file_name);
33 if (!out)
34 {
35 ERR("Error writing histogram: Could not open file.");
36 return 1;
37 }
38
39 out << "# Histogram for parameter " << param_name << " of data set "
40 << data_set_name << "\n";
41 std::size_t const n_bins = this->getNumberOfBins();
42 std::vector<std::size_t> const& bin_cnts(this->getBinCounts());
43 double const min(this->getMinimum());
44 double const bin_width(this->getBinWidth());
45
46 for (std::size_t k(0); k < n_bins; k++)
47 {
48 out << min + k * bin_width << " " << bin_cnts[k] << "\n";
49 }
50 out.close();
51 return 0;
52}
53
54template <typename T>
55void Histogram<T>::prettyPrint(std::ostream& os,
56 const unsigned int line_width) const
57{
58 const std::size_t count_max =
59 *std::max_element(histogram_.begin(), histogram_.end());
60 for (unsigned int bin = 0; bin < nr_bins_; ++bin)
61 {
62 os << "[" << min_ + bin * bin_width_ << ", "
63 << min_ + (bin + 1) * bin_width_ << ")\t";
64 os << histogram_[bin] << "\t";
65
66 const int n_stars = static_cast<int>(
67 std::ceil(line_width * ((double)histogram_[bin] / count_max)));
68 for (int star = 0; star < n_stars; star++)
69 {
70 os << "*";
71 }
72 os << "\n";
73 }
74}
75
76template <typename T>
77std::ostream& operator<<(std::ostream& os, const Histogram<T>& h)
78{
79 os << h.getNumberOfBins() << " " << h.getMinimum() << " " << h.getMaximum()
80 << " ";
81 std::copy(h.getBinCounts().begin(), h.getBinCounts().end(),
82 std::ostream_iterator<std::size_t>(os, " "));
83 return os << std::endl;
84}
85
86template class Histogram<double>;
87template std::ostream& operator<<(std::ostream& os, const Histogram<double>& h);
88} // namespace BaseLib
Implementation of Histogram class.
void ERR(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:45
const T & getMinimum() const
Definition Histogram.h:112
const unsigned int & getNumberOfBins() const
Definition Histogram.h:111
const std::vector< std::size_t > & getBinCounts() const
Definition Histogram.h:110
void prettyPrint(std::ostream &os, const unsigned int line_width=16) const
Definition Histogram.cpp:55
const T & getMaximum() const
Definition Histogram.h:113
int write(std::string const &file_name, std::string const &data_set_name, std::string const &param_name) const
Definition Histogram.cpp:22
std::ostream & operator<<(std::ostream &os, const Histogram< T > &h)
Definition Histogram.cpp:77