source: src/Box.cpp@ 8fc1a6

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

Renamed Box::WrapPeriodically -> ::enforceBoundaryConditions.

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