source: src/Box.cpp@ aec098

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

FIX: Box does not notify (though update) when set conditions or matrix is the same.

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