source: src/Jobs/Grid/SamplingGrid.cpp@ 620517

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

FIX: SamplingGrid::getWindowGridPoints() was broken.

  • or at least inconsistent with use in MPQC.
  • also added .._inline.hpp module to contain all inline functions.
  • placed several one- or two-liners in the inline section.
  • Property mode set to 100644
File size: 15.4 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 * SamplingGrid.cpp
25 *
26 * Created on: 25.07.2012
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35// include headers that implement a archive in simple text format
36// otherwise BOOST_CLASS_EXPORT_IMPLEMENT has no effect
37#include <boost/archive/text_oarchive.hpp>
38#include <boost/archive/text_iarchive.hpp>
39
40#include "CodePatterns/MemDebug.hpp"
41
42#include "Jobs/Grid/SamplingGrid.hpp"
43
44#include <limits>
45
46#include "CodePatterns/Assert.hpp"
47#include "CodePatterns/Log.hpp"
48
49// static instances
50const double SamplingGrid::zeroOffset[3] = { 0., 0., 0. };
51
52SamplingGrid::SamplingGrid() :
53 SamplingGridProperties()
54{
55 setWindowSize(zeroOffset, zeroOffset);
56 ASSERT( getWindowGridPoints() == (size_t)0,
57 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
58}
59
60SamplingGrid::SamplingGrid(const double _begin[3],
61 const double _end[3],
62 const int _level) :
63 SamplingGridProperties(_begin, _end, _level)
64{
65 setWindowSize(zeroOffset, zeroOffset);
66 ASSERT( getWindowGridPoints() == (size_t)0,
67 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
68}
69
70SamplingGrid::SamplingGrid(const double _begin[3],
71 const double _end[3],
72 const int _level,
73 const sampledvalues_t &_sampled_grid) :
74 SamplingGridProperties(_begin, _end, _level),
75 sampled_grid(_sampled_grid)
76{
77 setWindowSize(_begin, _end);
78 ASSERT( getWindowGridPoints() == (size_t)_sampled_grid.size(),
79 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
80}
81
82SamplingGrid::SamplingGrid(const SamplingGrid &_grid) :
83 SamplingGridProperties(_grid),
84 sampled_grid(_grid.sampled_grid)
85{
86 setWindowSize(_grid.begin_window, _grid.end_window);
87 ASSERT( getWindowGridPoints() == _grid.getWindowGridPoints(),
88 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
89}
90
91SamplingGrid::SamplingGrid(const SamplingGridProperties &_props) :
92 SamplingGridProperties(_props)
93{
94 setWindowSize(zeroOffset, zeroOffset);
95 ASSERT( getWindowGridPoints() == (size_t)0,
96 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
97}
98
99SamplingGrid::SamplingGrid(
100 const SamplingGridProperties &_props,
101 const sampledvalues_t &_sampled_grid) :
102 SamplingGridProperties(_props),
103 sampled_grid(_sampled_grid)
104{
105 setWindowSize(_props.begin, _props.end);
106 ASSERT( getWindowGridPoints() == (size_t)_sampled_grid.size(),
107 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
108}
109
110SamplingGrid::~SamplingGrid()
111{}
112
113SamplingGrid& SamplingGrid::operator=(const SamplingGrid& other)
114{
115 // check for self-assignment
116 if (this != &other) {
117 static_cast<SamplingGridProperties &>(*this) = other;
118 setWindowSize(other.begin_window, other.end_window);
119 sampled_grid = other.sampled_grid;
120 }
121 return *this;
122}
123
124SamplingGrid& SamplingGrid::operator*=(const SamplingGrid& other)
125{
126 // check that grids are compatible
127 if (isCompatible(other)) {
128 sampledvalues_t::iterator iter = sampled_grid.begin();
129 sampledvalues_t::const_iterator otheriter = other.sampled_grid.begin();
130 for(; iter != sampled_grid.end(); ++iter, ++otheriter )
131 *iter *= (*otheriter);
132 } else {
133 ASSERT(0, "SamplingGrid::operator*=() - superposing incompatible grids is so far not in the cards.");
134 }
135 return *this;
136}
137
138void SamplingGrid::superposeOtherGrids(const SamplingGrid &other, const double prefactor)
139{
140 /// check that grids are compatible
141 if (isCompatible(other)) {
142 /// get maximum of window
143 double max_begin_window[3];
144 double max_end_window[3];
145 bool doExtend = false;
146 for (size_t index=0; index<3;++index) {
147 if (begin_window[index] >= other.begin_window[index]) {
148 max_begin_window[index] = other.begin_window[index];
149 doExtend = true;
150 } else {
151 max_begin_window[index] = begin_window[index];
152 }
153 if (end_window[index] >= other.end_window[index]) {
154 max_end_window[index] = end_window[index];
155 } else {
156 max_end_window[index] = other.end_window[index];
157 doExtend = true;
158 }
159 }
160 LOG(2, "DEBUG: max begin is " << max_begin_window[0] << "," << max_begin_window[1] << "," << max_begin_window[2] << ".");
161 LOG(2, "DEBUG: max end is " << max_end_window[0] << "," << max_end_window[1] << "," << max_end_window[2] << ".");
162 if (doExtend)
163 extendWindow(max_begin_window, max_end_window);
164 /// and copy other into larger window, too
165 addOntoWindow(other.begin_window, other.end_window, other.sampled_grid, prefactor);
166 } else {
167 ASSERT(0, "SamplingGrid::superposeOtherGrids() - superposing incompatible grids is so far not in the cards.");
168 }
169}
170
171const size_t SamplingGrid::getWindowGridPointsPerAxis(const size_t axis) const
172{
173 static const double round_offset(
174 (std::numeric_limits<size_t>::round_style == std::round_toward_zero) ?
175 0.5 : 0.); // need offset to get to round_toward_nearest behavior
176// const double total = getTotalLengthPerAxis(axis);
177 const double delta = getDeltaPerAxis(axis);
178 if (delta == 0)
179 return 0;
180 const double length = getWindowLengthPerAxis(axis);
181 if (length == 0)
182 return 0;
183 return (size_t)(length/delta+round_offset);
184}
185
186double SamplingGrid::integral() const
187{
188 const double volume_element = getVolume()/(double)getTotalGridPoints();
189 double int_value = 0.;
190 for (sampledvalues_t::const_iterator iter = sampled_grid.begin();
191 iter != sampled_grid.end();
192 ++iter)
193 int_value += *iter;
194 int_value *= volume_element;
195 LOG(2, "DEBUG: SamplingGrid::integral() is " << scientific << setprecision(13) << int_value << ".");
196 return int_value;
197}
198
199double SamplingGrid::integral(const SamplingGrid &weight) const
200{
201 if (isCompatible(weight)) {
202 const double volume_element = getVolume()/(double)getTotalGridPoints();
203 double int_value = 0.;
204 sampledvalues_t::const_iterator iter = sampled_grid.begin();
205 sampledvalues_t::const_iterator weightiter = weight.sampled_grid.begin();
206 for (;iter != sampled_grid.end();++iter,++weightiter)
207 int_value += (*weightiter) * (*iter);
208 int_value *= volume_element;
209 //LOG(2, "DEBUG: SamplingGrid::integral() is " << scientific << setprecision(13) << int_value << ".");
210 return int_value;
211 } else
212 return 0.;
213}
214
215double SamplingGrid::getNearestLowerGridPoint(
216 const double value, const size_t axis) const
217{
218 const double length = end[axis] - begin[axis];
219 if ((fabs(length) < std::numeric_limits<double>::epsilon()) || (getGridPointsPerAxis() == 0)) {
220 return 0.;
221 } else {
222 const double offset = value - begin[axis];
223 const double factor = floor((double)getGridPointsPerAxis()*(offset/length));
224 return factor*(length/(double)getGridPointsPerAxis());
225 }
226}
227
228double SamplingGrid::getNearestHigherGridPoint(
229 const double value, const size_t axis) const
230{
231 const double length = end[axis] - begin[axis];
232 if ((fabs(length) < std::numeric_limits<double>::epsilon()) || (getGridPointsPerAxis() == 0)) {
233 return 0.;
234 } else {
235 const double offset = value - begin[axis];
236 const double factor = ceil((double)getGridPointsPerAxis()*(offset/length));
237 return factor*(length/(double)getGridPointsPerAxis());
238 }
239}
240
241void SamplingGrid::setWindowSize(
242 const double _begin_window[3],
243 const double _end_window[3])
244{
245 for (size_t index=0;index<3;++index) {
246 begin_window[index] = getNearestLowerGridPoint(_begin_window[index], index);
247 ASSERT( begin_window[index] >= begin[index],
248 "SamplingGrid::setWindowSize() - window starts earlier than domain on "
249 +toString(index)+"th component.");
250 end_window[index] = getNearestHigherGridPoint(_end_window[index], index);
251 ASSERT( end_window[index] <= end[index],
252 "SamplingGrid::setWindowSize() - window ends later than domain on "
253 +toString(index)+"th component.");
254 }
255}
256
257void SamplingGrid::setWindow(
258 const double _begin_window[3],
259 const double _end_window[3])
260{
261 setWindowSize(_begin_window, _end_window);
262 const size_t gridpoints_window = getWindowGridPoints();
263 sampled_grid.clear();
264 sampled_grid.resize(gridpoints_window, 0.);
265}
266
267void SamplingGrid::setDomain(
268 const double _begin[3],
269 const double _end[3])
270{
271 setDomainSize(_begin, _end);
272 setWindowSize(_begin, _end);
273 const size_t gridpoints = getTotalGridPoints();
274 sampled_grid.resize(gridpoints, 0.);
275}
276
277void SamplingGrid::extendWindow(
278 const double _begin_window[3],
279 const double _end_window[3])
280{
281#ifndef NDEBUG
282 for(size_t index=0;index < 3; ++index) {
283 // check that we truly have to extend the window
284 ASSERT ( begin_window[index] >= _begin_window[index],
285 "SamplingGrid::extendWindow() - component "+toString(index)+
286 " of window start is greater than old value.");
287 ASSERT ( end_window[index] <= _end_window[index],
288 "SamplingGrid::extendWindow() - component "+toString(index)+
289 " of window end is less than old value.");
290
291 // check that we are still less than domain
292 ASSERT ( _begin_window[index] >= begin[index],
293 "SamplingGrid::extendWindow() - component "+toString(index)+
294 " of window start is less than domain start.");
295 ASSERT ( _end_window[index] <= end[index],
296 "SamplingGrid::extendWindow() - component "+toString(index)+
297 " of window end is greater than domain end.");
298 }
299#endif
300 // copy old window size and values
301 double old_begin_window[3];
302 double old_end_window[3];
303 for(size_t index=0;index<3;++index) {
304 old_begin_window[index] = begin_window[index];
305 old_end_window[index] = end_window[index];
306 }
307 sampledvalues_t old_values(sampled_grid);
308 // set new window
309 setWindow(_begin_window,_end_window);
310 // now extend it ...
311 addOntoWindow(old_begin_window, old_end_window, old_values, +1.);
312 LOG(2, "DEBUG: Grid after extension is " << sampled_grid << ".");
313}
314
315void SamplingGrid::addOntoWindow(
316 const double _begin_window[3],
317 const double _end_window[3],
318 const sampledvalues_t &_sampled_grid,
319 const double prefactor)
320{
321#ifndef NDEBUG
322 for(size_t index=0;index<3;++index) {
323 ASSERT( _begin_window[index] >= begin_window[index],
324 "SamplingGrid::addOntoWindow() - given window starts earlier in component "
325 +toString(index)+".");
326 ASSERT( _end_window[index] <= end_window[index],
327 "SamplingGrid::addOntoWindow() - given window ends later in component "
328 +toString(index)+".");
329 }
330#endif
331 // the only issue are indices
332 const size_t gridpoints_axis = getGridPointsPerAxis();
333 size_t pre_offset[3];
334 size_t post_offset[3];
335 size_t length[3];
336 size_t total[3];
337 const double round_offset =
338 (std::numeric_limits<size_t>::round_style == std::round_toward_zero) ?
339 0.5 : 0.; // need offset to get to round_toward_nearest behavior
340 for(size_t index=0;index<3;++index) {
341 // we refrain from using floor/ceil as the window's starts and ends,
342 // the grids have to be compatible (equal level), should always be on
343 // discrete grid point locations.
344 const double delta = (double)gridpoints_axis/(end[index] - begin[index]);
345 // delta is conversion factor from box length to discrete length, i.e. number of points
346 pre_offset[index] = delta*(_begin_window[index] - begin_window[index])+round_offset;
347 length[index] = delta*(_end_window[index] - _begin_window[index])+round_offset;
348 post_offset[index] = delta*(end_window[index] - _end_window[index])+round_offset;
349 total[index] = delta*(end_window[index] - begin_window[index])+round_offset;
350 // total is used as safe-guard against loss due to discrete conversion
351 ASSERT( pre_offset[index]+post_offset[index]+length[index] == total[index],
352 "SamplingGrid::addOntoWindow() - pre, post, and length don't sum up to total for "
353 +toString(index)+"th component.");
354 }
355 // assert that calculated lengths match with given vector sizes
356#ifndef NDEBUG
357 const size_t calculated_size = length[0]*length[1]*length[2];
358 ASSERT( calculated_size == _sampled_grid.size(),
359 "SamplingGrid::addOntoWindow() - not enough sampled values given: "
360 +toString(calculated_size)+" != "+toString(_sampled_grid.size())+".");
361 ASSERT( calculated_size <= sampled_grid.size(),
362 "SamplingGrid::addOntoWindow() - not enough sampled values available: "
363 +toString(calculated_size)+" <= "+toString(sampled_grid.size())+".");
364 const size_t total_size = total[0]*total[1]*total[2];
365 ASSERT( total_size == sampled_grid.size(),
366 "SamplingGrid::addOntoWindow() - total size is not equal to number of present points: "
367 +toString(total_size)+" != "+toString(sampled_grid.size())+".");
368#endif
369 size_t N[3];
370// size_t counter = 0;
371 sampledvalues_t::iterator griditer = sampled_grid.begin();
372 std::advance(griditer, pre_offset[0]*total[1]*total[2]);
373 sampledvalues_t::const_iterator copyiter = _sampled_grid.begin();
374 for(N[0]=0; N[0] < length[0]; ++N[0]) {
375 std::advance(griditer, pre_offset[1]*total[2]);
376 for(N[1]=0; N[1] < length[1]; ++N[1]) {
377 std::advance(griditer, pre_offset[2]);
378 for(N[2]=0; N[2] < length[2]; ++N[2]) {
379 ASSERT( griditer != sampled_grid.end(),
380 "SamplingGrid::addOntoWindow() - griditer is already at end of window.");
381 ASSERT( copyiter != _sampled_grid.end(),
382 "SamplingGrid::addOntoWindow() - griditer is already at end of window.");
383 *griditer++ += prefactor*(*copyiter++);
384 }
385 std::advance(griditer, post_offset[2]);
386 }
387 std::advance(griditer, post_offset[1]*total[2]);
388 }
389#ifndef NDEBUG
390 std::advance(griditer, post_offset[0]*total[1]*total[2]);
391 ASSERT( griditer == sampled_grid.end(),
392 "SamplingGrid::addOntoWindow() - griditer is not at end of window.");
393 ASSERT( copyiter == _sampled_grid.end(),
394 "SamplingGrid::addOntoWindow() - copyiter is not at end of window.");
395#endif
396 LOG(2, "DEBUG: Grid after adding other is " << sampled_grid << ".");
397}
398
399std::ostream & operator<<(std::ostream &ost, const SamplingGrid& other)
400{
401 ost << "SamplingGrid";
402 ost << " starting at " << other.begin[0] << "," << other.begin[1] << "," << other.begin[2];
403 ost << " ending at " << other.end[0] << "," << other.end[1] << "," << other.end[2];
404 ost << ", window starting at " << other.begin_window[0] << "," << other.begin_window[1] << "," << other.begin_window[2];
405 ost << ", window ending at " << other.end_window[0] << "," << other.end_window[1] << "," << other.end_window[2];
406 ost << ", level of " << other.level;
407 ost << " and integrated value of " << other.integral();
408 return ost;
409}
410
411template<> SamplingGrid ZeroInstance<SamplingGrid>()
412{
413 SamplingGrid returnvalue;
414 return returnvalue;
415}
416
417// we need to explicitly instantiate the serialization functions as
418// its is only serialized through its base class FragmentJob
419BOOST_CLASS_EXPORT_IMPLEMENT(SamplingGrid)
Note: See TracBrowser for help on using the repository browser.