source: src/Fragmentation/Histogram/Histogram.cpp@ 6bed1f

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 Candidate_v1.7.0 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 6bed1f was 6bed1f, checked in by Frederik Heber <heber@…>, 13 years ago

Changed Histogram's cstor to take offset and binwidth instead of CountBins.

  • CountBins was nonsense anyway, could have been taken from samples.size() as well.
  • with these two values, we may also add the samples lateron.
  • Property mode set to 100644
File size: 9.9 KB
RevLine 
[c4fd03]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * Histogram.cpp
25 *
26 * Created on: Jul 26, 2012
27 * Author: heber
28 */
29
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36#include "CodePatterns/MemDebug.hpp"
37
38#include "Histogram.hpp"
39
40#include <algorithm>
41#include <cmath>
[3f6bbb]42#include <iostream>
[c4fd03]43#include <sstream>
[3f6bbb]44#include <string>
[c4fd03]45
46#include <boost/bind.hpp>
47#include <boost/foreach.hpp>
48
49#include "CodePatterns/Assert.hpp"
50#include "CodePatterns/Log.hpp"
51
52/** Tiny helper struct to create equally spaced bins with count of zero.
53 *
54 */
55struct BinCreator_t {
56 BinCreator_t( const double lowerend, const double _width ) :
57 currentstart(lowerend),
58 width(_width)
59 {}
60 Histogram::Bin_t operator()() {
61 Histogram::Bin_t bin( make_pair( currentstart, 0.) );
62 currentstart+=width;
63 return bin;
64 }
65private:
66 double currentstart;
67 const double width;
68};
69
[3f6bbb]70
[c4fd03]71// see http://stackoverflow.com/questions/634087/stdcopy-to-stdcout-for-stdpair
72// printing a pair is not easy, especially so with ostream_iterator as it cannot find
73// overload operator<<() as it is not in namespace std.
74template <class T>
75struct PrintPair : public std::unary_function<T, void>
76{
77 std::ostream& os;
78 PrintPair(std::ostream& strm) : os(strm) {}
79
80 void operator()(const T& elem) const
81 {
82 os << "(" << elem.first << "," << elem.second << ") ";
83 }
84};
85
[3f6bbb]86std::ostream & operator<<(std::ostream &ost, const Histogram::Bin_t &elem)
87{
88 ost << "(" << elem.first << "," << elem.second << ") ";
89 return ost;
90}
91
[cf18c5]92std::ostream & operator<<(std::ostream &ost, const Histogram &histogram)
93{
94 for (Histogram::Bins_t::const_iterator iter = histogram.bins.begin();
95 iter != histogram.bins.end(); ++iter)
96 ost << *iter;
97 return ost;
98}
99
[6bed1f]100Histogram::Histogram(const samples_t &samples, const BinLowerEnd _offset, const double _binwidth) :
101 binwidth(_binwidth),
102 offset(_offset)
[c4fd03]103{
104 // build histogram from samples
105 if (!samples.empty()) {
[6bed1f]106 // 1. get min and max and determine width
[c4fd03]107 samples_t::const_iterator maxiter = max_element(samples.begin(), samples.end());
108 samples_t::const_iterator miniter = min_element(samples.begin(), samples.end());
109 ASSERT((maxiter != samples.end()) || (miniter != samples.end()),
110 "Histogram::Histogram() - cannot find min/max despite non-empty range.");
[e11e23]111// LOG(1, "DEBUG: min is " << *miniter << " and max is " << *maxiter << ".");
[6bed1f]112
113 // 2. create each bin
114 {
115 std::vector<Bin_t> vectorbins;
116 BinCreator_t BinCreator( getLowerEnd(*miniter), binwidth );
117 // we need one extra bin for get...Bin()'s find to work properly
118 const int CountBins = ceil((*maxiter - getLowerEnd(*miniter))/binwidth)+1;
119 vectorbins.resize(CountBins+1, Bin_t( make_pair(0., 0.) ) );
120 std::generate( vectorbins.begin(), vectorbins.end(), BinCreator );
121 bins.insert(vectorbins.begin(), vectorbins.end());
122 }
123
124 // 3. place each sample into bin
[c4fd03]125 BOOST_FOREACH( double value, samples) {
[1c365e]126 const Bins_t::iterator biniter = getLowerEndBin(value);
[c4fd03]127 ASSERT( biniter != bins.end(),
128 "Histogram::Histogram() - cannot find bin for value from given samples.");
[6bed1f]129 // (make bin count normalized, i.e. always equal to surface area of 1)
[45f4f96]130 biniter->second += 1./binwidth;
[c4fd03]131 }
[e5dbd5]132 LOG(2, "DEBUG: Bins are " << printBins() << ".");
[c4fd03]133 } else {
[e11e23]134// LOG(1, "INFO: Given vector of samples is empty.");
[c4fd03]135 }
136}
137
[e5dbd5]138std::string Histogram::printBins() const
139{
140 std::stringstream output;
141 std::for_each( bins.begin(), bins.end(), PrintPair<Bin_t>(output));
142 return output.str();
143}
144
[e4048f]145void Histogram::extendMissingBins(const BinLowerEnd LowerEnd, const BinLowerEnd NextLowerEnd)
146{
147 Bins_t::const_iterator loweriter = getLowerEndBin(LowerEnd);
148 Bins_t::const_iterator upperiter = getHigherEndBin(NextLowerEnd);
149 if (loweriter == bins.end()) {
150 // we need bins beneath our first, add them
151 for(BinLowerEnd offset = getLowerEnd(LowerEnd);
152 offset < getLowerEnd(NextLowerEnd);
153 offset += binwidth)
154 bins.insert( std::make_pair (offset, 0. ) );
[e11e23]155// LOG(2, "DEBUG: Bins after adding empties before start are " << printBins() << ".");
[e4048f]156 loweriter = getLowerEndBin(LowerEnd);
157 ASSERT( loweriter != bins.end(),
158 "Histogram::extendMissingBins() - still no lower bound after adding empties.");
159 }
160 if (upperiter == bins.end()) {
161 // we need bins after our last, add them
162 for(BinLowerEnd offset = getLowerEnd(LowerEnd);
163 offset <= getLowerEnd(NextLowerEnd)+binwidth;
164 offset += binwidth)
165 bins.insert( std::make_pair (offset, 0. ) );
[e11e23]166// LOG(2, "DEBUG: Bins after adding empties after end are " << printBins() << ".");
[e4048f]167 upperiter = getHigherEndBin(NextLowerEnd);
168 ASSERT( upperiter != bins.end(),
169 "Histogram::extendMissingBins() - still no upper bound after adding empties.");
170 }
171}
172
[22c4f57]173void Histogram::superposeOtherHistogram(const Histogram &other, const double prefactor)
174{
175 // go through each of the other histogram's bins
176 Bins_t::const_iterator enditer = --other.bins.end(); // (except internal last one)
177 for (Bins_t::const_iterator biniter = other.bins.begin();
178 biniter != enditer; /* we advance ourselves in loop */) {
179 const Bin_t &bin = *biniter;
180 ++biniter;
181 const Bin_t &nextbin = *biniter;
182
[e11e23]183// LOG(2, "DEBUG: Current bin is " << bin << ", next bin is " << nextbin << ".");
[e4048f]184
185 // Check first whether start or end actually fit into our histogram, if not extend.
186 extendMissingBins(bin.first, nextbin.first);
187
[22c4f57]188 // The bin will in general not fit into one bin in this histogram, but overlap.
189 // Hence, we determine the contribution of the bin to each bin in this histogram
190 // its overlaps into and add this weight to the bin.
191 Bins_t::const_iterator loweriter = getLowerEndBin(bin.first);
192 Bins_t::const_iterator upperiter = getHigherEndBin(nextbin.first);
[e4048f]193
[22c4f57]194 ASSERT( loweriter->first < upperiter->first,
195 "Histogram::superposeOtherHistogram() - the bin range is invalid.");
[e11e23]196// LOG(2, "DEBUG: bin range here is ["
197// << loweriter->first << "," << upperiter->first << ").");
[22c4f57]198
199 // Next, we create a vector of offsets
200 typedef std::vector< BinLowerEnd > offsets_t;
201 offsets_t offsets;
202 {
203 offsets.push_back(bin.first);
204 Bins_t::const_iterator iter = loweriter;
205 for (++iter; iter != upperiter; ++iter)
206 if (offsets.back() != iter->first)
207 offsets.push_back(iter->first);
208 if (offsets.back() != nextbin.first)
209 offsets.push_back(nextbin.first);
[e11e23]210// LOG(2, "DEBUG: Offsets are " << offsets << ".");
[22c4f57]211 }
212
213 // then, we go through the offsets but the last one and add the respective area
214 {
215 offsets_t::const_iterator iter = offsets.begin();
216 offsets_t::const_iterator nextiter = ++offsets.begin();
217 for (; iter != --offsets.end(); ++iter, ++nextiter) {
218 const double length = *nextiter - *iter;
219 const double weight = bin.second * (length/binwidth);
220 Bins_t::iterator filliter = getLowerEndBin(*iter);
221 filliter->second += prefactor * weight;
222 }
223 }
224
225 {
226 std::stringstream output;
227 std::for_each( bins.begin(), bins.end(), PrintPair<Bin_t>(output));
228 LOG(2, "DEBUG: Bins are after summation " << output.str() << ".");
229 }
230 }
231}
232
[c4fd03]233Histogram& Histogram::operator+=(const Histogram &other)
234{
[22c4f57]235 superposeOtherHistogram(other, +1.);
[e11e23]236 LOG(2, "DEBUG: Bins after addition are " << printBins() << ".");
[c4fd03]237 return *this;
238}
239
240Histogram& Histogram::operator-=(const Histogram &other)
241{
[22c4f57]242 superposeOtherHistogram(other, -1.);
[e11e23]243 LOG(2, "DEBUG: Bins after subtraction are " << printBins() << ".");
[c4fd03]244 return *this;
245}
246
247bool Histogram::isEmpty() const
248{
249 bool status = true;
250 for (Bins_t::const_iterator iter = bins.begin(); iter != bins.end(); ++iter)
251 status &= iter->second == 0;
252 return status;
253}
254
[1c365e]255Histogram::Bins_t::iterator Histogram::getLowerEndBin(const double _value)
[c4fd03]256{
[1c365e]257 // lower bound returns key that is equal or greater
[c4fd03]258 Bins_t::iterator iter = bins.lower_bound(_value);
259 if (iter != bins.end()) {
[1c365e]260 // if we are not on the boundary we always have to step back by one
261 if (_value != iter->first) {
262 if (iter != bins.begin()) {
263 --iter;
264 } else {
265 iter = bins.end();
266 }
267 } else if (iter == --bins.end()) {
268 // if we actually are on boundary of "last bin", set to end
[c4fd03]269 iter = bins.end();
[1c365e]270 }
271 }
272 return iter;
273}
274
275Histogram::Bins_t::iterator Histogram::getHigherEndBin(const double _value)
276{
277 // upper bound return key that is strictly greater
278 Bins_t::iterator iter = bins.upper_bound(_value);
279 // if we are on the boundary we have to step back by one
280 if (iter != bins.end())
281 if (_value == iter->first)
282 if (iter != bins.begin())
283 --iter;
[c4fd03]284
285 return iter;
286}
[45f4f96]287
[1dd419]288Histogram::BinLowerEnd Histogram::getLowerEnd(const double _value) const
289{
290 BinLowerEnd start = _value - offset;
291 // then divide by binwidth
292 const int integral = floor(start/binwidth);
[e11e23]293 //const double fraction = fmod(start,binwidth);
[1dd419]294 start = offset + binwidth*integral;
295 return start;
296}
297
[45f4f96]298double Histogram::area() const
299{
300 double area = 0.;
301 for(Bins_t::const_iterator iter = bins.begin(); iter != bins.end(); ++iter)
302 area += iter->second*binwidth;
303 return area;
304}
Note: See TracBrowser for help on using the repository browser.