source: src/Shapes/BaseShapes.cpp@ 87d6bd

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

FIX: Fixing several clang errors such that we may safely use the compiler.

Changes:

  • clang does not like execeptions as pure forward declarations.
  • clang does not like AtomTypes[MaxTypes] with MaxTypes being dynamic.
  • clang does not like cppunit to have no operator<<() for std::sets (it though finds the ones for std::vector?), it cannot use one from toString.hpp as it is declared afterwards (although before instantiation site).
  • clang does not tolerate inheriting from a protected member class TQuery.
  • clang does not tolerate shadowing of a variable inside a for-loop (i.e. declaring variable in loop body with same name as e.g. loop variable).
  • clang compilation ran through after these changes without a single failing test.
  • Property mode set to 100644
File size: 14.0 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 * BaseShapes_impl.cpp
25 *
26 * Created on: Jun 18, 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 "Shapes/BaseShapes.hpp"
38#include "Shapes/BaseShapes_impl.hpp"
39#include "Shapes/ShapeExceptions.hpp"
40#include "Shapes/ShapeOps.hpp"
41
42#include "Helpers/defs.hpp"
43
44#include "CodePatterns/Assert.hpp"
45#include "LinearAlgebra/Vector.hpp"
46#include "LinearAlgebra/RealSpaceMatrix.hpp"
47#include "LinearAlgebra/Line.hpp"
48#include "LinearAlgebra/Plane.hpp"
49#include "LinearAlgebra/LineSegment.hpp"
50#include "LinearAlgebra/LineSegmentSet.hpp"
51
52#include <cmath>
53#include <algorithm>
54
55// CYLINDER CODE
56// ----------------------------------------------------------------------------
57bool Cylinder_impl::isInside(const Vector &point) const {
58 return (Vector(point[0], point[1], 0.0).NormSquared() < 1.0+MYEPSILON) &&
59 (point[2] > -1.0-MYEPSILON) && (point[2] < 1.0+MYEPSILON);
60}
61
62bool Cylinder_impl::isOnSurface(const Vector &point) const {
63 // on the side?
64 if (fabs(Vector(point[0], point[1], 0.0).NormSquared()-1.0)<MYEPSILON &&
65 (point[2] > -1.0-MYEPSILON) && (point[2] < 1.0+MYEPSILON))
66 return true;
67 // on top/bottom?
68 if ((Vector(point[0], point[1], 0.0).NormSquared()< 1.0 + MYEPSILON) &&
69 ((fabs(point[2]-1)<MYEPSILON) || (fabs(point[2]+1)<MYEPSILON)))
70 return true;
71 return false;
72
73}
74
75Vector Cylinder_impl::getNormal(const Vector &point) const throw(NotOnSurfaceException) {
76 if(!isOnSurface(point)){
77 throw NotOnSurfaceException() << ShapeVector(&point);
78 }
79
80 Vector n = Vector(0, 0, 0);
81 if ((fabs(point[2]-1)<MYEPSILON) || (fabs(point[2]+1)<MYEPSILON))
82 n += Vector(0.0, 0.0, point[2]);
83 else
84 n += Vector(point[0], point[1], 0.0);
85 n.Normalize();
86 return n;
87}
88
89Vector Cylinder_impl::getCenter() const
90{
91 return Vector(0.0, 0.0, 0.0);
92}
93
94double Cylinder_impl::getRadius() const
95{
96 return 1.0;
97}
98
99double Cylinder_impl::getVolume() const
100{
101 return M_PI*2.0; // pi r^2 h
102}
103
104double Cylinder_impl::getSurfaceArea() const
105{
106 return 2.0*M_PI*2.0; // 2 pi r h
107}
108
109LineSegmentSet Cylinder_impl::getLineIntersections(const Line &line) const {
110 const Vector origin = line.getOrigin();
111 const Vector direction = line.getDirection();
112
113 const Vector e(direction[0], direction[1], 0.0);
114 const Vector f(origin[0], origin[1], 0.0);
115 const double A = e.ScalarProduct(e);
116 const double B = 2.0*e.ScalarProduct(f);
117 const double C = f.ScalarProduct(f) - 1.0;
118
119 std::vector<double> solutions;
120
121 // Common routine to solve quadratic equations, anywhere?
122 const double neg_p_half = -B/(2.0*A);
123 const double q = C/A;
124 const double radicant = neg_p_half*neg_p_half-q;
125
126 if (radicant > 0.0) {
127 const double root = sqrt(radicant);
128 solutions.push_back(neg_p_half+root);
129 const double sln2 = neg_p_half-root;
130 if (sln2 != solutions.back())
131 solutions.push_back(sln2);
132 }
133
134 // Now get parameter for intersection with z-Planes.
135 const double origin_z = origin[2];
136 const double dir_z = direction[2];
137
138 if (dir_z != 0.0) {
139 solutions.push_back((-1.0-origin_z)/dir_z);
140 solutions.push_back((1.0-origin_z)/dir_z);
141 }
142
143 // Calculate actual vectors from obtained parameters and check,
144 // if they are actual intersections.
145 std::vector<Vector> intersections;
146
147 for(unsigned int i=0; i<solutions.size(); i++) {
148 const Vector check_me(origin + direction*solutions[i]);
149 if (isOnSurface(check_me))
150 intersections.push_back(check_me);
151 }
152
153 LineSegmentSet result(line);
154 if (intersections.size()==2)
155 result.insert(LineSegment(intersections[0], intersections[1]));
156 return result;
157}
158
159std::string Cylinder_impl::toString() const
160{
161 return "Cylinder()";
162}
163
164enum ShapeType Cylinder_impl::getType() const
165{
166 return CylinderType;
167}
168
169std::vector<Vector> Cylinder_impl::getHomogeneousPointsOnSurface(const size_t N) const {
170 const double nz_float = sqrt(N/M_PI);
171 const int nu = round(N/nz_float);
172 const int nz = round(nz_float);
173
174 const double dphi = 2.0*M_PI/nu;
175 const double dz = 2.0/nz;
176
177 std::vector<Vector> result;
178
179 for(int useg=0; useg<nu; useg++)
180 for(int zseg=0; zseg<=nz; zseg++)
181 result.push_back(Vector(cos(useg*dphi), sin(useg*dphi), zseg*dz-1.0));
182
183 return result;
184}
185
186std::vector<Vector> Cylinder_impl::getHomogeneousPointsInVolume(const size_t N) const {
187 const double nz_float = pow(N/(2.0*M_PI), 1.0/3.0);
188 const int nu = round(nz_float*M_PI);
189 const int nr = round(nz_float*0.5);
190 const int nz = round(nz_float);
191
192 const double dphi = 2.0*M_PI/nu;
193 const double dz = 2.0/nz;
194 const double dr = 1.0/nr;
195
196 std::vector<Vector> result;
197
198 for(int useg=0; useg<nu; useg++)
199 for(int zseg=0; zseg<nz; zseg++)
200 for(int rseg=0; rseg<nr; rseg++)
201 {
202 const double r = dr+rseg*dr;
203 result.push_back(Vector(r*cos(useg*dphi), r*sin(useg*dphi), zseg*dz-1.0));
204 }
205
206 return result;
207}
208
209Shape Cylinder() {
210 Shape::impl_ptr impl = Shape::impl_ptr(new Cylinder_impl());
211 return Shape(impl);
212}
213
214Shape Cylinder(const Vector &center, const double xrot, const double yrot,
215 const double height, const double radius)
216{
217 RealSpaceMatrix rot;
218 rot.setRotation(xrot, yrot, 0.0);
219
220 return translate(
221 transform(
222 stretch(
223 Cylinder(),
224 Vector(radius, radius, height*0.5)),
225 rot),
226 center);
227}
228// ----------------------------------------------------------------------------
229
230bool Sphere_impl::isInside(const Vector &point) const{
231 return point.NormSquared() <= 1. + MYEPSILON;
232}
233
234bool Sphere_impl::isOnSurface(const Vector &point) const{
235 return fabs(point.NormSquared()-1.)<MYEPSILON;
236}
237
238Vector Sphere_impl::getNormal(const Vector &point) const throw(NotOnSurfaceException){
239 if(!isOnSurface(point)){
240 throw NotOnSurfaceException() << ShapeVector(&point);
241 }
242 return point;
243}
244
245Vector Sphere_impl::getCenter() const
246{
247 return Vector(0.,0.,0.);
248}
249
250double Sphere_impl::getRadius() const
251{
252 return 1.;
253}
254
255double Sphere_impl::getVolume() const
256{
257 return (4./3.)*M_PI; // 4/3 pi r^3
258}
259
260double Sphere_impl::getSurfaceArea() const
261{
262 return 2.*M_PI; // 2 pi r^2
263}
264
265
266LineSegmentSet Sphere_impl::getLineIntersections(const Line &line) const{
267 LineSegmentSet res(line);
268 std::vector<Vector> intersections = line.getSphereIntersections();
269 if(intersections.size()==2){
270 res.insert(LineSegment(intersections[0],intersections[1]));
271 }
272 return res;
273}
274
275std::string Sphere_impl::toString() const{
276 return "Sphere()";
277}
278
279enum ShapeType Sphere_impl::getType() const
280{
281 return SphereType;
282}
283
284/**
285 * algorithm taken from http://www.cgafaq.info/wiki/Evenly_distributed_points_on_sphere
286 * \param N number of points on surface
287 */
288std::vector<Vector> Sphere_impl::getHomogeneousPointsOnSurface(const size_t N) const
289{
290 std::vector<Vector> PointsOnSurface;
291 if (true) {
292 // Exactly N points but not symmetric.
293
294 // This formula is derived by finding a curve on the sphere that spirals down from
295 // the north pole to the south pole keeping a constant distance between consecutive turns.
296 // The curve is then parametrized by arch length and evaluated in constant intervals.
297 double a = sqrt(N) * 2;
298 for (int i=0; i<N; i++){
299 double t0 = ((double)i + 0.5) / (double)N;
300 double t = (sqrt(t0) - sqrt(1.0 - t0) + 1.0) / 2.0 * M_PI;
301 Vector point;
302 point.Zero();
303 point[0] = sin(t) * sin(t * a);
304 point[1] = sin(t) * cos(t * a);
305 point[2] = cos(t);
306 PointsOnSurface.push_back(point);
307 }
308 ASSERT(PointsOnSurface.size() == N,
309 "Sphere_impl::getHomogeneousPointsOnSurface() did not create "
310 +::toString(N)+" but "+::toString(PointsOnSurface.size())+" points.");
311 } else {
312 // Symmetric but only approximately N points.
313 double a=4*M_PI/N;
314 double d= sqrt(a);
315 int Mtheta=int(M_PI/d);
316 double dtheta=M_PI/Mtheta;
317 double dphi=a/dtheta;
318 for (int m=0; m<Mtheta; m++)
319 {
320 double theta=M_PI*(m+0.5)/Mtheta;
321 int Mphi=int(2*M_PI*sin(theta)/dphi);
322 for (int n=0; n<Mphi;n++)
323 {
324 double phi= 2*M_PI*n/Mphi;
325 Vector point;
326 point.Zero();
327 point[0]=sin(theta)*cos(phi);
328 point[1]=sin(theta)*sin(phi);
329 point[2]=cos(theta);
330 PointsOnSurface.push_back(point);
331 }
332 }
333 }
334 return PointsOnSurface;
335}
336
337std::vector<Vector> Sphere_impl::getHomogeneousPointsInVolume(const size_t N) const {
338 ASSERT(0,
339 "Sphere_impl::getHomogeneousPointsInVolume() - not implemented.");
340 return std::vector<Vector>();
341}
342
343Shape Sphere(){
344 Shape::impl_ptr impl = Shape::impl_ptr(new Sphere_impl());
345 return Shape(impl);
346}
347
348Shape Sphere(const Vector &center,double radius){
349 return translate(resize(Sphere(),radius),center);
350}
351
352Shape Ellipsoid(const Vector &center, const Vector &radius){
353 return translate(stretch(Sphere(),radius),center);
354}
355
356bool Cuboid_impl::isInside(const Vector &point) const{
357 return (point[0]>=-MYEPSILON && point[0]<=1+MYEPSILON) && (point[1]>=-MYEPSILON && point[1]<=1+MYEPSILON) && (point[2]>=-MYEPSILON && point[2]<=1+MYEPSILON);
358}
359
360bool Cuboid_impl::isOnSurface(const Vector &point) const{
361 bool retVal = isInside(point);
362 // test all borders of the cuboid
363 // double fabs
364 retVal = retVal &&
365 (((fabs(point[0]-1.) < MYEPSILON) || (fabs(point[0]) < MYEPSILON)) ||
366 ((fabs(point[1]-1.) < MYEPSILON) || (fabs(point[1]) < MYEPSILON)) ||
367 ((fabs(point[2]-1.) < MYEPSILON) || (fabs(point[2]) < MYEPSILON)));
368 return retVal;
369}
370
371Vector Cuboid_impl::getNormal(const Vector &point) const throw(NotOnSurfaceException){
372 if(!isOnSurface(point)){
373 throw NotOnSurfaceException() << ShapeVector(&point);
374 }
375 Vector res;
376 // figure out on which sides the Vector lies (maximum 3, when it is in a corner)
377 for(int i=NDIM;i--;){
378 if((fabs(point[i])<MYEPSILON) || (fabs(point[i]-1)<MYEPSILON)){
379 // add the scaled (-1/+1) Vector to the set of surface vectors
380 res[i] = point[i] * 2.0 - 1.0;
381 }
382 }
383 ASSERT(res.NormSquared()>=1 && res.NormSquared()<=3,"To many or to few sides found for this Vector");
384
385 res.Normalize();
386 return res;
387}
388
389
390Vector Cuboid_impl::getCenter() const
391{
392 return Vector(0.5,0.5,0.5);
393}
394
395double Cuboid_impl::getRadius() const
396{
397 return .5;
398}
399
400double Cuboid_impl::getVolume() const
401{
402 return 1.; // l^3
403}
404
405double Cuboid_impl::getSurfaceArea() const
406{
407 return 6.; // 6 * l^2
408}
409
410LineSegmentSet Cuboid_impl::getLineIntersections(const Line &line) const{
411 LineSegmentSet res(line);
412 // get the intersection on each of the six faces
413 std::vector<Vector> intersections;
414 intersections.resize(2);
415 int c=0;
416 int x[2]={-1,+1};
417 for(int i=NDIM;i--;){
418 for(int j=0;j<2;++j){
419 if(c==2) goto end; // I know this sucks, but breaking two loops is stupid
420 Vector base;
421 base[i]=x[j];
422 // base now points to the surface and is normal to it at the same time
423 Plane p(base,base);
424 Vector intersection = p.GetIntersection(line);
425 if(isInside(intersection)){
426 // if we have a point on the edge it might already be contained
427 if(c==1 && intersections[0]==intersection)
428 continue;
429 intersections[c++]=intersection;
430 }
431 }
432 }
433 end:
434 if(c==2){
435 res.insert(LineSegment(intersections[0],intersections[1]));
436 }
437 return res;
438}
439
440std::string Cuboid_impl::toString() const{
441 return "Cuboid()";
442}
443
444enum ShapeType Cuboid_impl::getType() const
445{
446 return CuboidType;
447}
448
449/**
450 * \param N number of points on surface
451 */
452std::vector<Vector> Cuboid_impl::getHomogeneousPointsOnSurface(const size_t N) const {
453 std::vector<Vector> PointsOnSurface;
454 // sides
455 int n = sqrt((N - 1) / 6) + 1;
456 for (int i=0; i<=n; i++){
457 double ii = (double)i / (double)n;
458 for (int k=0; k<n; k++){
459 double kk = (double)k / (double)n;
460 PointsOnSurface.push_back(Vector(ii, kk, 1));
461 PointsOnSurface.push_back(Vector(ii, 1, 1-kk));
462 PointsOnSurface.push_back(Vector(ii, 1-kk, 0));
463 PointsOnSurface.push_back(Vector(ii, 0, kk));
464 }
465 }
466 // top and bottom
467 for (int i=1; i<n; i++){
468 double ii = (double)i / (double)n;
469 for (int k=1; k<n; k++){
470 double kk = (double)k / (double)n;
471 PointsOnSurface.push_back(Vector(0, ii, kk));
472 PointsOnSurface.push_back(Vector(1, ii, kk));
473 }
474 }
475 return PointsOnSurface;
476}
477
478std::vector<Vector> Cuboid_impl::getHomogeneousPointsInVolume(const size_t N) const {
479 ASSERT(0,
480 "Cuboid_impl::getHomogeneousPointsInVolume() - not implemented.");
481 return std::vector<Vector>();
482}
483
484Shape Cuboid(){
485 Shape::impl_ptr impl = Shape::impl_ptr(new Cuboid_impl());
486 return Shape(impl);
487}
488
489Shape Cuboid(const Vector &corner1, const Vector &corner2){
490 // make sure the two edges are upper left front and lower right back
491 Vector sortedC1;
492 Vector sortedC2;
493 for(int i=NDIM;i--;){
494 sortedC1[i] = std::min(corner1[i],corner2[i]);
495 sortedC2[i] = std::max(corner1[i],corner2[i]);
496 ASSERT(corner1[i]!=corner2[i],"Given points for cuboid edges did not define a valid space");
497 }
498 // get the middle point
499 Vector middle = (1./2.)*(sortedC1+sortedC2);
500 Vector factors = sortedC2-middle;
501 return translate(stretch(Cuboid(),factors),middle);
502}
Note: See TracBrowser for help on using the repository browser.