source: src/LinkedCell/LinkedCell_Model.cpp@ 8c31865

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

Added new class LinkedCellArrayCache that performs the lazy updates on a LinkedCellArray.

  • basically, we cache all write operations and perform them first when there is a read operation that requires an up-to-date structure.
  • we cannot do this via the Cacheable pattern was there we always have a return value of the update structure. It is currently unknown how to initialize a cached pointer (apart from always checking for this in the update function).
  • Property mode set to 100644
File size: 17.1 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2011 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * LinkedCell_Model.cpp
10 *
11 * Created on: Nov 15, 2011
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include "CodePatterns/MemDebug.hpp"
21
22#include "LinkedCell_Model.hpp"
23
24#include <algorithm>
25#include <boost/bind.hpp>
26#include <boost/multi_array.hpp>
27#include <limits>
28
29#include "Atom/AtomObserver.hpp"
30#include "Atom/TesselPoint.hpp"
31#include "Box.hpp"
32#include "CodePatterns/Assert.hpp"
33#include "CodePatterns/Info.hpp"
34#include "CodePatterns/Log.hpp"
35#include "CodePatterns/Observer/Observer.hpp"
36#include "CodePatterns/Observer/Notification.hpp"
37#include "CodePatterns/toString.hpp"
38#include "LinearAlgebra/RealSpaceMatrix.hpp"
39#include "LinearAlgebra/Vector.hpp"
40#include "LinkedCell/IPointCloud.hpp"
41#include "LinkedCell/LinkedCell.hpp"
42#include "LinkedCell/LinkedCell_Model_changeModel.hpp"
43#include "LinkedCell/LinkedCell_Model_LinkedCellArrayCache.hpp"
44#include "World.hpp"
45
46// initialize static entities
47LinkedCell::tripleIndex LinkedCell::LinkedCell_Model::NearestNeighbors;
48
49
50/** Constructor of LinkedCell_Model.
51 *
52 * @param radius desired maximum neighborhood distance
53 * @param _domain Box instance with domain size and boundary conditions
54 */
55LinkedCell::LinkedCell_Model::LinkedCell_Model(const double radius, const Box &_domain) :
56 ::Observer(std::string("LinkedCell_Model")+std::string("_")+toString(radius)),
57 Changes( new changeModel(radius) ),
58 internal_Sizes(NULL),
59 N(new LinkedCellArrayCache(Changes, boost::bind(&changeModel::performUpdates, Changes), std::string("N_cached"))),
60 domain(_domain)
61{
62 // set default argument
63 NearestNeighbors[0] = NearestNeighbors[1] = NearestNeighbors[2] = 1;
64
65 // get the partition of the domain
66 setPartition(radius);
67
68 // allocate linked cell structure
69 AllocateCells();
70
71 // sign in to AtomObserver
72 startListening();
73}
74
75/** Constructor of LinkedCell_Model.
76 *
77 * @oaram set set of points to place into the linked cell structure
78 * @param radius desired maximum neighborhood distance
79 * @param _domain Box instance with domain size and boundary conditions
80 */
81LinkedCell::LinkedCell_Model::LinkedCell_Model(IPointCloud &set, const double radius, const Box &_domain) :
82 ::Observer(std::string("LinkedCell_Model")+std::string("_")+toString(radius)),
83 Changes( new changeModel(radius) ),
84 internal_Sizes(NULL),
85 N(new LinkedCellArrayCache(Changes, boost::bind(&changeModel::performUpdates, Changes), std::string("N_cached"))),
86 domain(_domain)
87{
88 Info info(__func__);
89
90 // get the partition of the domain
91 setPartition(radius);
92
93 // allocate linked cell structure
94 AllocateCells();
95
96 insertPointCloud(set);
97
98 // sign in to AtomObserver
99 startListening();
100}
101
102/** Destructor of class LinkedCell_Model.
103 *
104 */
105LinkedCell::LinkedCell_Model::~LinkedCell_Model()
106{
107 // sign off from observables
108 stopListening();
109
110 // delete change queue
111 delete Changes;
112
113 // reset linked cell structure
114 Reset();
115
116}
117
118/** Signs in to AtomObserver and World to known about all changes.
119 *
120 */
121void LinkedCell::LinkedCell_Model::startListening()
122{
123 World::getInstance().signOn(this, World::AtomInserted);
124 World::getInstance().signOn(this, World::AtomRemoved);
125 AtomObserver::getInstance().signOn(this, AtomObservable::PositionChanged);
126}
127
128/** Signs off from AtomObserver and World.
129 *
130 */
131void LinkedCell::LinkedCell_Model::stopListening()
132{
133 World::getInstance().signOff(this, World::AtomInserted);
134 World::getInstance().signOff(this, World::AtomRemoved);
135 AtomObserver::getInstance().signOff(this, AtomObservable::PositionChanged);
136}
137
138
139/** Allocates as much cells per axis as required by
140 * LinkedCell_Model::BoxPartition.
141 *
142 */
143void LinkedCell::LinkedCell_Model::AllocateCells()
144{
145 // resize array
146 tripleIndex index;
147 for (int i=0;i<NDIM;i++)
148 index[i] = static_cast<LinkedCellArray::index>(Dimensions.at(i,i));
149 N->setN().resize(index);
150 ASSERT(getSize(0)*getSize(1)*getSize(2) < MAX_LINKEDCELLNODES,
151 "LinkedCell_Model::AllocateCells() - Number linked of linked cell nodes exceeded hard-coded limit, use greater edge length!");
152
153 // allocate LinkedCell instances
154 for(index[0] = 0; index[0] != static_cast<LinkedCellArray::index>(Dimensions.at(0,0)); ++index[0]) {
155 for(index[1] = 0; index[1] != static_cast<LinkedCellArray::index>(Dimensions.at(1,1)); ++index[1]) {
156 for(index[2] = 0; index[2] != static_cast<LinkedCellArray::index>(Dimensions.at(2,2)); ++index[2]) {
157 LOG(5, "INFO: Creating cell at " << index[0] << " " << index[1] << " " << index[2] << ".");
158 N->setN()(index) = new LinkedCell(index);
159 }
160 }
161 }
162}
163
164/** Frees all Linked Cell instances and sets array dimensions to (0,0,0).
165 *
166 */
167void LinkedCell::LinkedCell_Model::Reset()
168{
169 // free all LinkedCell instances
170 for(iterator3 iter3 = N->setN().begin(); iter3 != N->setN().end(); ++iter3) {
171 for(iterator2 iter2 = (*iter3).begin(); iter2 != (*iter3).end(); ++iter2) {
172 for(iterator1 iter1 = (*iter2).begin(); iter1 != (*iter2).end(); ++iter1) {
173 delete *iter1;
174 }
175 }
176 }
177 // set dimensions to zero
178 N->setN().resize(boost::extents[0][0][0]);
179}
180
181/** Inserts all points contained in \a set.
182 *
183 * @param set set with points to insert into linked cell structure
184 */
185void LinkedCell::LinkedCell_Model::insertPointCloud(IPointCloud &set)
186{
187 if (set.IsEmpty()) {
188 ELOG(1, "set is NULL or contains no linked cell nodes!");
189 return;
190 }
191
192 // put each atom into its respective cell
193 set.GoToFirst();
194 while (!set.IsEnd()) {
195 TesselPoint *Walker = set.GetPoint();
196 addNode(Walker);
197 set.GoToNext();
198 }
199}
200
201/** Calculates the required edge length for the given desired distance.
202 *
203 * We need to make some matrix transformations in order to obtain the required
204 * edge lengths per axis. Goal is guarantee that whatever the shape of the
205 * domain that always all points at least up to \a distance away are contained
206 * in the nearest neighboring cells.
207 *
208 * @param distance distance of this linked cell array
209 */
210void LinkedCell::LinkedCell_Model::setPartition(double distance)
211{
212 // generate box matrix of desired edge length
213 RealSpaceMatrix neighborhood;
214 neighborhood.setIdentity();
215 neighborhood *= distance;
216
217 // obtain refs to both domain matrix transformations
218 //const RealSpaceMatrix &M = domain.getM();
219 const RealSpaceMatrix &Minv = domain.getMinv();
220
221 RealSpaceMatrix output = Minv * neighborhood;
222
223 std::cout << Minv << " * " << neighborhood << " = " << output << std::endl;
224
225 Dimensions = output.invert();
226 Partition = Minv*Dimensions; //
227
228 std::cout << "Dimensions are then " << Dimensions << std::endl;
229 std::cout << "Partition matrix is then " << Partition << std::endl;
230}
231
232/** Returns the number of required neighbor-shells to get all neighboring points
233 * in the given \a distance.
234 *
235 * @param distance radius of neighborhood sphere
236 * @return number of LinkedCell's per dimension to get all neighbors
237 */
238const LinkedCell::tripleIndex LinkedCell::LinkedCell_Model::getStep(const double distance) const
239{
240 tripleIndex index;
241 index[0] = index[1] = index[2] = 0;
242
243 if (fabs(distance) < std::numeric_limits<double>::min())
244 return index;
245 // generate box matrix of desired edge length
246 RealSpaceMatrix neighborhood;
247 neighborhood.setIdentity();
248 neighborhood *= distance;
249
250 const RealSpaceMatrix output = Partition * neighborhood;
251
252 //std::cout << "GetSteps: " << Partition << " * " << neighborhood << " = " << output << std::endl;
253
254 const RealSpaceMatrix steps = output;
255 for (size_t i =0; i<NDIM; ++i)
256 index[i] = ceil(steps.at(i,i));
257 LOG(2, "INFO: number of shells are ("+toString(index[0])+","+toString(index[1])+","+toString(index[2])+").");
258
259 return index;
260}
261
262/** Calculates the index of the cell \a position would belong to.
263 *
264 * @param position position whose associated cell to calculate
265 * @return index of the cell
266 */
267const LinkedCell::tripleIndex LinkedCell::LinkedCell_Model::getIndexToVector(const Vector &position) const
268{
269 tripleIndex index;
270 Vector x(Partition*position);
271 LOG(2, "INFO: Transformed position is " << x << ".");
272 for (int i=0;i<NDIM;i++) {
273 index[i] = static_cast<LinkedCellArray::index>(floor(x[i]));
274 }
275 return index;
276}
277
278/** Adds an update to the list of lazy changes to add a node.
279 *
280 * @param Walker node to add
281 */
282void LinkedCell::LinkedCell_Model::addNode(const TesselPoint *Walker)
283{
284 addNode_internal(Walker);
285}
286
287/** Adds an update to the list of lazy changes to add remove a node.
288 *
289 * We do nothing of Walker is not found
290 *
291 * @param Walker node to remove
292 */
293void LinkedCell::LinkedCell_Model::deleteNode(const TesselPoint *Walker)
294{
295 deleteNode_internal(Walker);
296}
297
298/** Adds an update to the list of lazy changes to move a node.
299 *
300 * @param Walker node who has moved.
301 */
302void LinkedCell::LinkedCell_Model::moveNode(const TesselPoint *Walker)
303{
304 moveNode_internal(Walker);
305}
306
307/** Internal function to add a node to the linked cell structure
308 *
309 * @param Walker node to add
310 */
311void LinkedCell::LinkedCell_Model::addNode_internal(const TesselPoint *Walker)
312{
313 // find index
314 tripleIndex index = getIndexToVector(Walker->getPosition());
315 LOG(2, "INFO: " << *Walker << " goes into cell " << index[0] << ", " << index[1] << ", " << index[2] << ".");
316 LOG(2, "INFO: Cell's indices are "
317 << (N->getN())(index)->getIndex(0) << " "
318 << (N->getN())(index)->getIndex(1) << " "
319 << (N->getN())(index)->getIndex(2) << ".");
320 // add to cell
321 (N->setN())(index)->addPoint(Walker);
322 // add to index with check for presence
323 std::pair<MapPointToCell::iterator, bool> inserter = CellLookup.insert( std::make_pair(Walker, (N->setN())(index)) );
324 ASSERT( inserter.second,
325 "LinkedCell_Model::addNode() - Walker "
326 +toString(*Walker)+" is already present in cell "
327 +toString((inserter.first)->second->getIndex(0))+" "
328 +toString((inserter.first)->second->getIndex(1))+" "
329 +toString((inserter.first)->second->getIndex(2))+".");
330}
331
332/** Internal function to remove a node to the linked cell structure
333 *
334 * We do nothing of Walker is not found
335 *
336 * @param Walker node to remove
337 */
338void LinkedCell::LinkedCell_Model::deleteNode_internal(const TesselPoint *Walker)
339{
340 MapPointToCell::iterator iter = CellLookup.find(Walker);
341 ASSERT(iter != CellLookup.end(),
342 "LinkedCell_Model::deleteNode() - Walker not present in cell stored under CellLookup.");
343 if (iter != CellLookup.end()) {
344 // remove from lookup
345 CellLookup.erase(iter);
346 // remove from cell
347 iter->second->deletePoint(Walker);
348 }
349}
350
351/** Internal function to move node from current cell to another on position change.
352 *
353 * @param Walker node who has moved.
354 */
355void LinkedCell::LinkedCell_Model::moveNode_internal(const TesselPoint *Walker)
356{
357 MapPointToCell::iterator iter = CellLookup.find(Walker);
358 ASSERT(iter != CellLookup.end(),
359 "LinkedCell_Model::deleteNode() - Walker not present in cell stored under CellLookup.");
360 if (iter != CellLookup.end()) {
361 tripleIndex index = getIndexToVector(Walker->getPosition());
362 if (index != iter->second->getIndices()) {
363 // remove in old cell
364 iter->second->deletePoint(Walker);
365 // add to new cell
366 N->setN()(index)->addPoint(Walker);
367 // update lookup
368 iter->second = N->setN()(index);
369 }
370 }
371}
372
373/** Checks whether cell indicated by \a relative relative to LinkedCell_Model::internal_index
374 * is out of bounds.
375 *
376 * \note We do not check for boundary conditions of LinkedCell_Model::domain,
377 * we only look at the array sizes
378 *
379 * @param relative index relative to LinkedCell_Model::internal_index.
380 * @return true - relative index is still inside bounds, false - outside
381 */
382bool LinkedCell::LinkedCell_Model::checkArrayBounds(const tripleIndex &index) const
383{
384 bool status = true;
385 for (size_t i=0;i<NDIM;++i) {
386 status = status && (
387 (index[i] >= 0) &&
388 (index[i] < getSize(i))
389 );
390 }
391 return status;
392}
393
394/** Corrects \a index according to boundary conditions of LinkedCell_Model::domain .
395 *
396 * @param index index to correct according to boundary conditions
397 */
398void LinkedCell::LinkedCell_Model::applyBoundaryConditions(tripleIndex &index) const
399{
400 for (size_t i=0;i<NDIM;++i) {
401 switch (domain.getConditions()[i]) {
402 case Box::Wrap:
403 if ((index[i] < 0) || (index[i] >= getSize(i)))
404 index[i] = (index[i] % getSize(i));
405 break;
406 case Box::Bounce:
407 if (index[i] < 0)
408 index[i] = 0;
409 if (index[i] >= getSize(i))
410 index[i] = getSize(i)-1;
411 break;
412 case Box::Ignore:
413 if (index[i] < 0)
414 index[i] = 0;
415 if (index[i] >= getSize(i))
416 index[i] = getSize(i)-1;
417 break;
418 default:
419 ASSERT(0, "LinkedCell_Model::checkBounds() - unknown boundary conditions.");
420 break;
421 }
422 }
423}
424
425/** Calculates the interval bounds of the linked cell grid.
426 *
427 * \note we assume for index to allows be valid, i.e. within the range of LinkedCell_Model::N.
428 *
429 * \param index index to give relative bounds to
430 * \param step how deep to check the neighbouring cells (i.e. number of layers to check)
431 * \return pair of tripleIndex indicating lower and upper bounds
432 */
433const LinkedCell::LinkedCell_Model::LinkedCellNeighborhoodBounds LinkedCell::LinkedCell_Model::getNeighborhoodBounds(
434 const tripleIndex &index,
435 const tripleIndex &step
436 ) const
437{
438 LinkedCellNeighborhoodBounds neighbors;
439
440 // calculate bounds
441 for (size_t i=0;i<NDIM;++i) {
442 ASSERT(index[i] >= 0,
443 "LinkedCell_Model::getNeighborhoodBounds() - index "+toString(index)+" out of lower bounds.");
444 ASSERT (index[i] < getSize(i),
445 "LinkedCell_Model::getNeighborhoodBounds() - index "+toString(index)+" out of upper bounds.");
446 switch (domain.getConditions()[i]) {
447 case Box::Wrap:
448 if ((index[i] - step[i]) < 0)
449 neighbors.first[i] = getSize(i) + (index[i] - step[i]);
450 else if ((index[i] - step[i]) >= getSize(i))
451 neighbors.first[i] = (index[i] - step[i]) - getSize(i);
452 else
453 neighbors.first[i] = index[i] - step[i];
454 neighbors.second[i] = 2*step[i]+1;
455 break;
456 case Box::Bounce:
457 neighbors.second[i] = 2*step[i]+1;
458 if (index[i] - step[i] >= 0) {
459 neighbors.first[i] = index[i] - step[i];
460 } else {
461 neighbors.first[i] = 0;
462 neighbors.second[i] = index[i] + step[i]+1;
463 }
464 if (index[i] + step[i] >= getSize(i)) {
465 neighbors.second[i] = getSize(i) - (index[i] - step[i]);
466 }
467 break;
468 case Box::Ignore:
469 if (index[i] - step[i] < 0)
470 neighbors.first[i] = 0;
471 else
472 neighbors.first[i] = index[i] - step[i];
473 if (index[i] + step[i] >= getSize(i))
474 neighbors.second[i] = getSize(i) - index[i];
475 else
476 neighbors.second[i] = 2*step[i]+1;
477 break;
478 default:
479 ASSERT(0, "LinkedCell_Model::getNeighborhoodBounds() - unknown boundary conditions.");
480 break;
481 }
482 }
483
484 return neighbors;
485}
486
487/** Returns a reference to the cell indicated by LinkedCell_Model::internal_index.
488 *
489 * \return LinkedCell ref to current cell
490 */
491const LinkedCell::LinkedCell& LinkedCell::LinkedCell_Model::getCell(const tripleIndex &index) const
492{
493 return *(N->getN()(index));
494}
495
496
497/** Returns size of array for given \a dim.
498 *
499 * @param dim desired dimension
500 * @return size of array along dimension
501 */
502LinkedCell::LinkedCellArray::index LinkedCell::LinkedCell_Model::getSize(const size_t dim) const
503{
504 ASSERT((dim >= 0) && (dim < NDIM),
505 "LinkedCell_Model::getSize() - dimension "
506 +toString(dim)+" is out of bounds.");
507 return N->getN().shape()[dim];
508}
509
510/** Callback function for Observer mechanism.
511 *
512 * @param publisher reference to the Observable that calls
513 */
514void LinkedCell::LinkedCell_Model::update(Observable *publisher)
515{
516 ELOG(2, "LinkedCell_Model received inconclusive general update from "
517 << publisher << ".");
518}
519
520/** Callback function for the Notifications mechanism.
521 *
522 * @param publisher reference to the Observable that calls
523 * @param notification specific notification as cause of the call
524 */
525void LinkedCell::LinkedCell_Model::recieveNotification(Observable *publisher, Notification_ptr notification)
526{
527 // either it's the World or from the atom (through relay) itself
528 if (publisher == World::getPointer()) {
529 switch(notification->getChannelNo()) {
530 case World::AtomInserted:
531 addNode(World::getInstance().lastChanged<atom>());
532 break;
533 case World::AtomRemoved:
534 deleteNode(World::getInstance().lastChanged<atom>());
535 break;
536 }
537 } else {
538 switch(notification->getChannelNo()) {
539 case AtomObservable::PositionChanged:
540 {
541 moveNode(dynamic_cast<const TesselPoint *>(publisher));
542 break;
543 }
544 default:
545 LOG(2, "LinkedCell_Model received unwanted notification from AtomObserver's channel "
546 << notification->getChannelNo() << ".");
547 break;
548 }
549 }
550}
551
552/** Callback function when an Observer dies.
553 *
554 * @param publisher reference to the Observable that calls
555 */
556void LinkedCell::LinkedCell_Model::subjectKilled(Observable *publisher)
557{}
558
Note: See TracBrowser for help on using the repository browser.