source: src/LinkedCell/LinkedCell_Model.cpp@ 97c2550

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

LinkedCell_Model now inherits Observer.

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