source: src/Box.cpp@ de29ad6

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

Some optimization to speed up Subgraph dissections.

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