source: src/Box.cpp@ 4e904b

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 4e904b was 94d5ac6, checked in by Frederik Heber <heber@…>, 12 years ago

FIX: As we use GSL internally, we are as of now required to use GPL v2 license.

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