source: src/LinkedCell/LinkedCell_Model.cpp@ 4834f4

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 4834f4 was 53d894, checked in by Frederik Heber <heber@…>, 14 years ago

Changed LinkedCell_Model::getNeighborhoodBounds() and LinkedCell_View::getAllNeighbors().

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