source: src/Box.cpp@ d66cb7

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 Candidate_v1.7.0 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 d66cb7 was d66cb7, checked in by Frederik Heber <heber@…>, 14 years ago

Replaced Conditions_t by BoundaryConditions::BCContainer in class Box.

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