source: src/Box.cpp@ cb7676

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

New function Box::isValid() to be discerned from ::isInside().

  • isValid checks with and isInside without boundary conditions.
  • added Box::isValid() check to LinkedCell_Model::getIndexToVector().
  • TESTFIX: regression test Atoms/Add needed Ignore BCs.
  • Property mode set to 100644
File size: 11.2 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
177bool Box::isValid(const Vector &point) const
178{
179 bool result = true;
180 Vector tester = translateOut(point);
181
182 for(int i=0;i<NDIM;i++)
183 result = result &&
184 ((conditions[i] != BoundaryConditions::Ignore) ||
185 ((tester[i] >= -MYEPSILON) &&
186 ((tester[i] - 1.) < MYEPSILON)));
187
188 return result;
189}
190
191
192VECTORSET(std::vector) Box::explode(const Vector &point,int n) const{
193 ASSERT(isInside(point),"Exploded point not inside Box");
194 internal_explode(point, n);
195 VECTORSET(std::vector) res(internal_list);
196 return res;
197}
198
199void Box::internal_explode(const Vector &point,int n) const{
200 internal_list.clear();
201 size_t list_index = 0;
202
203 Vector translater = translateOut(point);
204 Vector mask; // contains the ignored coordinates
205
206 // count the number of coordinates we need to do
207 int dims = 0; // number of dimensions that are not ignored
208 coords.clear();
209 index.clear();
210 for(int i=0;i<NDIM;++i){
211 if(conditions[i]==BoundaryConditions::Ignore){
212 mask[i]=translater[i];
213 continue;
214 }
215 coords.push_back(i);
216 index.push_back(-n);
217 dims++;
218 } // there are max vectors in total we need to create
219 internal_list.resize(pow(2*n+1, dims));
220
221 if(!dims){
222 // all boundaries are ignored
223 internal_list[list_index++] = point;
224 return;
225 }
226
227 bool done = false;
228 while(!done){
229 // create this vector
230 Vector helper;
231 for(int i=0;i<dims;++i){
232 switch(conditions[coords[i]]){
233 case BoundaryConditions::Wrap:
234 helper[coords[i]] = index[i]+translater[coords[i]];
235 break;
236 case BoundaryConditions::Bounce:
237 {
238 // Bouncing the coordinate x produces the series:
239 // 0 -> x
240 // 1 -> 2-x
241 // 2 -> 2+x
242 // 3 -> 4-x
243 // 4 -> 4+x
244 // the first number is the next bigger even number (n+n%2)
245 // the next number is the value with alternating sign (x-2*(n%2)*x)
246 // the negative numbers produce the same sequence reversed and shifted
247 int n = abs(index[i]) + ((index[i]<0)?-1:0);
248 int sign = (index[i]<0)?-1:+1;
249 int even = n%2;
250 helper[coords[i]]=n+even+translater[coords[i]]-2*even*translater[coords[i]];
251 helper[coords[i]]*=sign;
252 }
253 break;
254 case BoundaryConditions::Ignore:
255 ASSERT(0,"Ignored coordinate handled in generation loop");
256 break;
257 default:
258 ASSERT(0,"No default case for this switch-case");
259 break;
260 }
261
262 }
263 // add back all ignored coordinates (not handled in above loop)
264 helper+=mask;
265 ASSERT(list_index < internal_list.size(),
266 "Box::internal_explode() - we have estimated the number of vectors wrong: "
267 +toString(list_index) +" >= "+toString(internal_list.size())+".");
268 internal_list[list_index++] = translateIn(helper);
269 // set the new indexes
270 int pos=0;
271 ++index[pos];
272 while(index[pos]>n){
273 index[pos++]=-n;
274 if(pos>=dims) { // it's trying to increase one beyond array... all vectors generated
275 done = true;
276 break;
277 }
278 ++index[pos];
279 }
280 }
281}
282
283VECTORSET(std::vector) Box::explode(const Vector &point) const{
284 ASSERT(isInside(point),"Exploded point not inside Box");
285 return explode(point,1);
286}
287
288const Vector Box::periodicDistanceVector(const Vector &point1,const Vector &point2) const{
289 Vector helper1(enforceBoundaryConditions(point1));
290 Vector helper2(enforceBoundaryConditions(point2));
291 internal_explode(helper1,1);
292 const Vector res = internal_list.minDistance(helper2);
293 return res;
294}
295
296double Box::periodicDistanceSquared(const Vector &point1,const Vector &point2) const{
297 const Vector res = periodicDistanceVector(point1, point2);
298 return res.NormSquared();
299}
300
301double Box::periodicDistance(const Vector &point1,const Vector &point2) const{
302 double res = sqrt(periodicDistanceSquared(point1,point2));
303 return res;
304}
305
306double Box::DistanceToBoundary(const Vector &point) const
307{
308 std::map<double, Plane> DistanceSet;
309 std::vector<std::pair<Plane,Plane> > Boundaries = getBoundingPlanes();
310 for (int i=0;i<NDIM;++i) {
311 const double tempres1 = Boundaries[i].first.distance(point);
312 const double tempres2 = Boundaries[i].second.distance(point);
313 DistanceSet.insert( make_pair(tempres1, Boundaries[i].first) );
314 LOG(1, "Inserting distance " << tempres1 << " and " << tempres2 << ".");
315 DistanceSet.insert( make_pair(tempres2, Boundaries[i].second) );
316 }
317 ASSERT(!DistanceSet.empty(), "Box::DistanceToBoundary() - no distances in map!");
318 return (DistanceSet.begin())->first;
319}
320
321Shape Box::getShape() const{
322 return transform(Cuboid(Vector(0,0,0),Vector(1,1,1)),(*M));
323}
324
325const std::string Box::getConditionNames() const
326{
327 std::stringstream outputstream;
328 outputstream << conditions;
329 return outputstream.str();
330}
331
332const BoundaryConditions::Conditions_t & Box::getConditions() const
333{
334 return conditions.get();
335}
336
337const BoundaryConditions::BoundaryCondition_t Box::getCondition(size_t i) const
338{
339 return conditions.get(i);
340}
341
342void Box::setCondition(size_t i, const BoundaryConditions::BoundaryCondition_t _condition)
343{
344 OBSERVE;
345 NOTIFY(BoundaryConditionsChanged);
346 conditions.set(i, _condition);
347}
348
349void Box::setConditions(const BoundaryConditions::Conditions_t & _conditions)
350{
351 OBSERVE;
352 NOTIFY(BoundaryConditionsChanged);
353 conditions.set(_conditions);
354}
355
356void Box::setConditions(const std::string & _conditions)
357{
358 OBSERVE;
359 NOTIFY(BoundaryConditionsChanged);
360 std::stringstream inputstream(_conditions);
361 inputstream >> conditions;
362}
363
364const std::vector<std::pair<Plane,Plane> > Box::getBoundingPlanes() const
365{
366 std::vector<std::pair<Plane,Plane> > res;
367 for(int i=0;i<NDIM;++i){
368 Vector base1,base2,base3;
369 base2[(i+1)%NDIM] = 1.;
370 base3[(i+2)%NDIM] = 1.;
371 Plane p1(translateIn(base1),
372 translateIn(base2),
373 translateIn(base3));
374 Vector offset;
375 offset[i]=1;
376 Plane p2(translateIn(base1+offset),
377 translateIn(base2+offset),
378 translateIn(base3+offset));
379 res.push_back(make_pair(p1,p2));
380 }
381 ASSERT(res.size() == 3, "Box::getBoundingPlanes() - does not have three plane pairs!");
382 return res;
383}
384
385void Box::setCuboid(const Vector &endpoint)
386{
387 OBSERVE;
388 NOTIFY(MatrixChanged);
389 ASSERT(endpoint[0]>0 && endpoint[1]>0 && endpoint[2]>0,"Vector does not define a full cuboid");
390 M->setIdentity();
391 M->diagonal()=endpoint;
392 Vector &dinv = Minv->diagonal();
393 for(int i=NDIM;i--;)
394 dinv[i]=1/endpoint[i];
395}
396
397Box &Box::operator=(const Box &src)
398{
399 if(&src!=this){
400 OBSERVE;
401 // new matrix
402 NOTIFY(MatrixChanged);
403 delete M;
404 delete Minv;
405 M = new RealSpaceMatrix(*src.M);
406 Minv = new RealSpaceMatrix(*src.Minv);
407 // new boundary conditions
408 NOTIFY(BoundaryConditionsChanged);
409 conditions = src.conditions;
410 }
411 return *this;
412}
413
414Box &Box::operator=(const RealSpaceMatrix &mat)
415{
416 OBSERVE;
417 NOTIFY(MatrixChanged);
418 setM(mat);
419 return *this;
420}
421
422std::ostream & operator << (std::ostream& ost, const Box &m)
423{
424 ost << m.getM();
425 return ost;
426}
Note: See TracBrowser for help on using the repository browser.