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

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

Refactored copy routine out of AddOntoWindow().

  • this is preparatory for preparing a shrinking and copying into a smaller window functionalities.
  • Property mode set to 100644
File size: 17.6 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 <boost/bind.hpp>
45#include <limits>
46
47#include "CodePatterns/Assert.hpp"
48#include "CodePatterns/Log.hpp"
49
50// static instances
51const double SamplingGrid::zeroOffset[3] = { 0., 0., 0. };
52
53SamplingGrid::SamplingGrid() :
54 SamplingGridProperties()
55{
56 setWindowSize(zeroOffset, zeroOffset);
57 ASSERT( getWindowGridPoints() == (size_t)0,
58 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
59}
60
61SamplingGrid::SamplingGrid(const double _begin[3],
62 const double _end[3],
63 const int _level) :
64 SamplingGridProperties(_begin, _end, _level)
65{
66 setWindowSize(zeroOffset, zeroOffset);
67 ASSERT( getWindowGridPoints() == (size_t)0,
68 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
69}
70
71SamplingGrid::SamplingGrid(const double _begin[3],
72 const double _end[3],
73 const int _level,
74 const sampledvalues_t &_sampled_grid) :
75 SamplingGridProperties(_begin, _end, _level),
76 sampled_grid(_sampled_grid)
77{
78 setWindowSize(_begin, _end);
79 ASSERT( getWindowGridPoints() == (size_t)_sampled_grid.size(),
80 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
81}
82
83SamplingGrid::SamplingGrid(const SamplingGrid &_grid) :
84 SamplingGridProperties(_grid),
85 sampled_grid(_grid.sampled_grid)
86{
87 setWindowSize(_grid.begin_window, _grid.end_window);
88 ASSERT( getWindowGridPoints() == _grid.getWindowGridPoints(),
89 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
90}
91
92SamplingGrid::SamplingGrid(const SamplingGridProperties &_props) :
93 SamplingGridProperties(_props)
94{
95 setWindowSize(zeroOffset, zeroOffset);
96 ASSERT( getWindowGridPoints() == (size_t)0,
97 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
98}
99
100SamplingGrid::SamplingGrid(
101 const SamplingGridProperties &_props,
102 const sampledvalues_t &_sampled_grid) :
103 SamplingGridProperties(_props),
104 sampled_grid(_sampled_grid)
105{
106 setWindowSize(_props.begin, _props.end);
107 ASSERT( getWindowGridPoints() == (size_t)_sampled_grid.size(),
108 "SamplingGrid::SamplingGrid() - incorrect number of samples given for the window.");
109}
110
111SamplingGrid::~SamplingGrid()
112{}
113
114bool SamplingGrid::isCongruent(const SamplingGrid &_props) const
115{
116 bool status = true;
117 status &= (static_cast<const SamplingGridProperties &>(*this) ==
118 static_cast<const SamplingGridProperties &>(_props));
119 for(size_t i = 0; i<3; ++i) {
120 status &= begin_window[i] == _props.begin_window[i];
121 status &= end_window[i] == _props.end_window[i];
122 }
123 return status;
124}
125
126SamplingGrid& SamplingGrid::operator=(const SamplingGrid& other)
127{
128 // check for self-assignment
129 if (this != &other) {
130 static_cast<SamplingGridProperties &>(*this) = other;
131 setWindowSize(other.begin_window, other.end_window);
132 sampled_grid = other.sampled_grid;
133 }
134 return *this;
135}
136
137SamplingGrid& SamplingGrid::operator*=(const SamplingGrid& other)
138{
139 // check that grids are compatible
140 if (isCongruent(other)) {
141 sampledvalues_t::iterator iter = sampled_grid.begin();
142 sampledvalues_t::const_iterator otheriter = other.sampled_grid.begin();
143 for(; iter != sampled_grid.end(); ++iter, ++otheriter )
144 *iter *= (*otheriter);
145 } else {
146 ASSERT(0, "SamplingGrid::operator*=() - multiplying incongruent grids is so far not in the cards.");
147 }
148 return *this;
149}
150
151void SamplingGrid::superposeOtherGrids(const SamplingGrid &other, const double prefactor)
152{
153 /// check that grids are compatible
154 if (isCompatible(other)) {
155 /// get maximum of window
156 double max_begin_window[3];
157 double max_end_window[3];
158 bool doExtend = false;
159 for (size_t index=0; index<3;++index) {
160 if (begin_window[index] >= other.begin_window[index]) {
161 max_begin_window[index] = other.begin_window[index];
162 doExtend = true;
163 } else {
164 max_begin_window[index] = begin_window[index];
165 }
166 if (end_window[index] >= other.end_window[index]) {
167 max_end_window[index] = end_window[index];
168 } else {
169 max_end_window[index] = other.end_window[index];
170 doExtend = true;
171 }
172 }
173 LOG(2, "DEBUG: max begin is " << max_begin_window[0] << "," << max_begin_window[1] << "," << max_begin_window[2] << ".");
174 LOG(2, "DEBUG: max end is " << max_end_window[0] << "," << max_end_window[1] << "," << max_end_window[2] << ".");
175 if (doExtend)
176 extendWindow(max_begin_window, max_end_window);
177 /// and copy other into larger window, too
178 addOntoWindow(other.begin_window, other.end_window, other.sampled_grid, prefactor);
179 } else {
180 ASSERT(0, "SamplingGrid::superposeOtherGrids() - superposing incompatible grids is so far not in the cards.");
181 }
182}
183
184const size_t SamplingGrid::getWindowGridPointsPerAxis(const size_t axis) const
185{
186 static const double round_offset(
187 (std::numeric_limits<size_t>::round_style == std::round_toward_zero) ?
188 0.5 : 0.); // need offset to get to round_toward_nearest behavior
189// const double total = getTotalLengthPerAxis(axis);
190 const double delta = getDeltaPerAxis(axis);
191 if (delta == 0)
192 return 0;
193 const double length = getWindowLengthPerAxis(axis);
194 if (length == 0)
195 return 0;
196 return (size_t)(length/delta+round_offset);
197}
198
199double SamplingGrid::integral() const
200{
201 const double volume_element = getVolume()/(double)getTotalGridPoints();
202 double int_value = 0.;
203 for (sampledvalues_t::const_iterator iter = sampled_grid.begin();
204 iter != sampled_grid.end();
205 ++iter)
206 int_value += *iter;
207 int_value *= volume_element;
208 LOG(2, "DEBUG: SamplingGrid::integral() is " << scientific << setprecision(13) << int_value << ".");
209 return int_value;
210}
211
212double SamplingGrid::integral(const SamplingGrid &weight) const
213{
214 if (isCompatible(weight)) {
215 const double volume_element = getVolume()/(double)getTotalGridPoints();
216 double int_value = 0.;
217 sampledvalues_t::const_iterator iter = sampled_grid.begin();
218 sampledvalues_t::const_iterator weightiter = weight.sampled_grid.begin();
219 for (;iter != sampled_grid.end();++iter,++weightiter)
220 int_value += (*weightiter) * (*iter);
221 int_value *= volume_element;
222 //LOG(2, "DEBUG: SamplingGrid::integral() is " << scientific << setprecision(13) << int_value << ".");
223 return int_value;
224 } else
225 return 0.;
226}
227
228double SamplingGrid::getNearestLowerGridPoint(
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 // modify value a little if value actually has been on a grid point but
237 // perturbed by numerical rounding: here up, as we always go lower
238 const double factor =
239 floor((double)getGridPointsPerAxis()*(offset/length)
240 +std::numeric_limits<double>::epsilon()*1.e4);
241 return factor*(length/(double)getGridPointsPerAxis());
242 }
243}
244
245double SamplingGrid::getNearestHigherGridPoint(
246 const double value, const size_t axis) const
247{
248 const double length = end[axis] - begin[axis];
249 if ((fabs(length) < std::numeric_limits<double>::epsilon()) || (getGridPointsPerAxis() == 0)) {
250 return 0.;
251 } else {
252 const double offset = value - begin[axis];
253 // modify value a little if value actually has been on a grid point but
254 // perturbed by numerical rounding: here down, as we always go higher
255 const double factor =
256 ceil((double)getGridPointsPerAxis()*(offset/length)
257 -std::numeric_limits<double>::epsilon()*1.e4);
258 return factor*(length/(double)getGridPointsPerAxis());
259 }
260}
261
262void SamplingGrid::setWindowSize(
263 const double _begin_window[3],
264 const double _end_window[3])
265{
266 for (size_t index=0;index<3;++index) {
267 begin_window[index] = getNearestLowerGridPoint(_begin_window[index], index);
268 ASSERT( begin_window[index] >= begin[index],
269 "SamplingGrid::setWindowSize() - window starts earlier than domain on "
270 +toString(index)+"th component.");
271 end_window[index] = getNearestHigherGridPoint(_end_window[index], index);
272 ASSERT( end_window[index] <= end[index],
273 "SamplingGrid::setWindowSize() - window ends later than domain on "
274 +toString(index)+"th component.");
275 }
276}
277
278void SamplingGrid::setWindow(
279 const double _begin_window[3],
280 const double _end_window[3])
281{
282 setWindowSize(_begin_window, _end_window);
283 const size_t gridpoints_window = getWindowGridPoints();
284 sampled_grid.clear();
285 sampled_grid.resize(gridpoints_window, 0.);
286}
287
288void SamplingGrid::setDomain(
289 const double _begin[3],
290 const double _end[3])
291{
292 setDomainSize(_begin, _end);
293 setWindowSize(_begin, _end);
294 const size_t gridpoints = getTotalGridPoints();
295 sampled_grid.resize(gridpoints, 0.);
296}
297
298void SamplingGrid::extendWindow(
299 const double _begin_window[3],
300 const double _end_window[3])
301{
302#ifndef NDEBUG
303 for(size_t index=0;index < 3; ++index) {
304 // check that we truly have to extend the window
305 ASSERT ( begin_window[index] >= _begin_window[index],
306 "SamplingGrid::extendWindow() - component "+toString(index)+
307 " of window start is greater than old value.");
308 ASSERT ( end_window[index] <= _end_window[index],
309 "SamplingGrid::extendWindow() - component "+toString(index)+
310 " of window end is less than old value.");
311
312 // check that we are still less than domain
313 ASSERT ( _begin_window[index] >= begin[index],
314 "SamplingGrid::extendWindow() - component "+toString(index)+
315 " of window start is less than domain start.");
316 ASSERT ( _end_window[index] <= end[index],
317 "SamplingGrid::extendWindow() - component "+toString(index)+
318 " of window end is greater than domain end.");
319 }
320#endif
321 // copy old window size and values
322 double old_begin_window[3];
323 double old_end_window[3];
324 for(size_t index=0;index<3;++index) {
325 old_begin_window[index] = begin_window[index];
326 old_end_window[index] = end_window[index];
327 }
328 sampledvalues_t old_values(sampled_grid);
329 // set new window
330 setWindow(_begin_window,_end_window);
331 // now extend it ...
332 addOntoWindow(old_begin_window, old_end_window, old_values, +1.);
333 LOG(2, "DEBUG: Grid after extension is " << sampled_grid << ".");
334}
335
336static void addElements(
337 double &dest,
338 const double &source,
339 const double prefactor)
340{
341 dest += prefactor*(source);
342}
343
344void SamplingGrid::addOntoWindow(
345 const double _begin_window[3],
346 const double _end_window[3],
347 const sampledvalues_t &_sampled_grid,
348 const double prefactor)
349{
350 addWindowOntoWindow(
351 begin_window,
352 end_window,
353 _begin_window,
354 _end_window,
355 sampled_grid,
356 _sampled_grid,
357 boost::bind(addElements, _1, _2, boost::cref(prefactor)),
358 thiswindow);
359}
360
361void SamplingGrid::addWindowOntoWindow(
362 const double wbegin[3],
363 const double wend[3],
364 const double other_wbegin[3],
365 const double other_wend[3],
366 sampledvalues_t &sampled_grid,
367 const sampledvalues_t &other_sampled_grid,
368 boost::function<void (double &, const double &)> op,
369 enum LargerWindow choice)
370{
371#ifndef NDEBUG
372 for(size_t index=0;index<3;++index) {
373 ASSERT( other_wbegin[index] >= wbegin[index],
374 "SamplingGrid::addWindowOntoWindow() - given smaller window starts earlier than larger window in component "
375 +toString(index)+".");
376 ASSERT( other_wend[index] <= wend[index],
377 "SamplingGrid::addWindowOntoWindow() - given smaller window ends later than larger window in component "
378 +toString(index)+".");
379 }
380#endif
381 // the only issue are indices
382 const size_t gridpoints_axis = getGridPointsPerAxis();
383 size_t pre_offset[3];
384 size_t post_offset[3];
385 size_t length[3];
386 size_t total[3];
387 const double round_offset =
388 (std::numeric_limits<size_t>::round_style == std::round_toward_zero) ?
389 0.5 : 0.; // need offset to get to round_toward_nearest behavior
390 for(size_t index=0;index<3;++index) {
391 // we refrain from using floor/ceil as the window's starts and ends,
392 // the grids have to be compatible (equal level), should always be on
393 // discrete grid point locations.
394 const double delta = (double)gridpoints_axis/(end[index] - begin[index]);
395 // delta is conversion factor from box length to discrete length, i.e. number of points
396 pre_offset[index] = delta*(other_wbegin[index] - wbegin[index])+round_offset;
397 length[index] = delta*(other_wend[index] - other_wbegin[index])+round_offset;
398 post_offset[index] = delta*(wend[index] - other_wend[index])+round_offset;
399 total[index] = delta*(wend[index] - wbegin[index])+round_offset;
400 // total is used as safe-guard against loss due to discrete conversion
401 ASSERT( pre_offset[index]+post_offset[index]+length[index] == total[index],
402 "SamplingGrid::addWindowOntoWindow() - pre, post, and length don't sum up to total for "
403 +toString(index)+"th component.");
404 }
405 // assert that calculated lengths match with given vector sizes
406#ifndef NDEBUG
407 const size_t calculated_size = length[0]*length[1]*length[2];
408 ASSERT( calculated_size == other_sampled_grid.size(),
409 "SamplingGrid::addWindowOntoWindow() - not enough sampled values given: "
410 +toString(calculated_size)+" != "+toString(other_sampled_grid.size())+".");
411 ASSERT( calculated_size <= sampled_grid.size(),
412 "SamplingGrid::addWindowOntoWindow() - not enough sampled values available: "
413 +toString(calculated_size)+" <= "+toString(sampled_grid.size())+".");
414 const size_t total_size = total[0]*total[1]*total[2];
415 ASSERT( total_size == sampled_grid.size(),
416 "SamplingGrid::addWindowOntoWindow() - total size is not equal to number of present points: "
417 +toString(total_size)+" != "+toString(sampled_grid.size())+".");
418#endif
419 size_t N[3];
420// size_t counter = 0;
421 sampledvalues_t::iterator griditer = sampled_grid.begin();
422 sampledvalues_t::const_iterator copyiter = other_sampled_grid.begin();
423 if (choice == thiswindow)
424 std::advance(griditer, pre_offset[0]*total[1]*total[2]);
425 else
426 std::advance(copyiter, pre_offset[0]*total[1]*total[2]);
427 for(N[0]=0; N[0] < length[0]; ++N[0]) {
428 if (choice == thiswindow)
429 std::advance(griditer, pre_offset[1]*total[2]);
430 else
431 std::advance(copyiter, pre_offset[1]*total[2]);
432 for(N[1]=0; N[1] < length[1]; ++N[1]) {
433 if (choice == thiswindow)
434 std::advance(griditer, pre_offset[2]);
435 else
436 std::advance(copyiter, pre_offset[2]);
437 for(N[2]=0; N[2] < length[2]; ++N[2]) {
438 ASSERT( griditer != sampled_grid.end(),
439 "SamplingGrid::addWindowOntoWindow() - griditer is already at end of window.");
440 ASSERT( copyiter != other_sampled_grid.end(),
441 "SamplingGrid::addWindowOntoWindow() - griditer is already at end of window.");
442 op(*griditer, *copyiter);
443 ++griditer;
444 ++copyiter;
445 }
446 if (choice == thiswindow)
447 std::advance(griditer, post_offset[2]);
448 else
449 std::advance(copyiter, post_offset[2]);
450 }
451 if (choice == thiswindow)
452 std::advance(griditer, post_offset[1]*total[2]);
453 else
454 std::advance(copyiter, post_offset[1]*total[2]);
455 }
456#ifndef NDEBUG
457 if (choice == thiswindow)
458 std::advance(griditer, post_offset[0]*total[1]*total[2]);
459 else
460 std::advance(copyiter, post_offset[0]*total[1]*total[2]);
461 ASSERT( griditer == sampled_grid.end(),
462 "SamplingGrid::addWindowOntoWindow() - griditer is not at end of window.");
463 ASSERT( copyiter == other_sampled_grid.end(),
464 "SamplingGrid::addWindowOntoWindow() - copyiter is not at end of window.");
465#endif
466 LOG(2, "DEBUG: Grid after adding other is " << sampled_grid << ".");
467}
468
469std::ostream & operator<<(std::ostream &ost, const SamplingGrid& other)
470{
471 ost << "SamplingGrid";
472 ost << " starting at " << other.begin[0] << "," << other.begin[1] << "," << other.begin[2];
473 ost << " ending at " << other.end[0] << "," << other.end[1] << "," << other.end[2];
474 ost << ", window starting at " << other.begin_window[0] << "," << other.begin_window[1] << "," << other.begin_window[2];
475 ost << ", window ending at " << other.end_window[0] << "," << other.end_window[1] << "," << other.end_window[2];
476 ost << ", level of " << other.level;
477 ost << " and integrated value of " << other.integral();
478 return ost;
479}
480
481template<> SamplingGrid ZeroInstance<SamplingGrid>()
482{
483 SamplingGrid returnvalue;
484 return returnvalue;
485}
486
487// we need to explicitly instantiate the serialization functions as
488// its is only serialized through its base class FragmentJob
489BOOST_CLASS_EXPORT_IMPLEMENT(SamplingGrid)
Note: See TracBrowser for help on using the repository browser.