This repository has been archived on 2020-04-08. You can view files and clone it, but cannot push or open issues or pull requests.
Files
Indoor/math/stats/Histogram.h
2018-10-25 11:50:12 +02:00

105 lines
1.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* © Copyright 2014 Urheberrechtshinweis
* Alle Rechte vorbehalten / All Rights Reserved
*
* Programmcode ist urheberrechtlich geschuetzt.
* Das Urheberrecht liegt, soweit nicht ausdruecklich anders gekennzeichnet, bei Frank Ebner.
* Keine Verwendung ohne explizite Genehmigung.
* (vgl. § 106 ff UrhG / § 97 UrhG)
*/
#ifndef STATS_HISTOGRAM_H
#define STATS_HISTOGRAM_H
#ifdef WITH_DEBUG_PLOT
#include <KLib/misc/gnuplot/Gnuplot.h>
#include <KLib/misc/gnuplot/GnuplotPlot.h>
#include <KLib/misc/gnuplot/GnuplotPlotElementLines.h>
#endif
#include <vector>
namespace Stats {
template <typename Scalar> class Histogram {
#ifdef WITH_DEBUG_PLOT
K::Gnuplot gp;
K::GnuplotPlot plot;
K::GnuplotPlotElementLines lines;
#endif
Scalar min;
Scalar max;
int bins;
int cnt = 0;
std::vector<Scalar> counts;
public:
/** ctor */
Histogram(Scalar min, Scalar max, int bins) : min(min), max(max), bins(bins) {
clear();
#ifdef WITH_DEBUG_PLOT
plot.add(&lines);
#endif
}
int count() const {
return cnt;
}
void add(const Scalar x) {
const int idx = binIdx(x);
counts.at(idx) += 1;
++cnt;
#ifdef WITH_DEBUG_PLOT
if (cnt % 200 == 0) {showPlot();}
#endif
}
void clear() {
counts.clear();
counts.resize(bins);
cnt = 0;
}
#ifdef WITH_DEBUG_PLOT
void showPlot() {
lines.clear();
lines.add(K::GnuplotPoint2(-1,0));
for (size_t idx = 0; idx < counts.size(); ++idx) {
const Scalar val = binValue(idx);
const Scalar sum = counts[idx];
const K::GnuplotPoint2 gp2(val, sum);
lines.add(gp2);
}
gp.draw(plot);
gp.flush();
}
#endif
private:
int binIdx(const Scalar val) const {
return (val - min) / (max-min) * bins;
}
Scalar binValue(const int idx) {
return idx * (max-min) + min;
}
};
}
#endif // STATS_HISTOGRAM_H