source: src/Box.cpp@ 0cd8cf

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 0cd8cf was 31021ab, checked in by Frederik Heber <heber@…>, 12 years ago

Optimized Bondgraph detection.

  • VectorSet::minDistance() now operators on the set (translating by -point).
  • VectorSet::minDistSquared() removed as is the same as minDistance().
  • LinearAlgebra version is now 3:2:0, API is 1.0.5.
  • decrease log level of DepthFirstSearchAnalysis' msg about disconnected subgraphs.
  • Box::internal_explode() does not clear() internal_list, avoing constructing Vectors all the time.
  • BondGraph::CreateAdjacency gives some more message to tell when it does what.
  • Property mode set to 100644
File size: 12.1 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-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 * Box.cpp
25 *
26 * Created on: Jun 30, 2010
27 * Author: crueger
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 "Box.hpp"
38
39#include <cmath>
40#include <cstdlib>
41#include <iostream>
42#include <sstream>
43
44#include "CodePatterns/Assert.hpp"
45#include "CodePatterns/Log.hpp"
46#include "CodePatterns/Observer/Channels.hpp"
47#include "CodePatterns/Observer/Notification.hpp"
48#include "CodePatterns/Verbose.hpp"
49#include "Helpers/defs.hpp"
50#include "LinearAlgebra/RealSpaceMatrix.hpp"
51#include "LinearAlgebra/Vector.hpp"
52#include "LinearAlgebra/Plane.hpp"
53#include "Shapes/BaseShapes.hpp"
54#include "Shapes/ShapeOps.hpp"
55
56
57Box::Box() :
58 Observable("Box"),
59 M(new RealSpaceMatrix()),
60 Minv(new RealSpaceMatrix())
61{
62 internal_list.reserve(pow(3,3));
63 coords.reserve(NDIM);
64 index.reserve(NDIM);
65
66 // observable stuff
67 Channels *OurChannel = new Channels;
68 NotificationChannels.insert( std::make_pair(this, OurChannel) );
69 // add instance for each notification type
70 for (size_t type = 0; type < NotificationType_MAX; ++type)
71 OurChannel->addChannel(type);
72
73 M->setIdentity();
74 Minv->setIdentity();
75}
76
77Box::Box(const Box& src) :
78 Observable("Box"),
79 conditions(src.conditions),
80 M(new RealSpaceMatrix(*src.M)),
81 Minv(new RealSpaceMatrix(*src.Minv))
82{
83 internal_list.reserve(pow(3,3));
84 coords.reserve(NDIM);
85 index.reserve(NDIM);
86
87 // observable stuff
88 Channels *OurChannel = new Channels;
89 NotificationChannels.insert( std::make_pair(this, OurChannel) );
90 // add instance for each notification type
91 for (size_t type = 0; type < NotificationType_MAX; ++type)
92 OurChannel->addChannel(type);
93}
94
95Box::Box(RealSpaceMatrix _M) :
96 Observable("Box"),
97 M(new RealSpaceMatrix(_M)),
98 Minv(new RealSpaceMatrix())
99{
100 internal_list.reserve(pow(3,3));
101 coords.reserve(NDIM);
102 index.reserve(NDIM);
103
104 // observable stuff
105 Channels *OurChannel = new Channels;
106 NotificationChannels.insert( std::make_pair(this, OurChannel) );
107 // add instance for each notification type
108 for (size_t type = 0; type < NotificationType_MAX; ++type)
109 OurChannel->addChannel(type);
110
111 ASSERT(M->determinant()!=0,"Matrix in Box construction was not invertible");
112 *Minv = M->invert();
113}
114
115Box::~Box()
116{
117 // observable stuff
118 std::map<Observable *, Channels*>::iterator iter = NotificationChannels.find(this);
119 delete iter->second;
120 NotificationChannels.erase(iter);
121
122 delete M;
123 delete Minv;
124}
125
126const RealSpaceMatrix &Box::getM() const{
127 return *M;
128}
129const RealSpaceMatrix &Box::getMinv() const{
130 return *Minv;
131}
132
133void Box::setM(RealSpaceMatrix _M){
134 ASSERT(_M.determinant()!=0,"Matrix in Box construction was not invertible");
135 OBSERVE;
136 if (_M != *M)
137 NOTIFY(MatrixChanged);
138 *M =_M;
139 *Minv = M->invert();
140}
141
142Vector Box::translateIn(const Vector &point) const{
143 return (*M) * point;
144}
145
146Vector Box::translateOut(const Vector &point) const{
147 return (*Minv) * point;
148}
149
150Vector Box::enforceBoundaryConditions(const Vector &point) const{
151 Vector helper = translateOut(point);
152 for(int i=NDIM;i--;){
153
154 switch(conditions[i]){
155 case BoundaryConditions::Wrap:
156 helper.at(i)=fmod(helper.at(i),1);
157 helper.at(i)+=(helper.at(i)>=0)?0:1;
158 break;
159 case BoundaryConditions::Bounce:
160 {
161 // there probably is a better way to handle this...
162 // all the fabs and fmod modf probably makes it very slow
163 double intpart,fracpart;
164 fracpart = modf(fabs(helper.at(i)),&intpart);
165 helper.at(i) = fabs(fracpart-fmod(intpart,2));
166 }
167 break;
168 case BoundaryConditions::Ignore:
169 break;
170 default:
171 ASSERT(0,"No default case for this");
172 break;
173 }
174
175 }
176 return translateIn(helper);
177}
178
179bool Box::isInside(const Vector &point) const
180{
181 bool result = true;
182 Vector tester = translateOut(point);
183
184 for(int i=0;i<NDIM;i++)
185 result = result &&
186 ((conditions[i] == BoundaryConditions::Ignore) ||
187 ((tester[i] >= -MYEPSILON) &&
188 ((tester[i] - 1.) < MYEPSILON)));
189
190 return result;
191}
192
193bool Box::isValid(const Vector &point) const
194{
195 bool result = true;
196 Vector tester = translateOut(point);
197
198 for(int i=0;i<NDIM;i++)
199 result = result &&
200 ((conditions[i] != BoundaryConditions::Ignore) ||
201 ((tester[i] >= -MYEPSILON) &&
202 ((tester[i] - 1.) < MYEPSILON)));
203
204 return result;
205}
206
207
208VECTORSET(std::vector) Box::explode(const Vector &point,int n) const{
209 ASSERT(isInside(point),"Exploded point not inside Box");
210 internal_explode(point, n);
211 VECTORSET(std::vector) res(internal_list);
212 return res;
213}
214
215void Box::internal_explode(const Vector &point,int n) const{
216// internal_list.clear();
217 size_t list_index = 0;
218
219 Vector translater = translateOut(point);
220 Vector mask; // contains the ignored coordinates
221
222 // count the number of coordinates we need to do
223 int dims = 0; // number of dimensions that are not ignored
224 coords.clear();
225 index.clear();
226 for(int i=0;i<NDIM;++i){
227 if(conditions[i]==BoundaryConditions::Ignore){
228 mask[i]=translater[i];
229 continue;
230 }
231 coords.push_back(i);
232 index.push_back(-n);
233 dims++;
234 } // there are max vectors in total we need to create
235 const int new_size = pow(2*n+1, dims);
236 if (internal_list.size() != new_size)
237 internal_list.resize(new_size);
238
239 if(!dims){
240 // all boundaries are ignored
241 internal_list[list_index++] = point;
242 return;
243 }
244
245 bool done = false;
246 while(!done){
247 // create this vector
248 Vector helper;
249 for(int i=0;i<dims;++i){
250 switch(conditions[coords[i]]){
251 case BoundaryConditions::Wrap:
252 helper[coords[i]] = index[i]+translater[coords[i]];
253 break;
254 case BoundaryConditions::Bounce:
255 {
256 // Bouncing the coordinate x produces the series:
257 // 0 -> x
258 // 1 -> 2-x
259 // 2 -> 2+x
260 // 3 -> 4-x
261 // 4 -> 4+x
262 // the first number is the next bigger even number (n+n%2)
263 // the next number is the value with alternating sign (x-2*(n%2)*x)
264 // the negative numbers produce the same sequence reversed and shifted
265 int n = abs(index[i]) + ((index[i]<0)?-1:0);
266 int sign = (index[i]<0)?-1:+1;
267 int even = n%2;
268 helper[coords[i]]=n+even+translater[coords[i]]-2*even*translater[coords[i]];
269 helper[coords[i]]*=sign;
270 }
271 break;
272 case BoundaryConditions::Ignore:
273 ASSERT(0,"Ignored coordinate handled in generation loop");
274 break;
275 default:
276 ASSERT(0,"No default case for this switch-case");
277 break;
278 }
279
280 }
281 // add back all ignored coordinates (not handled in above loop)
282 helper+=mask;
283 ASSERT(list_index < internal_list.size(),
284 "Box::internal_explode() - we have estimated the number of vectors wrong: "
285 +toString(list_index) +" >= "+toString(internal_list.size())+".");
286 internal_list[list_index++] = translateIn(helper);
287 // set the new indexes
288 int pos=0;
289 ++index[pos];
290 while(index[pos]>n){
291 index[pos++]=-n;
292 if(pos>=dims) { // it's trying to increase one beyond array... all vectors generated
293 done = true;
294 break;
295 }
296 ++index[pos];
297 }
298 }
299}
300
301VECTORSET(std::vector) Box::explode(const Vector &point) const{
302 ASSERT(isInside(point),"Exploded point not inside Box");
303 return explode(point,1);
304}
305
306const Vector Box::periodicDistanceVector(const Vector &point1,const Vector &point2) const{
307 Vector helper1(enforceBoundaryConditions(point1));
308 Vector helper2(enforceBoundaryConditions(point2));
309 internal_explode(helper1,1);
310 const Vector res = internal_list.minDistance(helper2);
311 return res;
312}
313
314double Box::periodicDistanceSquared(const Vector &point1,const Vector &point2) const{
315 const Vector res = periodicDistanceVector(point1, point2);
316 return res.NormSquared();
317}
318
319double Box::periodicDistance(const Vector &point1,const Vector &point2) const{
320 double res = sqrt(periodicDistanceSquared(point1,point2));
321 return res;
322}
323
324double Box::DistanceToBoundary(const Vector &point) const
325{
326 std::map<double, Plane> DistanceSet;
327 std::vector<std::pair<Plane,Plane> > Boundaries = getBoundingPlanes();
328 for (int i=0;i<NDIM;++i) {
329 const double tempres1 = Boundaries[i].first.distance(point);
330 const double tempres2 = Boundaries[i].second.distance(point);
331 DistanceSet.insert( make_pair(tempres1, Boundaries[i].first) );
332 LOG(1, "Inserting distance " << tempres1 << " and " << tempres2 << ".");
333 DistanceSet.insert( make_pair(tempres2, Boundaries[i].second) );
334 }
335 ASSERT(!DistanceSet.empty(), "Box::DistanceToBoundary() - no distances in map!");
336 return (DistanceSet.begin())->first;
337}
338
339Shape Box::getShape() const{
340 return transform(Cuboid(Vector(0,0,0),Vector(1,1,1)),(*M));
341}
342
343const std::string Box::getConditionNames() const
344{
345 std::stringstream outputstream;
346 outputstream << conditions;
347 return outputstream.str();
348}
349
350const BoundaryConditions::Conditions_t & Box::getConditions() const
351{
352 return conditions.get();
353}
354
355const BoundaryConditions::BoundaryCondition_t Box::getCondition(size_t i) const
356{
357 return conditions.get(i);
358}
359
360void Box::setCondition(size_t i, const BoundaryConditions::BoundaryCondition_t _condition)
361{
362 OBSERVE;
363 if (conditions.get(i) != _condition)
364 NOTIFY(BoundaryConditionsChanged);
365 conditions.set(i, _condition);
366}
367
368void Box::setConditions(const BoundaryConditions::Conditions_t & _conditions)
369{
370 OBSERVE;
371 if (conditions.get() != _conditions)
372 NOTIFY(BoundaryConditionsChanged);
373 conditions.set(_conditions);
374}
375
376void Box::setConditions(const std::string & _conditions)
377{
378 OBSERVE;
379 NOTIFY(BoundaryConditionsChanged);
380 std::stringstream inputstream(_conditions);
381 inputstream >> conditions;
382}
383
384void Box::setConditions(const std::vector< std::string >& _conditions)
385{
386 OBSERVE;
387 NOTIFY(BoundaryConditionsChanged);
388 conditions.set(_conditions);
389}
390
391const std::vector<std::pair<Plane,Plane> > Box::getBoundingPlanes() const
392{
393 std::vector<std::pair<Plane,Plane> > res;
394 for(int i=0;i<NDIM;++i){
395 Vector base1,base2,base3;
396 base2[(i+1)%NDIM] = 1.;
397 base3[(i+2)%NDIM] = 1.;
398 Plane p1(translateIn(base1),
399 translateIn(base2),
400 translateIn(base3));
401 Vector offset;
402 offset[i]=1;
403 Plane p2(translateIn(base1+offset),
404 translateIn(base2+offset),
405 translateIn(base3+offset));
406 res.push_back(make_pair(p1,p2));
407 }
408 ASSERT(res.size() == 3, "Box::getBoundingPlanes() - does not have three plane pairs!");
409 return res;
410}
411
412void Box::setCuboid(const Vector &endpoint)
413{
414 OBSERVE;
415 NOTIFY(MatrixChanged);
416 ASSERT(endpoint[0]>0 && endpoint[1]>0 && endpoint[2]>0,"Vector does not define a full cuboid");
417 M->setIdentity();
418 M->diagonal()=endpoint;
419 Vector &dinv = Minv->diagonal();
420 for(int i=NDIM;i--;)
421 dinv[i]=1/endpoint[i];
422}
423
424Box &Box::operator=(const Box &src)
425{
426 if(&src!=this){
427 OBSERVE;
428 // new matrix
429 NOTIFY(MatrixChanged);
430 delete M;
431 delete Minv;
432 M = new RealSpaceMatrix(*src.M);
433 Minv = new RealSpaceMatrix(*src.Minv);
434 // new boundary conditions
435 NOTIFY(BoundaryConditionsChanged);
436 conditions = src.conditions;
437 }
438 return *this;
439}
440
441Box &Box::operator=(const RealSpaceMatrix &mat)
442{
443 OBSERVE;
444 NOTIFY(MatrixChanged);
445 setM(mat);
446 return *this;
447}
448
449std::ostream & operator << (std::ostream& ost, const Box &m)
450{
451 ost << m.getM();
452 return ost;
453}
Note: See TracBrowser for help on using the repository browser.