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

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

Added SamplingGrid::isCongruent().

  • also added unit test function.
  • Property mode set to 100644
File size: 16.2 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
113bool SamplingGrid::isCongruent(const SamplingGrid &_props) const
114{
115 bool status = true;
116 status &= (static_cast<const SamplingGridProperties &>(*this) ==
117 static_cast<const SamplingGridProperties &>(_props));
118 for(size_t i = 0; i<3; ++i) {
119 status &= begin_window[i] == _props.begin_window[i];
120 status &= end_window[i] == _props.end_window[i];
121 }
122 return status;
123}
124
125SamplingGrid& SamplingGrid::operator=(const SamplingGrid& other)
126{
127 // check for self-assignment
128 if (this != &other) {
129 static_cast<SamplingGridProperties &>(*this) = other;
130 setWindowSize(other.begin_window, other.end_window);
131 sampled_grid = other.sampled_grid;
132 }
133 return *this;
134}
135
136SamplingGrid& SamplingGrid::operator*=(const SamplingGrid& other)
137{
138 // check that grids are compatible
139 if (isCongruent(other)) {
140 sampledvalues_t::iterator iter = sampled_grid.begin();
141 sampledvalues_t::const_iterator otheriter = other.sampled_grid.begin();
142 for(; iter != sampled_grid.end(); ++iter, ++otheriter )
143 *iter *= (*otheriter);
144 } else {
145 ASSERT(0, "SamplingGrid::operator*=() - multiplying incongruent grids is so far not in the cards.");
146 }
147 return *this;
148}
149
150void SamplingGrid::superposeOtherGrids(const SamplingGrid &other, const double prefactor)
151{
152 /// check that grids are compatible
153 if (isCompatible(other)) {
154 /// get maximum of window
155 double max_begin_window[3];
156 double max_end_window[3];
157 bool doExtend = false;
158 for (size_t index=0; index<3;++index) {
159 if (begin_window[index] >= other.begin_window[index]) {
160 max_begin_window[index] = other.begin_window[index];
161 doExtend = true;
162 } else {
163 max_begin_window[index] = begin_window[index];
164 }
165 if (end_window[index] >= other.end_window[index]) {
166 max_end_window[index] = end_window[index];
167 } else {
168 max_end_window[index] = other.end_window[index];
169 doExtend = true;
170 }
171 }
172 LOG(2, "DEBUG: max begin is " << max_begin_window[0] << "," << max_begin_window[1] << "," << max_begin_window[2] << ".");
173 LOG(2, "DEBUG: max end is " << max_end_window[0] << "," << max_end_window[1] << "," << max_end_window[2] << ".");
174 if (doExtend)
175 extendWindow(max_begin_window, max_end_window);
176 /// and copy other into larger window, too
177 addOntoWindow(other.begin_window, other.end_window, other.sampled_grid, prefactor);
178 } else {
179 ASSERT(0, "SamplingGrid::superposeOtherGrids() - superposing incompatible grids is so far not in the cards.");
180 }
181}
182
183const size_t SamplingGrid::getWindowGridPointsPerAxis(const size_t axis) const
184{
185 static const double round_offset(
186 (std::numeric_limits<size_t>::round_style == std::round_toward_zero) ?
187 0.5 : 0.); // need offset to get to round_toward_nearest behavior
188// const double total = getTotalLengthPerAxis(axis);
189 const double delta = getDeltaPerAxis(axis);
190 if (delta == 0)
191 return 0;
192 const double length = getWindowLengthPerAxis(axis);
193 if (length == 0)
194 return 0;
195 return (size_t)(length/delta+round_offset);
196}
197
198double SamplingGrid::integral() const
199{
200 const double volume_element = getVolume()/(double)getTotalGridPoints();
201 double int_value = 0.;
202 for (sampledvalues_t::const_iterator iter = sampled_grid.begin();
203 iter != sampled_grid.end();
204 ++iter)
205 int_value += *iter;
206 int_value *= volume_element;
207 LOG(2, "DEBUG: SamplingGrid::integral() is " << scientific << setprecision(13) << int_value << ".");
208 return int_value;
209}
210
211double SamplingGrid::integral(const SamplingGrid &weight) const
212{
213 if (isCompatible(weight)) {
214 const double volume_element = getVolume()/(double)getTotalGridPoints();
215 double int_value = 0.;
216 sampledvalues_t::const_iterator iter = sampled_grid.begin();
217 sampledvalues_t::const_iterator weightiter = weight.sampled_grid.begin();
218 for (;iter != sampled_grid.end();++iter,++weightiter)
219 int_value += (*weightiter) * (*iter);
220 int_value *= volume_element;
221 //LOG(2, "DEBUG: SamplingGrid::integral() is " << scientific << setprecision(13) << int_value << ".");
222 return int_value;
223 } else
224 return 0.;
225}
226
227double SamplingGrid::getNearestLowerGridPoint(
228 const double value, const size_t axis) const
229{
230 const double length = end[axis] - begin[axis];
231 if ((fabs(length) < std::numeric_limits<double>::epsilon()) || (getGridPointsPerAxis() == 0)) {
232 return 0.;
233 } else {
234 const double offset = value - begin[axis];
235 // modify value a little if value actually has been on a grid point but
236 // perturbed by numerical rounding: here up, as we always go lower
237 const double factor =
238 floor((double)getGridPointsPerAxis()*(offset/length)
239 +std::numeric_limits<double>::epsilon()*1.e4);
240 return factor*(length/(double)getGridPointsPerAxis());
241 }
242}
243
244double SamplingGrid::getNearestHigherGridPoint(
245 const double value, const size_t axis) const
246{
247 const double length = end[axis] - begin[axis];
248 if ((fabs(length) < std::numeric_limits<double>::epsilon()) || (getGridPointsPerAxis() == 0)) {
249 return 0.;
250 } else {
251 const double offset = value - begin[axis];
252 // modify value a little if value actually has been on a grid point but
253 // perturbed by numerical rounding: here down, as we always go higher
254 const double factor =
255 ceil((double)getGridPointsPerAxis()*(offset/length)
256 -std::numeric_limits<double>::epsilon()*1.e4);
257 return factor*(length/(double)getGridPointsPerAxis());
258 }
259}
260
261void SamplingGrid::setWindowSize(
262 const double _begin_window[3],
263 const double _end_window[3])
264{
265 for (size_t index=0;index<3;++index) {
266 begin_window[index] = getNearestLowerGridPoint(_begin_window[index], index);
267 ASSERT( begin_window[index] >= begin[index],
268 "SamplingGrid::setWindowSize() - window starts earlier than domain on "
269 +toString(index)+"th component.");
270 end_window[index] = getNearestHigherGridPoint(_end_window[index], index);
271 ASSERT( end_window[index] <= end[index],
272 "SamplingGrid::setWindowSize() - window ends later than domain on "
273 +toString(index)+"th component.");
274 }
275}
276
277void SamplingGrid::setWindow(
278 const double _begin_window[3],
279 const double _end_window[3])
280{
281 setWindowSize(_begin_window, _end_window);
282 const size_t gridpoints_window = getWindowGridPoints();
283 sampled_grid.clear();
284 sampled_grid.resize(gridpoints_window, 0.);
285}
286
287void SamplingGrid::setDomain(
288 const double _begin[3],
289 const double _end[3])
290{
291 setDomainSize(_begin, _end);
292 setWindowSize(_begin, _end);
293 const size_t gridpoints = getTotalGridPoints();
294 sampled_grid.resize(gridpoints, 0.);
295}
296
297void SamplingGrid::extendWindow(
298 const double _begin_window[3],
299 const double _end_window[3])
300{
301#ifndef NDEBUG
302 for(size_t index=0;index < 3; ++index) {
303 // check that we truly have to extend the window
304 ASSERT ( begin_window[index] >= _begin_window[index],
305 "SamplingGrid::extendWindow() - component "+toString(index)+
306 " of window start is greater than old value.");
307 ASSERT ( end_window[index] <= _end_window[index],
308 "SamplingGrid::extendWindow() - component "+toString(index)+
309 " of window end is less than old value.");
310
311 // check that we are still less than domain
312 ASSERT ( _begin_window[index] >= begin[index],
313 "SamplingGrid::extendWindow() - component "+toString(index)+
314 " of window start is less than domain start.");
315 ASSERT ( _end_window[index] <= end[index],
316 "SamplingGrid::extendWindow() - component "+toString(index)+
317 " of window end is greater than domain end.");
318 }
319#endif
320 // copy old window size and values
321 double old_begin_window[3];
322 double old_end_window[3];
323 for(size_t index=0;index<3;++index) {
324 old_begin_window[index] = begin_window[index];
325 old_end_window[index] = end_window[index];
326 }
327 sampledvalues_t old_values(sampled_grid);
328 // set new window
329 setWindow(_begin_window,_end_window);
330 // now extend it ...
331 addOntoWindow(old_begin_window, old_end_window, old_values, +1.);
332 LOG(2, "DEBUG: Grid after extension is " << sampled_grid << ".");
333}
334
335void SamplingGrid::addOntoWindow(
336 const double _begin_window[3],
337 const double _end_window[3],
338 const sampledvalues_t &_sampled_grid,
339 const double prefactor)
340{
341#ifndef NDEBUG
342 for(size_t index=0;index<3;++index) {
343 ASSERT( _begin_window[index] >= begin_window[index],
344 "SamplingGrid::addOntoWindow() - given window starts earlier in component "
345 +toString(index)+".");
346 ASSERT( _end_window[index] <= end_window[index],
347 "SamplingGrid::addOntoWindow() - given window ends later in component "
348 +toString(index)+".");
349 }
350#endif
351 // the only issue are indices
352 const size_t gridpoints_axis = getGridPointsPerAxis();
353 size_t pre_offset[3];
354 size_t post_offset[3];
355 size_t length[3];
356 size_t total[3];
357 const double round_offset =
358 (std::numeric_limits<size_t>::round_style == std::round_toward_zero) ?
359 0.5 : 0.; // need offset to get to round_toward_nearest behavior
360 for(size_t index=0;index<3;++index) {
361 // we refrain from using floor/ceil as the window's starts and ends,
362 // the grids have to be compatible (equal level), should always be on
363 // discrete grid point locations.
364 const double delta = (double)gridpoints_axis/(end[index] - begin[index]);
365 // delta is conversion factor from box length to discrete length, i.e. number of points
366 pre_offset[index] = delta*(_begin_window[index] - begin_window[index])+round_offset;
367 length[index] = delta*(_end_window[index] - _begin_window[index])+round_offset;
368 post_offset[index] = delta*(end_window[index] - _end_window[index])+round_offset;
369 total[index] = delta*(end_window[index] - begin_window[index])+round_offset;
370 // total is used as safe-guard against loss due to discrete conversion
371 ASSERT( pre_offset[index]+post_offset[index]+length[index] == total[index],
372 "SamplingGrid::addOntoWindow() - pre, post, and length don't sum up to total for "
373 +toString(index)+"th component.");
374 }
375 // assert that calculated lengths match with given vector sizes
376#ifndef NDEBUG
377 const size_t calculated_size = length[0]*length[1]*length[2];
378 ASSERT( calculated_size == _sampled_grid.size(),
379 "SamplingGrid::addOntoWindow() - not enough sampled values given: "
380 +toString(calculated_size)+" != "+toString(_sampled_grid.size())+".");
381 ASSERT( calculated_size <= sampled_grid.size(),
382 "SamplingGrid::addOntoWindow() - not enough sampled values available: "
383 +toString(calculated_size)+" <= "+toString(sampled_grid.size())+".");
384 const size_t total_size = total[0]*total[1]*total[2];
385 ASSERT( total_size == sampled_grid.size(),
386 "SamplingGrid::addOntoWindow() - total size is not equal to number of present points: "
387 +toString(total_size)+" != "+toString(sampled_grid.size())+".");
388#endif
389 size_t N[3];
390// size_t counter = 0;
391 sampledvalues_t::iterator griditer = sampled_grid.begin();
392 std::advance(griditer, pre_offset[0]*total[1]*total[2]);
393 sampledvalues_t::const_iterator copyiter = _sampled_grid.begin();
394 for(N[0]=0; N[0] < length[0]; ++N[0]) {
395 std::advance(griditer, pre_offset[1]*total[2]);
396 for(N[1]=0; N[1] < length[1]; ++N[1]) {
397 std::advance(griditer, pre_offset[2]);
398 for(N[2]=0; N[2] < length[2]; ++N[2]) {
399 ASSERT( griditer != sampled_grid.end(),
400 "SamplingGrid::addOntoWindow() - griditer is already at end of window.");
401 ASSERT( copyiter != _sampled_grid.end(),
402 "SamplingGrid::addOntoWindow() - griditer is already at end of window.");
403 *griditer++ += prefactor*(*copyiter++);
404 }
405 std::advance(griditer, post_offset[2]);
406 }
407 std::advance(griditer, post_offset[1]*total[2]);
408 }
409#ifndef NDEBUG
410 std::advance(griditer, post_offset[0]*total[1]*total[2]);
411 ASSERT( griditer == sampled_grid.end(),
412 "SamplingGrid::addOntoWindow() - griditer is not at end of window.");
413 ASSERT( copyiter == _sampled_grid.end(),
414 "SamplingGrid::addOntoWindow() - copyiter is not at end of window.");
415#endif
416 LOG(2, "DEBUG: Grid after adding other is " << sampled_grid << ".");
417}
418
419std::ostream & operator<<(std::ostream &ost, const SamplingGrid& other)
420{
421 ost << "SamplingGrid";
422 ost << " starting at " << other.begin[0] << "," << other.begin[1] << "," << other.begin[2];
423 ost << " ending at " << other.end[0] << "," << other.end[1] << "," << other.end[2];
424 ost << ", window starting at " << other.begin_window[0] << "," << other.begin_window[1] << "," << other.begin_window[2];
425 ost << ", window ending at " << other.end_window[0] << "," << other.end_window[1] << "," << other.end_window[2];
426 ost << ", level of " << other.level;
427 ost << " and integrated value of " << other.integral();
428 return ost;
429}
430
431template<> SamplingGrid ZeroInstance<SamplingGrid>()
432{
433 SamplingGrid returnvalue;
434 return returnvalue;
435}
436
437// we need to explicitly instantiate the serialization functions as
438// its is only serialized through its base class FragmentJob
439BOOST_CLASS_EXPORT_IMPLEMENT(SamplingGrid)
Note: See TracBrowser for help on using the repository browser.