source: src/Box.cpp@ 6ff62c

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 6ff62c was 708277, checked in by Frederik Heber <heber@…>, 12 years ago

FIX: Using fixed Observer in CodePatterns 1.2.6.

  • we now require CodePatterns 1.2.6.
  • Notifications now use subjectKilled() when the Observable they are associated with is destroyed. This allows Observers that are just sign on to a single channel safely sign off.
  • also, derived Observable classes must not remove their Channels and Notifications by themselves. This is done by the Observable base class. Otherwise, subjectKilled() is not called.
  • changed AtomObserver: Is directly connected to the atom class, AtomInserted and AtomRemoved called in its cstor and dstor. The World has nothing to do with it. However, we have to make sure AtomObserver is purged after World.
  • Fixed also some faulty uses of ObserverLog and we always insert into NotificationChannels with static_cast to Observable for clarity.
  • 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(static_cast<Observable *>(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(static_cast<Observable *>(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(static_cast<Observable *>(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 delete M;
118 delete Minv;
119}
120
121const RealSpaceMatrix &Box::getM() const{
122 return *M;
123}
124const RealSpaceMatrix &Box::getMinv() const{
125 return *Minv;
126}
127
128void Box::setM(RealSpaceMatrix _M){
129 ASSERT(_M.determinant()!=0,"Matrix in Box construction was not invertible");
130 OBSERVE;
131 if (_M != *M)
132 NOTIFY(MatrixChanged);
133 *M =_M;
134 *Minv = M->invert();
135}
136
137Vector Box::translateIn(const Vector &point) const{
138 return (*M) * point;
139}
140
141Vector Box::translateOut(const Vector &point) const{
142 return (*Minv) * point;
143}
144
145Vector Box::enforceBoundaryConditions(const Vector &point) const{
146 Vector helper = translateOut(point);
147 for(int i=NDIM;i--;){
148
149 switch(conditions[i]){
150 case BoundaryConditions::Wrap:
151 helper.at(i)=fmod(helper.at(i),1);
152 helper.at(i)+=(helper.at(i)>=0)?0:1;
153 break;
154 case BoundaryConditions::Bounce:
155 {
156 // there probably is a better way to handle this...
157 // all the fabs and fmod modf probably makes it very slow
158 double intpart,fracpart;
159 fracpart = modf(fabs(helper.at(i)),&intpart);
160 helper.at(i) = fabs(fracpart-fmod(intpart,2));
161 }
162 break;
163 case BoundaryConditions::Ignore:
164 break;
165 default:
166 ASSERT(0,"No default case for this");
167 break;
168 }
169
170 }
171 return translateIn(helper);
172}
173
174bool Box::isInside(const Vector &point) const
175{
176 bool result = true;
177 Vector tester = translateOut(point);
178
179 for(int i=0;i<NDIM;i++)
180 result = result &&
181 ((conditions[i] == BoundaryConditions::Ignore) ||
182 ((tester[i] >= -MYEPSILON) &&
183 ((tester[i] - 1.) < MYEPSILON)));
184
185 return result;
186}
187
188bool Box::isValid(const Vector &point) const
189{
190 bool result = true;
191 Vector tester = translateOut(point);
192
193 for(int i=0;i<NDIM;i++)
194 result = result &&
195 ((conditions[i] != BoundaryConditions::Ignore) ||
196 ((tester[i] >= -MYEPSILON) &&
197 ((tester[i] - 1.) < MYEPSILON)));
198
199 return result;
200}
201
202
203VECTORSET(std::vector) Box::explode(const Vector &point,int n) const{
204 ASSERT(isInside(point),"Exploded point not inside Box");
205 internal_explode(point, n);
206 VECTORSET(std::vector) res(internal_list);
207 return res;
208}
209
210void Box::internal_explode(const Vector &point,int n) const{
211// internal_list.clear();
212 size_t list_index = 0;
213
214 Vector translater = translateOut(point);
215 Vector mask; // contains the ignored coordinates
216
217 // count the number of coordinates we need to do
218 int dims = 0; // number of dimensions that are not ignored
219 coords.clear();
220 index.clear();
221 for(int i=0;i<NDIM;++i){
222 if(conditions[i]==BoundaryConditions::Ignore){
223 mask[i]=translater[i];
224 continue;
225 }
226 coords.push_back(i);
227 index.push_back(-n);
228 dims++;
229 } // there are max vectors in total we need to create
230 const int new_size = pow(2*n+1, dims);
231 if (internal_list.size() != new_size)
232 internal_list.resize(new_size);
233
234 if(!dims){
235 // all boundaries are ignored
236 internal_list[list_index++] = point;
237 return;
238 }
239
240 bool done = false;
241 while(!done){
242 // create this vector
243 Vector helper;
244 for(int i=0;i<dims;++i){
245 switch(conditions[coords[i]]){
246 case BoundaryConditions::Wrap:
247 helper[coords[i]] = index[i]+translater[coords[i]];
248 break;
249 case BoundaryConditions::Bounce:
250 {
251 // Bouncing the coordinate x produces the series:
252 // 0 -> x
253 // 1 -> 2-x
254 // 2 -> 2+x
255 // 3 -> 4-x
256 // 4 -> 4+x
257 // the first number is the next bigger even number (n+n%2)
258 // the next number is the value with alternating sign (x-2*(n%2)*x)
259 // the negative numbers produce the same sequence reversed and shifted
260 int n = abs(index[i]) + ((index[i]<0)?-1:0);
261 int sign = (index[i]<0)?-1:+1;
262 int even = n%2;
263 helper[coords[i]]=n+even+translater[coords[i]]-2*even*translater[coords[i]];
264 helper[coords[i]]*=sign;
265 }
266 break;
267 case BoundaryConditions::Ignore:
268 ASSERT(0,"Ignored coordinate handled in generation loop");
269 break;
270 default:
271 ASSERT(0,"No default case for this switch-case");
272 break;
273 }
274
275 }
276 // add back all ignored coordinates (not handled in above loop)
277 helper+=mask;
278 ASSERT(list_index < internal_list.size(),
279 "Box::internal_explode() - we have estimated the number of vectors wrong: "
280 +toString(list_index) +" >= "+toString(internal_list.size())+".");
281 internal_list[list_index++] = translateIn(helper);
282 // set the new indexes
283 int pos=0;
284 ++index[pos];
285 while(index[pos]>n){
286 index[pos++]=-n;
287 if(pos>=dims) { // it's trying to increase one beyond array... all vectors generated
288 done = true;
289 break;
290 }
291 ++index[pos];
292 }
293 }
294}
295
296VECTORSET(std::vector) Box::explode(const Vector &point) const{
297 ASSERT(isInside(point),"Exploded point not inside Box");
298 return explode(point,1);
299}
300
301const Vector Box::periodicDistanceVector(const Vector &point1,const Vector &point2) const{
302 Vector helper1(enforceBoundaryConditions(point1));
303 Vector helper2(enforceBoundaryConditions(point2));
304 internal_explode(helper1,1);
305 const Vector res = internal_list.minDistance(helper2);
306 return res;
307}
308
309double Box::periodicDistanceSquared(const Vector &point1,const Vector &point2) const{
310 const Vector res = periodicDistanceVector(point1, point2);
311 return res.NormSquared();
312}
313
314double Box::periodicDistance(const Vector &point1,const Vector &point2) const{
315 double res = sqrt(periodicDistanceSquared(point1,point2));
316 return res;
317}
318
319double Box::DistanceToBoundary(const Vector &point) const
320{
321 std::map<double, Plane> DistanceSet;
322 std::vector<std::pair<Plane,Plane> > Boundaries = getBoundingPlanes();
323 for (int i=0;i<NDIM;++i) {
324 const double tempres1 = Boundaries[i].first.distance(point);
325 const double tempres2 = Boundaries[i].second.distance(point);
326 DistanceSet.insert( make_pair(tempres1, Boundaries[i].first) );
327 LOG(1, "Inserting distance " << tempres1 << " and " << tempres2 << ".");
328 DistanceSet.insert( make_pair(tempres2, Boundaries[i].second) );
329 }
330 ASSERT(!DistanceSet.empty(), "Box::DistanceToBoundary() - no distances in map!");
331 return (DistanceSet.begin())->first;
332}
333
334Shape Box::getShape() const{
335 return transform(Cuboid(Vector(0,0,0),Vector(1,1,1)),(*M));
336}
337
338const std::string Box::getConditionNames() const
339{
340 std::stringstream outputstream;
341 outputstream << conditions;
342 return outputstream.str();
343}
344
345const BoundaryConditions::Conditions_t & Box::getConditions() const
346{
347 return conditions.get();
348}
349
350const BoundaryConditions::BoundaryCondition_t Box::getCondition(size_t i) const
351{
352 return conditions.get(i);
353}
354
355void Box::setCondition(size_t i, const BoundaryConditions::BoundaryCondition_t _condition)
356{
357 OBSERVE;
358 if (conditions.get(i) != _condition)
359 NOTIFY(BoundaryConditionsChanged);
360 conditions.set(i, _condition);
361}
362
363void Box::setConditions(const BoundaryConditions::Conditions_t & _conditions)
364{
365 OBSERVE;
366 if (conditions.get() != _conditions)
367 NOTIFY(BoundaryConditionsChanged);
368 conditions.set(_conditions);
369}
370
371void Box::setConditions(const std::string & _conditions)
372{
373 OBSERVE;
374 NOTIFY(BoundaryConditionsChanged);
375 std::stringstream inputstream(_conditions);
376 inputstream >> conditions;
377}
378
379void Box::setConditions(const std::vector< std::string >& _conditions)
380{
381 OBSERVE;
382 NOTIFY(BoundaryConditionsChanged);
383 conditions.set(_conditions);
384}
385
386const std::vector<std::pair<Plane,Plane> > Box::getBoundingPlanes() const
387{
388 std::vector<std::pair<Plane,Plane> > res;
389 for(int i=0;i<NDIM;++i){
390 Vector base1,base2,base3;
391 base2[(i+1)%NDIM] = 1.;
392 base3[(i+2)%NDIM] = 1.;
393 Plane p1(translateIn(base1),
394 translateIn(base2),
395 translateIn(base3));
396 Vector offset;
397 offset[i]=1;
398 Plane p2(translateIn(base1+offset),
399 translateIn(base2+offset),
400 translateIn(base3+offset));
401 res.push_back(make_pair(p1,p2));
402 }
403 ASSERT(res.size() == 3, "Box::getBoundingPlanes() - does not have three plane pairs!");
404 return res;
405}
406
407void Box::setCuboid(const Vector &endpoint)
408{
409 OBSERVE;
410 NOTIFY(MatrixChanged);
411 ASSERT(endpoint[0]>0 && endpoint[1]>0 && endpoint[2]>0,"Vector does not define a full cuboid");
412 M->setIdentity();
413 M->diagonal()=endpoint;
414 Vector &dinv = Minv->diagonal();
415 for(int i=NDIM;i--;)
416 dinv[i]=1/endpoint[i];
417}
418
419Box &Box::operator=(const Box &src)
420{
421 if(&src!=this){
422 OBSERVE;
423 // new matrix
424 NOTIFY(MatrixChanged);
425 delete M;
426 delete Minv;
427 M = new RealSpaceMatrix(*src.M);
428 Minv = new RealSpaceMatrix(*src.Minv);
429 // new boundary conditions
430 NOTIFY(BoundaryConditionsChanged);
431 conditions = src.conditions;
432 }
433 return *this;
434}
435
436Box &Box::operator=(const RealSpaceMatrix &mat)
437{
438 OBSERVE;
439 NOTIFY(MatrixChanged);
440 setM(mat);
441 return *this;
442}
443
444std::ostream & operator << (std::ostream& ost, const Box &m)
445{
446 ost << m.getM();
447 return ost;
448}
Note: See TracBrowser for help on using the repository browser.