105 lines
1.8 KiB
C++
105 lines
1.8 KiB
C++
/*
|
||
* © 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
|