source: src/Fragmentation/Histogram/Histogram.cpp@ 22c4f57

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 22c4f57 was 22c4f57, checked in by Frederik Heber <heber@…>, 13 years ago

Added superposeOtherHistogram and implemented thereby operator+=() and operator-=().

  • the logic so far is that the other histogram must not extend beyond the present one.
  • Property mode set to 100644
File size: 8.7 KB
Line 
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>
42#include <iostream>
43#include <sstream>
44#include <string>
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
70
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
86std::ostream & operator<<(std::ostream &ost, const Histogram::Bin_t &elem)
87{
88 ost << "(" << elem.first << "," << elem.second << ") ";
89 return ost;
90}
91
92Histogram::Histogram(const samples_t &samples, const int _CountBins) :
93 binwidth(0.5),
94 CountBins(_CountBins)
95{
96 // build histogram from samples
97 if (!samples.empty()) {
98 if (CountBins == -1) {
99 CountBins = ceil(pow(samples.size(), 1./3.));
100 }
101 // 2. get min and max and determine width
102 samples_t::const_iterator maxiter = max_element(samples.begin(), samples.end());
103 samples_t::const_iterator miniter = min_element(samples.begin(), samples.end());
104 ASSERT((maxiter != samples.end()) || (miniter != samples.end()),
105 "Histogram::Histogram() - cannot find min/max despite non-empty range.");
106 LOG(1, "DEBUG: min is " << *miniter << " and max is " << *maxiter << ".");
107 // as the logic to calculate is a bit more complex, we cannot (sensibly) place
108 // it in the cstor call in the init list above. However, the binwidth is from
109 // this point on fixed through the existence of this instance. Hence, we rather
110 // keep it constant nonetheless and ust const_cast here.
111 const_cast<double &>(binwidth) = (*maxiter - *miniter)/(CountBins-1);
112
113 // 3. create each bin
114 BinCreator_t BinCreator( *miniter, binwidth );
115 std::vector<Bin_t> vectorbins;
116 // we need one extra bin for get...Bin()'s find to work properly
117 vectorbins.resize(CountBins+1, Bin_t( make_pair(0., 0.) ) );
118 std::generate( vectorbins.begin(), vectorbins.end(), BinCreator );
119 bins.insert(vectorbins.begin(), vectorbins.end());
120
121 // 4. place each sample into bin (make count normalized, i.e. always equal to
122 // surface area of 1)
123 BOOST_FOREACH( double value, samples) {
124 const Bins_t::iterator biniter = getLowerEndBin(value);
125 ASSERT( biniter != bins.end(),
126 "Histogram::Histogram() - cannot find bin for value from given samples.");
127 biniter->second += 1./binwidth;
128 }
129 LOG(2, "DEBUG: Bins are " << printBins() << ".");
130 } else {
131 LOG(1, "INFO: Given vector of samples is empty.");
132 }
133}
134
135std::string Histogram::printBins() const
136{
137 std::stringstream output;
138 std::for_each( bins.begin(), bins.end(), PrintPair<Bin_t>(output));
139 return output.str();
140}
141
142void Histogram::superposeOtherHistogram(const Histogram &other, const double prefactor)
143{
144 // check that other histogram lays within this one
145 ASSERT( getLowerEndBin(other.bins.begin()->first) != bins.end(),
146 "Histogram::superposeOtherHistogram() - other histogram's bins start sooner.");
147 ASSERT( getHigherEndBin((--other.bins.end())->first) != bins.end(),
148 "Histogram::superposeOtherHistogram() - other histogram's bins end later.");
149 // go through each of the other histogram's bins
150 Bins_t::const_iterator enditer = --other.bins.end(); // (except internal last one)
151 for (Bins_t::const_iterator biniter = other.bins.begin();
152 biniter != enditer; /* we advance ourselves in loop */) {
153 const Bin_t &bin = *biniter;
154 ++biniter;
155 const Bin_t &nextbin = *biniter;
156
157 LOG(2, "DEBUG: Current bin is " << bin << ", next bin is " << nextbin << ".");
158 // The bin will in general not fit into one bin in this histogram, but overlap.
159 // Hence, we determine the contribution of the bin to each bin in this histogram
160 // its overlaps into and add this weight to the bin.
161 Bins_t::const_iterator loweriter = getLowerEndBin(bin.first);
162 Bins_t::const_iterator upperiter = getHigherEndBin(nextbin.first);
163 ASSERT( loweriter != bins.end(),
164 "Histogram::superposeOtherHistogram() - lower end is invalid.");
165 ASSERT( upperiter != bins.end(),
166 "Histogram::superposeOtherHistogram() - higher end is invalid.");
167 ASSERT( loweriter->first < upperiter->first,
168 "Histogram::superposeOtherHistogram() - the bin range is invalid.");
169 LOG(2, "DEBUG: bin range here is ["
170 << loweriter->first << "," << upperiter->first << ").");
171
172 // Next, we create a vector of offsets
173 typedef std::vector< BinLowerEnd > offsets_t;
174 offsets_t offsets;
175 {
176 offsets.push_back(bin.first);
177 Bins_t::const_iterator iter = loweriter;
178 for (++iter; iter != upperiter; ++iter)
179 if (offsets.back() != iter->first)
180 offsets.push_back(iter->first);
181 if (offsets.back() != nextbin.first)
182 offsets.push_back(nextbin.first);
183 LOG(2, "DEBUG: Offsets are " << offsets << ".");
184 }
185
186 // then, we go through the offsets but the last one and add the respective area
187 {
188 offsets_t::const_iterator iter = offsets.begin();
189 offsets_t::const_iterator nextiter = ++offsets.begin();
190 for (; iter != --offsets.end(); ++iter, ++nextiter) {
191 const double length = *nextiter - *iter;
192 const double weight = bin.second * (length/binwidth);
193 Bins_t::iterator filliter = getLowerEndBin(*iter);
194 filliter->second += prefactor * weight;
195 }
196 }
197
198 {
199 std::stringstream output;
200 std::for_each( bins.begin(), bins.end(), PrintPair<Bin_t>(output));
201 LOG(2, "DEBUG: Bins are after summation " << output.str() << ".");
202 }
203 }
204}
205
206Histogram& Histogram::operator+=(const Histogram &other)
207{
208 superposeOtherHistogram(other, +1.);
209 return *this;
210}
211
212Histogram& Histogram::operator-=(const Histogram &other)
213{
214 superposeOtherHistogram(other, -1.);
215 return *this;
216}
217
218bool Histogram::isEmpty() const
219{
220 bool status = true;
221 for (Bins_t::const_iterator iter = bins.begin(); iter != bins.end(); ++iter)
222 status &= iter->second == 0;
223 return status;
224}
225
226Histogram::Bins_t::iterator Histogram::getLowerEndBin(const double _value)
227{
228 // lower bound returns key that is equal or greater
229 Bins_t::iterator iter = bins.lower_bound(_value);
230 if (iter != bins.end()) {
231 // if we are not on the boundary we always have to step back by one
232 if (_value != iter->first) {
233 if (iter != bins.begin()) {
234 --iter;
235 } else {
236 iter = bins.end();
237 }
238 } else if (iter == --bins.end()) {
239 // if we actually are on boundary of "last bin", set to end
240 iter = bins.end();
241 }
242 }
243 return iter;
244}
245
246Histogram::Bins_t::iterator Histogram::getHigherEndBin(const double _value)
247{
248 // upper bound return key that is strictly greater
249 Bins_t::iterator iter = bins.upper_bound(_value);
250 // if we are on the boundary we have to step back by one
251 if (iter != bins.end())
252 if (_value == iter->first)
253 if (iter != bins.begin())
254 --iter;
255
256 return iter;
257}
258
259double Histogram::area() const
260{
261 double area = 0.;
262 for(Bins_t::const_iterator iter = bins.begin(); iter != bins.end(); ++iter)
263 area += iter->second*binwidth;
264 return area;
265}
Note: See TracBrowser for help on using the repository browser.