source: src/LinkedCell/LinkedCell_Model.cpp@ e776dc

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

Added internal classes Update and changeModel to LinkedCell_Model.

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