source: src/LinkedCell/LinkedCell_Controller.cpp@ 6ff62c

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

Fixing minimum sensible length for LinkedCell_Controller.

  • we did use the minimum sensible length for getBestModel() but not for the actual creation.
  • extracted code into function getSensibleMinimumLength().
  • fixed (and documented) formula for calculating min_distance.
  • we also can now also deal with systems that are mostly 2d or 1d.
  • Property mode set to 100644
File size: 15.9 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 * LinkedCell_Controller.cpp
25 *
26 * Created on: Nov 15, 2011
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "CodePatterns/MemDebug.hpp"
36
37#include <set>
38
39#include "Box.hpp"
40#include "CodePatterns/Assert.hpp"
41#include "CodePatterns/Log.hpp"
42#include "CodePatterns/Observer/Notification.hpp"
43#include "CodePatterns/Range.hpp"
44#include "LinkedCell_Controller.hpp"
45#include "LinkedCell_Model.hpp"
46#include "LinkedCell_View.hpp"
47#include "LinkedCell_View_ModelWrapper.hpp"
48#include "IPointCloud.hpp"
49#include "WorldTime.hpp"
50
51
52using namespace LinkedCell;
53
54double LinkedCell_Controller::lower_threshold = 1.;
55double LinkedCell_Controller::upper_threshold = 20.;
56
57/** Constructor of class LinkedCell_Controller.
58 *
59 */
60LinkedCell_Controller::LinkedCell_Controller(const Box &_domain) :
61 Observer("LinkedCell_Controller"),
62 domain(_domain)
63{
64 // sign on to specific notifications
65 domain.signOn(this, Box::MatrixChanged);
66 WorldTime::getInstance().signOn(this, WorldTime::TimeChanged);
67
68 /// Check that upper_threshold fits within half the box.
69 Vector diagonal(1.,1.,1.);
70 diagonal.Scale(upper_threshold);
71 Vector diagonal_transformed = domain.getMinv() * diagonal;
72 double max_factor = 1.;
73 for (size_t i=0; i<NDIM; ++i)
74 if (diagonal_transformed.at(i) > 1./max_factor)
75 max_factor = 1./diagonal_transformed.at(i);
76 upper_threshold *= max_factor;
77
78 /// Check that lower_threshold is still lower, if not set to half times upper_threshold.
79 if (lower_threshold > upper_threshold)
80 lower_threshold = 0.5*upper_threshold;
81}
82
83/** Destructor of class LinkedCell_Controller.
84 *
85 * Here, we free all LinkedCell_Model instances again.
86 *
87 */
88LinkedCell_Controller::~LinkedCell_Controller()
89{
90 // sign off
91 domain.signOff(this, Box::MatrixChanged);
92 WorldTime::getInstance().signOff(this, WorldTime::TimeChanged);
93
94 /// we free all LinkedCell_Model instances again.
95 for(MapEdgelengthModel::iterator iter = ModelsMap.begin();
96 !ModelsMap.empty(); iter = ModelsMap.begin()) {
97 delete iter->second;
98 ModelsMap.erase(iter);
99 }
100}
101
102/** Internal function to obtain the range within which an model is suitable.
103 *
104 * \note We use statics lower_threshold and upper_threshold as min and max
105 * boundaries.
106 *
107 * @param distance desired egde length
108 * @return range within which model edge length is acceptable
109 */
110const range<double> LinkedCell_Controller::getHeuristicRange(const double distance) const
111{
112 const double lower = 0.5*distance < lower_threshold ? lower_threshold : 0.5*distance;
113 const double upper = 2.*distance > upper_threshold ? upper_threshold : 2.*distance;
114 range<double> HeuristicInterval(lower, upper);
115 return HeuristicInterval;
116}
117
118static size_t checkLengthsLess(
119 const Vector &Lengths,
120 const double min_distance)
121{
122 size_t counter=0;
123 for (size_t i=0;i<NDIM;++i) {
124 if (Lengths[i] < min_distance)
125 ++counter;
126 }
127 return counter;
128}
129
130/** Given some given \a distance return it such that it is larger equal than some minimum
131 * sensible value with respect to the current domain.
132 *
133 * The sensible minimum distance \f$\Delta\f$ is computed as follows:
134 * \f$ \frac {l_1} \Delta \frac {l_2} \Delta \frac {l_3} \Delta \leq M \f$, where M is the
135 * maximum number of linked cells. Where some additional thought must be given
136 * to rounding issues. Hence, we calculate \f$ (\frac {l_i} d)^{\frac 1 d}+.5\f$,
137 * where d is the assumed dimensionality of the domain: d=3 for cubic, d=2 for
138 * a planar, d=1 for a bar-like system.
139 *
140 * \param distance distance compared with minimum value
141 * \return minimum sensible value or \a distance if larger
142 */
143double LinkedCell_Controller::getMinimumSensibleLength(double distance) const
144{
145 // first check the box with respect to the given distance
146 // as we must not generate more than 10^3 cells per axis due to
147 // memory constraints
148 const RealSpaceMatrix &M = domain.getM();
149 RealSpaceMatrix UnitMatrix;
150 UnitMatrix.setIdentity();
151 UnitMatrix *= M;
152 Vector Lengths = UnitMatrix.transformToEigenbasis();
153 double max_length = 0.;
154 double volume = 1.;
155 double min_distance = lower_threshold;
156 for (size_t dim=NDIM; dim>0; --dim) {
157 const double fraction = pow(MAX_LINKEDCELLNODES+1., 1./(double)dim);
158 for (size_t i=0;i<NDIM;++i) {
159 max_length = std::max(Lengths[i], max_length);
160 // the length dropping out for dimensionality less than 3 must appear
161 // just as factor of 1 not less.
162 if (Lengths[i] < min_distance)
163 volume *= pow(min_distance, 1./(double)dim)+.5;
164 else
165 volume *= pow(Lengths[i], 1./(double)dim)+.5; //.5 for rounding issues
166 }
167 min_distance = volume/fraction;
168 // assuming a (cubic-like) 3d system
169 if (checkLengthsLess(Lengths, min_distance) == 0)
170 break;
171 }
172 if (distance < min_distance) {
173 LOG(1, "INFO: Setting LC distance from given " << distance
174 << " to " << min_distance << " due to box size.");
175 distance = min_distance;
176 }
177 return distance;
178}
179
180/** Internal function to decide whether a suitable model is present or not.
181 *
182 * Here, the heuristic for deciding whether a new linked cell structure has to
183 * be constructed or not is implemented. The current heuristic is as follows:
184 * -# the best model should have at least half the desired length (such
185 * that most we have to look two neighbor shells wide and not one).
186 * -# the best model should have at most twice the desired length but
187 * no less than 1 angstroem.
188 *
189 * \note Dealing out a pointer is here (hopefully) safe because the function is
190 * internal and we - inside this class - know what we are doing.
191 *
192 * @param distance edge length of the requested linked cell structure
193 * @return NULL - there is no fitting LinkedCell_Model, else - pointer to instance
194 */
195const LinkedCell_Model *LinkedCell_Controller::getBestModel(double distance) const
196{
197 /// Bound distance to be within [lower_threshold, upper_threshold).
198 /// Note that we need to stay away from upper boundary a bit,
199 /// otherwise the distance will end up outside of the interval.
200 if (distance < lower_threshold)
201 distance = lower_threshold;
202 if (distance > upper_threshold)
203 distance = upper_threshold - std::numeric_limits<double>::round_error();
204
205 /// Look for all models within [0.5 distance, 2. distance).
206 MapEdgelengthModel::const_iterator bestmatch = ModelsMap.end();
207 if (!ModelsMap.empty()) {
208 for(MapEdgelengthModel::const_iterator iter = ModelsMap.begin();
209 iter != ModelsMap.end(); ++iter) {
210 // check that we are truely within range
211 range<double> HeuristicInterval(getHeuristicRange(iter->first));
212 if (HeuristicInterval.isInRange(distance)) {
213 // if it's the first match or a closer one, pick
214 if ((bestmatch == ModelsMap.end())
215 || (fabs(bestmatch->first - distance) > fabs(iter->first - distance)))
216 bestmatch = iter;
217 }
218 }
219 }
220
221 /// Return best match or NULL if none found.
222 if (bestmatch != ModelsMap.end())
223 return bestmatch->second;
224 else
225 return NULL;
226}
227
228/** Internal function to insert a new model and check for valid insertion.
229 *
230 * @param distance edge length of new model
231 * @param instance pointer to model
232 */
233void LinkedCell_Controller::insertNewModel(const double edgelength, const LinkedCell_Model* instance)
234{
235 std::pair< MapEdgelengthModel::iterator, bool> inserter =
236 ModelsMap.insert( std::make_pair(edgelength, instance) );
237 ASSERT(inserter.second,
238 "LinkedCell_Controller::getView() - LinkedCell_Model instance with distance "
239 +toString(edgelength)+" already present.");
240}
241
242/** Returns the a suitable LinkedCell_Model contained in a LinkedCell_View
243 * for the requested \a distance.
244 *
245 * \sa getBestModel()
246 *
247 * @param distance edge length of the requested linked cell structure
248 * @param set of initial points to insert when new model is created (not always), should be World's
249 * @return LinkedCell_View wrapping the best LinkedCell_Model
250 */
251LinkedCell_View LinkedCell_Controller::getView(const double distance, IPointCloud &set)
252{
253 // distance should be a given minimum length dependent on domain at least
254 const double ConstraintDistance = getMinimumSensibleLength(distance);
255
256 /// Look for best instance.
257 const LinkedCell_Model * const LCModel_best = getBestModel(ConstraintDistance);
258
259 /// Construct new instance if none found,
260 if (LCModel_best == NULL) {
261 LinkedCell_Model * const LCModel_new = new LinkedCell_Model(ConstraintDistance, domain);
262 LCModel_new->insertPointCloud(set);
263 insertNewModel(ConstraintDistance, LCModel_new);
264 LinkedCell_View view(*LCModel_new);
265 return view;
266 } else {
267 /// else construct interface and return.
268 LinkedCell_View view(*LCModel_best);
269 return view;
270 }
271}
272
273/** Internal function to re-create all present and used models for the new Box.
274 *
275 * This is necessary in the following cases:
276 * -# the Box is changed
277 * -# we step on to a different time step, i.e. all atomic positions change
278 *
279 * The main problem are the views currently in use.
280 *
281 * We make use of LinkedCell:LinkedCell_View::RAIIMap as there all present are
282 * listed. We go through the list, create a map with old model ref as keys to
283 * just newly created ones, and finally go again through each view and exchange
284 * the model against the new ones via a simple map lookup.
285 *
286 */
287void LinkedCell_Controller::updateModels()
288{
289 LOG(1, "INFO: Updating all models.");
290
291 typedef std::map<const LinkedCell_Model *, LinkedCell_Model *> ModelLookup;
292 ModelLookup models;
293
294 // set up map, for now with NULL pointers
295 for (LinkedCell_View::ModelInstanceMap::const_iterator iter = LinkedCell_View::RAIIMap.begin();
296 iter != LinkedCell_View::RAIIMap.end(); ++iter) {
297#ifndef NDEBUG
298 std::pair< ModelLookup::iterator, bool > inserter =
299#endif
300 models.insert( std::pair<const LinkedCell_Model *, LinkedCell_Model *>( (*iter)->LC->getModel(), NULL) );
301 LOG(2, "INFO: Added " << (*iter)->LC->getModel() << " to list of models to replace.");
302 ASSERT( inserter.second,
303 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - failed to insert old model "
304 +toString( (*iter)->LC->getModel() )+",NULL into models, is already present");
305 }
306
307 // invert MapEdgelengthModel
308 LOG(2, "INFO: ModelsMap is " << ModelsMap << ".");
309 typedef std::map<const LinkedCell_Model*, double > MapEdgelengthModel_inverted;
310 MapEdgelengthModel_inverted ModelsMap_inverted;
311 for (MapEdgelengthModel::const_iterator iter = ModelsMap.begin();
312 iter != ModelsMap.end(); ++iter) {
313#ifndef NDEBUG
314 MapEdgelengthModel_inverted::const_iterator assertiter = ModelsMap_inverted.find(iter->second);
315 ASSERT( assertiter == ModelsMap_inverted.end(),
316 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - ModelsMap is not invertible, value "
317 +toString(iter->second)+" is already present.");
318#endif
319 ModelsMap_inverted.insert( std::make_pair(iter->second, iter->first) );
320 }
321 LOG(2, "INFO: Inverted ModelsMap is " << ModelsMap_inverted << ".");
322
323 // go through map and re-create models
324 for (ModelLookup::iterator iter = models.begin(); iter != models.end(); ++iter) {
325 // delete old model
326 const LinkedCell_Model * const oldref = iter->first;
327#ifndef NDEBUG
328 MapEdgelengthModel_inverted::const_iterator assertiter = ModelsMap_inverted.find(oldref);
329 ASSERT( assertiter != ModelsMap_inverted.end(),
330 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - ModelsMap_inverted does not contain old model "
331 +toString(oldref)+".");
332#endif
333 const double distance = ModelsMap_inverted[oldref];
334 // create new one, afterwards erase old model (this is for unit test to get different memory addresses)
335 LinkedCell_Model * const newref = new LinkedCell_Model(distance, domain);
336 MapEdgelengthModel::iterator oldmodeliter = ModelsMap.find(distance);
337 delete oldmodeliter->second;
338 ModelsMap.erase(oldmodeliter);
339 LOG(2, "INFO: oldref is " << oldref << ", newref is " << newref << ".");
340 iter->second = newref;
341 // replace in ModelsMap
342#ifndef NDEBUG
343 std::pair< MapEdgelengthModel::iterator, bool > inserter =
344#endif
345 ModelsMap.insert( std::make_pair(distance, newref) );
346 ASSERT( inserter.second,
347 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - failed to insert new model "
348 +toString(distance)+","+toString(newref)+" into ModelsMap, is already present");
349 }
350
351 // remove all remaining active models (also those that don't have an active View on them)
352 for (MapEdgelengthModel::iterator iter = ModelsMap.begin();
353 !ModelsMap.empty();
354 iter = ModelsMap.begin()) {
355 delete iter->second;
356 ModelsMap.erase(iter);
357 }
358
359
360 // delete inverted map for safety (values are gone)
361 ModelsMap_inverted.clear();
362
363 // go through views and exchange the models
364 for (LinkedCell_View::ModelInstanceMap::const_iterator iter = LinkedCell_View::RAIIMap.begin();
365 iter != LinkedCell_View::RAIIMap.end(); ++iter) {
366 ModelLookup::const_iterator modeliter = models.find((*iter)->LC->getModel());
367 ASSERT( modeliter != models.end(),
368 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - we miss a model "
369 +toString((*iter)->LC->getModel())+" in ModelLookup.");
370 // this is ugly but the only place where we have to set ourselves over the constness of the member variable
371 if (modeliter != models.end()) {
372 LOG(2, "INFO: Setting model to " << modeliter->second << " in view " << *iter << ".");
373 (*iter)->LC->setModel(modeliter->second);
374 }
375 }
376}
377
378/** Callback function for Observer mechanism.
379 *
380 * @param publisher reference to the Observable that calls
381 */
382void LinkedCell_Controller::update(Observable *publisher)
383{
384 ELOG(2, "LinkedCell_Model received inconclusive general update from "
385 << publisher << ".");
386}
387
388/** Callback function for the Notifications mechanism.
389 *
390 * @param publisher reference to the Observable that calls
391 * @param notification specific notification as cause of the call
392 */
393void LinkedCell_Controller::recieveNotification(Observable *publisher, Notification_ptr notification)
394{
395 if (publisher == &domain) {
396 switch(notification->getChannelNo()) {
397 case Box::MatrixChanged:
398 LOG(1, "INFO: LinkedCell_Controller got update from Box.");
399 updateModels();
400 break;
401 default:
402 ASSERT(0,
403 "LinkedCell_Controller::recieveNotification() - unwanted notification from Box "
404 +toString(notification->getChannelNo())+" received.");
405 break;
406 }
407 } else if (publisher == WorldTime::getPointer()) {
408 switch(notification->getChannelNo()) {
409 case WorldTime::TimeChanged:
410 LOG(1, "INFO: LinkedCell_Controller got update from WorldTime.");
411 updateModels();
412 break;
413 default:
414 ASSERT(0,
415 "LinkedCell_Controller::recieveNotification() - unwanted notification from WorldTime "
416 +toString(notification->getChannelNo())+" received.");
417 break;
418 }
419 } else {
420 ELOG(1, "Notification " << notification->getChannelNo()
421 << " from unknown publisher " << publisher << ".");
422 }
423}
424
425/** Callback function when an Observer dies.
426 *
427 * @param publisher reference to the Observable that calls
428 */
429void LinkedCell_Controller::subjectKilled(Observable *publisher)
430{}
431
Note: See TracBrowser for help on using the repository browser.