#ifndef __JTOOLS__JABSTRACTHISTOGRAM__ #define __JTOOLS__JABSTRACTHISTOGRAM__ #include #include #include "JTools/JRange.hh" #include "JTools/JGrid.hh" /** * \author mdejong */ namespace JTOOLS {} namespace JPP { using namespace JTOOLS; } namespace JTOOLS { /** * Simple data structure for histogram binning. */ template struct JAbstractHistogram : public JRange { typedef JAbscissa_t abscissa_type; typedef JRange range_type; /** * Default constructor. */ JAbstractHistogram() : JRange(), number_of_bins(0) {} /** * Constructor. * * \param nx number of bins * \param xmin lower limit * \param xmax upper limit */ JAbstractHistogram(const int nx, const abscissa_type xmin, const abscissa_type xmax) : JRange(xmin, xmax), number_of_bins(nx) {} /** * Constructor. * * \param xmin lower limit * \param xmax upper limit */ JAbstractHistogram(const abscissa_type xmin, const abscissa_type xmax) : JRange(xmin, xmax), number_of_bins(0) {} /** * Get number of bins. * * \return number of bins */ int getNumberOfBins() const { return number_of_bins; } /** * Get bin width. * * \return bin width */ double getBinWidth() const { return this->getLength() / this->getNumberOfBins(); } /** * Set bin width. * * If option < 0, adjust lower limit; if option > 0, adjust upper limit; else no adjustments. * * \param dx bin width * \param option option */ void setBinWidth(const abscissa_type dx, int option = 0) { number_of_bins = (int) (this->getLength() / dx); if (option < 0) { this->setLowerLimit(this->getUpperLimit() - number_of_bins + dx); } if (option > 0) { this->setUpperLimit(this->getLowerLimit() + number_of_bins + dx); } } /** * Check validity of histogram binning. * * \return true if both range and number of bins are valid; else false */ bool is_valid() const { return static_cast(*this).is_valid() && number_of_bins > 0; } /** * Type conversion operator. * * \return grid */ operator JGrid () const { return make_grid(this->getNumberOfBins() + 1, this->getLowerLimit(), this->getUpperLimit()); } /** * Read histogram from input. * * \param in input stream * \param histogram histogram * \return input stream */ friend inline std::istream& operator>>(std::istream& in, JAbstractHistogram& histogram) { return in >> histogram.number_of_bins >> static_cast(histogram); } /** * Write histogram to output. * * \param out output stream * \param histogram histogram * \return output stream */ friend inline std::ostream& operator<<(std::ostream& out, const JAbstractHistogram& histogram) { return out << histogram.number_of_bins << ' ' << static_cast(histogram); } protected: int number_of_bins; }; /** * Helper method for JAbstractHistogram. * * \param nx number of bins * \param xmin lower limit * \param xmax upper limit * \return histogram */ template inline JAbstractHistogram make_histogram(const int nx, const JAbscissa_t xmin, const JAbscissa_t xmax) { return JAbstractHistogram(nx, xmin, xmax); } } #endif