source: src/LinkedCell/LinkedCell_Controller.cpp@ d5b90b

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

Extended LinkedCell_Controller::getBestModel() to take box into account.

  • We now limit the number of cells for all models to at most 103 cells per axis.
  • Property mode set to 100644
File size: 14.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 * 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
118/** Internal function to decide whether a suitable model is present or not.
119 *
120 * Here, the heuristic for deciding whether a new linked cell structure has to
121 * be constructed or not is implemented. The current heuristic is as follows:
122 * -# the best model should have at least half the desired length (such
123 * that most we have to look two neighbor shells wide and not one).
124 * -# the best model should have at most twice the desired length but
125 * no less than 1 angstroem.
126 *
127 * \note Dealing out a pointer is here (hopefully) safe because the function is
128 * internal and we - inside this class - know what we are doing.
129 *
130 * @param distance edge length of the requested linked cell structure
131 * @return NULL - there is no fitting LinkedCell_Model, else - pointer to instance
132 */
133const LinkedCell_Model *LinkedCell_Controller::getBestModel(double distance) const
134{
135 // first check the box with respect to the given distance
136 // as we must not generate more than 10^3 cells per axis due to
137 // memory constraints
138 const RealSpaceMatrix &M = domain.getM();
139 RealSpaceMatrix UnitMatrix;
140 UnitMatrix.setIdentity();
141 UnitMatrix *= M;
142 Vector Lengths = UnitMatrix.transformToEigenbasis();
143 double min_distance = std::numeric_limits<double>::max();
144 double max_length = 0.;
145 for (size_t i=0;i<NDIM;++i) {
146 min_distance = std::min(Lengths[i], min_distance);
147 max_length = std::max(Lengths[i], max_length);
148 }
149 min_distance *= 1e-3; // at most 1000 cells per axis
150 if (distance < min_distance) {
151 LOG(1, "INFO: Setting LC distance from given " << distance
152 << " to " << min_distance << " due to box size.");
153 distance = min_distance;
154 }
155
156 /// Bound distance to be within [lower_threshold, upper_threshold).
157 /// Note that we need to stay away from upper boundary a bit,
158 /// otherwise the distance will end up outside of the interval.
159 if (distance < lower_threshold)
160 distance = lower_threshold;
161 if (distance > max_length)
162 distance = max_length - std::numeric_limits<double>::round_error();
163
164 /// Look for all models within [0.5 distance, 2. distance).
165 MapEdgelengthModel::const_iterator bestmatch = ModelsMap.end();
166 if (!ModelsMap.empty()) {
167 for(MapEdgelengthModel::const_iterator iter = ModelsMap.begin();
168 iter != ModelsMap.end(); ++iter) {
169 // check that we are truely within range
170 range<double> HeuristicInterval(getHeuristicRange(iter->first));
171 if (HeuristicInterval.isInRange(distance)) {
172 // if it's the first match or a closer one, pick
173 if ((bestmatch == ModelsMap.end())
174 || (fabs(bestmatch->first - distance) > fabs(iter->first - distance)))
175 bestmatch = iter;
176 }
177 }
178 }
179
180 /// Return best match or NULL if none found.
181 if (bestmatch != ModelsMap.end())
182 return bestmatch->second;
183 else
184 return NULL;
185}
186
187/** Internal function to insert a new model and check for valid insertion.
188 *
189 * @param distance edge length of new model
190 * @param instance pointer to model
191 */
192void LinkedCell_Controller::insertNewModel(const double edgelength, const LinkedCell_Model* instance)
193{
194 std::pair< MapEdgelengthModel::iterator, bool> inserter =
195 ModelsMap.insert( std::make_pair(edgelength, instance) );
196 ASSERT(inserter.second,
197 "LinkedCell_Controller::getView() - LinkedCell_Model instance with distance "
198 +toString(edgelength)+" already present.");
199}
200
201/** Returns the a suitable LinkedCell_Model contained in a LinkedCell_View
202 * for the requested \a distance.
203 *
204 * \sa getBestModel()
205 *
206 * @param distance edge length of the requested linked cell structure
207 * @param set of initial points to insert when new model is created (not always), should be World's
208 * @return LinkedCell_View wrapping the best LinkedCell_Model
209 */
210LinkedCell_View LinkedCell_Controller::getView(const double distance, IPointCloud &set)
211{
212 /// Look for best instance.
213 const LinkedCell_Model * const LCModel_best = getBestModel(distance);
214
215 /// Construct new instance if none found,
216 if (LCModel_best == NULL) {
217 LinkedCell_Model * const LCModel_new = new LinkedCell_Model(distance, domain);
218 LCModel_new->insertPointCloud(set);
219 insertNewModel(distance, LCModel_new);
220 LinkedCell_View view(*LCModel_new);
221 return view;
222 } else {
223 /// else construct interface and return.
224 LinkedCell_View view(*LCModel_best);
225 return view;
226 }
227}
228
229/** Internal function to re-create all present and used models for the new Box.
230 *
231 * This is necessary in the following cases:
232 * -# the Box is changed
233 * -# we step on to a different time step, i.e. all atomic positions change
234 *
235 * The main problem are the views currently in use.
236 *
237 * We make use of LinkedCell:LinkedCell_View::RAIIMap as there all present are
238 * listed. We go through the list, create a map with old model ref as keys to
239 * just newly created ones, and finally go again through each view and exchange
240 * the model against the new ones via a simple map lookup.
241 *
242 */
243void LinkedCell_Controller::updateModels()
244{
245 LOG(1, "INFO: Updating all models.");
246
247 typedef std::map<const LinkedCell_Model *, LinkedCell_Model *> ModelLookup;
248 ModelLookup models;
249
250 // set up map, for now with NULL pointers
251 for (LinkedCell_View::ModelInstanceMap::const_iterator iter = LinkedCell_View::RAIIMap.begin();
252 iter != LinkedCell_View::RAIIMap.end(); ++iter) {
253#ifndef NDEBUG
254 std::pair< ModelLookup::iterator, bool > inserter =
255#endif
256 models.insert( std::pair<const LinkedCell_Model *, LinkedCell_Model *>( (*iter)->LC->getModel(), NULL) );
257 LOG(2, "INFO: Added " << (*iter)->LC->getModel() << " to list of models to replace.");
258 ASSERT( inserter.second,
259 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - failed to insert old model "
260 +toString( (*iter)->LC->getModel() )+","+toString(NULL)+" into models, is already present");
261 }
262
263 // invert MapEdgelengthModel
264 LOG(2, "INFO: ModelsMap is " << ModelsMap << ".");
265 typedef std::map<const LinkedCell_Model*, double > MapEdgelengthModel_inverted;
266 MapEdgelengthModel_inverted ModelsMap_inverted;
267 for (MapEdgelengthModel::const_iterator iter = ModelsMap.begin();
268 iter != ModelsMap.end(); ++iter) {
269#ifndef NDEBUG
270 MapEdgelengthModel_inverted::const_iterator assertiter = ModelsMap_inverted.find(iter->second);
271 ASSERT( assertiter == ModelsMap_inverted.end(),
272 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - ModelsMap is not invertible, value "
273 +toString(iter->second)+" is already present.");
274#endif
275 ModelsMap_inverted.insert( std::make_pair(iter->second, iter->first) );
276 }
277 LOG(2, "INFO: Inverted ModelsMap is " << ModelsMap_inverted << ".");
278
279 // go through map and re-create models
280 for (ModelLookup::iterator iter = models.begin(); iter != models.end(); ++iter) {
281 // delete old model
282 const LinkedCell_Model * const oldref = iter->first;
283#ifndef NDEBUG
284 MapEdgelengthModel_inverted::const_iterator assertiter = ModelsMap_inverted.find(oldref);
285 ASSERT( assertiter != ModelsMap_inverted.end(),
286 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - ModelsMap_inverted does not contain old model "
287 +toString(oldref)+".");
288#endif
289 const double distance = ModelsMap_inverted[oldref];
290 // create new one, afterwards erase old model (this is for unit test to get different memory addresses)
291 LinkedCell_Model * const newref = new LinkedCell_Model(distance, domain);
292 MapEdgelengthModel::iterator oldmodeliter = ModelsMap.find(distance);
293 delete oldmodeliter->second;
294 ModelsMap.erase(oldmodeliter);
295 LOG(2, "INFO: oldref is " << oldref << ", newref is " << newref << ".");
296 iter->second = newref;
297 // replace in ModelsMap
298#ifndef NDEBUG
299 std::pair< MapEdgelengthModel::iterator, bool > inserter =
300#endif
301 ModelsMap.insert( std::make_pair(distance, newref) );
302 ASSERT( inserter.second,
303 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - failed to insert new model "
304 +toString(distance)+","+toString(newref)+" into ModelsMap, is already present");
305 }
306
307 // remove all remaining active models (also those that don't have an active View on them)
308 for (MapEdgelengthModel::iterator iter = ModelsMap.begin();
309 !ModelsMap.empty();
310 iter = ModelsMap.begin()) {
311 delete iter->second;
312 ModelsMap.erase(iter);
313 }
314
315
316 // delete inverted map for safety (values are gone)
317 ModelsMap_inverted.clear();
318
319 // go through views and exchange the models
320 for (LinkedCell_View::ModelInstanceMap::const_iterator iter = LinkedCell_View::RAIIMap.begin();
321 iter != LinkedCell_View::RAIIMap.end(); ++iter) {
322 ModelLookup::const_iterator modeliter = models.find((*iter)->LC->getModel());
323 ASSERT( modeliter != models.end(),
324 "LinkedCell_Controller::updateModelsForNewBoxMatrix() - we miss a model "
325 +toString((*iter)->LC->getModel())+" in ModelLookup.");
326 // this is ugly but the only place where we have to set ourselves over the constness of the member variable
327 if (modeliter != models.end()) {
328 LOG(2, "INFO: Setting model to " << modeliter->second << " in view " << *iter << ".");
329 (*iter)->LC->setModel(modeliter->second);
330 }
331 }
332}
333
334/** Callback function for Observer mechanism.
335 *
336 * @param publisher reference to the Observable that calls
337 */
338void LinkedCell_Controller::update(Observable *publisher)
339{
340 ELOG(2, "LinkedCell_Model received inconclusive general update from "
341 << publisher << ".");
342}
343
344/** Callback function for the Notifications mechanism.
345 *
346 * @param publisher reference to the Observable that calls
347 * @param notification specific notification as cause of the call
348 */
349void LinkedCell_Controller::recieveNotification(Observable *publisher, Notification_ptr notification)
350{
351 if (publisher == &domain) {
352 switch(notification->getChannelNo()) {
353 case Box::MatrixChanged:
354 LOG(1, "INFO: LinkedCell_Controller got update from Box.");
355 updateModels();
356 break;
357 default:
358 ASSERT(0,
359 "LinkedCell_Controller::recieveNotification() - unwanted notification from Box "
360 +toString(notification->getChannelNo())+" received.");
361 break;
362 }
363 } else if (publisher == WorldTime::getPointer()) {
364 switch(notification->getChannelNo()) {
365 case WorldTime::TimeChanged:
366 LOG(1, "INFO: LinkedCell_Controller got update from WorldTime.");
367 updateModels();
368 break;
369 default:
370 ASSERT(0,
371 "LinkedCell_Controller::recieveNotification() - unwanted notification from WorldTime "
372 +toString(notification->getChannelNo())+" received.");
373 break;
374 }
375 } else {
376 ELOG(1, "Notification " << notification->getChannelNo()
377 << " from unknown publisher " << publisher << ".");
378 }
379}
380
381/** Callback function when an Observer dies.
382 *
383 * @param publisher reference to the Observable that calls
384 */
385void LinkedCell_Controller::subjectKilled(Observable *publisher)
386{}
387
Note: See TracBrowser for help on using the repository browser.