source: src/Tesselation/BoundaryTriangleSet.cpp@ 6f0841

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

Shifted all modules related to atoms into own subfolder src/Atom/

  • also created own convenience library for this. This makes unit testing on list containing TesselPoint or atom a lot easier.
  • shifted TesselPoint to src/Atom from src/Tesselation and adapted include's.
  • Property mode set to 100644
File size: 16.6 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2011 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * BoundaryTriangleSet.cpp
10 *
11 * Created on: Jul 29, 2010
12 * Author: heber
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 "BoundaryTriangleSet.hpp"
23
24#include <iostream>
25
26#include "BoundaryLineSet.hpp"
27#include "BoundaryPointSet.hpp"
28#include "Atom/TesselPoint.hpp"
29
30#include "Helpers/defs.hpp"
31
32#include "CodePatterns/Assert.hpp"
33#include "CodePatterns/Info.hpp"
34#include "CodePatterns/Log.hpp"
35#include "CodePatterns/Verbose.hpp"
36#include "LinearAlgebra/Exceptions.hpp"
37#include "LinearAlgebra/Line.hpp"
38#include "LinearAlgebra/Plane.hpp"
39#include "LinearAlgebra/Vector.hpp"
40
41using namespace std;
42
43/** Constructor for BoundaryTriangleSet.
44 */
45BoundaryTriangleSet::BoundaryTriangleSet() :
46 Nr(-1)
47{
48 Info FunctionInfo(__func__);
49 for (int i = 0; i < 3; i++) {
50 endpoints[i] = NULL;
51 lines[i] = NULL;
52 }
53}
54;
55
56/** Constructor for BoundaryTriangleSet with three lines.
57 * \param *line[3] lines that make up the triangle
58 * \param number number of triangle
59 */
60BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet * const line[3], const int number) :
61 Nr(number)
62{
63 Info FunctionInfo(__func__);
64 // set number
65 // set lines
66 for (int i = 0; i < 3; i++) {
67 lines[i] = line[i];
68 lines[i]->AddTriangle(this);
69 }
70 // get ascending order of endpoints
71 PointMap OrderMap;
72 for (int i = 0; i < 3; i++) {
73 // for all three lines
74 for (int j = 0; j < 2; j++) { // for both endpoints
75 OrderMap.insert(pair<int, class BoundaryPointSet *> (line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
76 // and we don't care whether insertion fails
77 }
78 }
79 // set endpoints
80 int Counter = 0;
81 LOG(0, "New triangle " << Nr << " with end points: ");
82 for (PointMap::iterator runner = OrderMap.begin(); runner != OrderMap.end(); runner++) {
83 endpoints[Counter] = runner->second;
84 LOG(0, " " << *endpoints[Counter]);
85 Counter++;
86 }
87 ASSERT(Counter >= 3,"We have a triangle with only two distinct endpoints!");
88};
89
90
91/** Destructor of BoundaryTriangleSet.
92 * Removes itself from each of its lines' LineMap and removes them if necessary.
93 * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
94 */
95BoundaryTriangleSet::~BoundaryTriangleSet()
96{
97 Info FunctionInfo(__func__);
98 for (int i = 0; i < 3; i++) {
99 if (lines[i] != NULL) {
100 if (lines[i]->triangles.erase(Nr)) {
101 //LOG(0, "Triangle Nr." << Nr << " erased in line " << *lines[i] << ".");
102 }
103 if (lines[i]->triangles.empty()) {
104 //LOG(0, *lines[i] << " is no more attached to any triangle, erasing.");
105 delete (lines[i]);
106 lines[i] = NULL;
107 }
108 }
109 }
110 //LOG(0, "Erasing triangle Nr." << Nr << " itself.");
111}
112;
113
114/** Calculates the normal vector for this triangle.
115 * Is made unique by comparison with \a OtherVector to point in the other direction.
116 * \param &OtherVector direction vector to make normal vector unique.
117 */
118void BoundaryTriangleSet::GetNormalVector(const Vector &OtherVector)
119{
120 Info FunctionInfo(__func__);
121 // get normal vector
122 NormalVector = Plane((endpoints[0]->node->getPosition()),
123 (endpoints[1]->node->getPosition()),
124 (endpoints[2]->node->getPosition())).getNormal();
125
126 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
127 if (NormalVector.ScalarProduct(OtherVector) > 0.)
128 NormalVector.Scale(-1.);
129 LOG(1, "Normal Vector is " << NormalVector << ".");
130}
131;
132
133/** Finds the point on the triangle \a *BTS through which the line defined by \a *MolCenter and \a *x crosses.
134 * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
135 * Thus we test if it's really on the plane and whether it's inside the triangle on the plane or not.
136 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
137 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
138 * the first two basepoints) or not.
139 * \param *out output stream for debugging
140 * \param &MolCenter offset vector of line
141 * \param &x second endpoint of line, minus \a *MolCenter is directional vector of line
142 * \param &Intersection intersection on plane on return
143 * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
144 */
145
146bool BoundaryTriangleSet::GetIntersectionInsideTriangle(const Vector & MolCenter, const Vector & x, Vector &Intersection) const
147{
148 Info FunctionInfo(__func__);
149 Vector CrossPoint;
150 Vector helper;
151
152 try {
153 Line centerLine = makeLineThrough(MolCenter, x);
154 Intersection = Plane(NormalVector, (endpoints[0]->node->getPosition())).GetIntersection(centerLine);
155
156 LOG(1, "INFO: Triangle is " << *this << ".");
157 LOG(1, "INFO: Line is from " << MolCenter << " to " << x << ".");
158 LOG(1, "INFO: Intersection is " << Intersection << ".");
159
160 if (Intersection.DistanceSquared(endpoints[0]->node->getPosition()) < MYEPSILON) {
161 LOG(1, "Intersection coindices with first endpoint.");
162 return true;
163 } else if (Intersection.DistanceSquared(endpoints[1]->node->getPosition()) < MYEPSILON) {
164 LOG(1, "Intersection coindices with second endpoint.");
165 return true;
166 } else if (Intersection.DistanceSquared(endpoints[2]->node->getPosition()) < MYEPSILON) {
167 LOG(1, "Intersection coindices with third endpoint.");
168 return true;
169 }
170 // Calculate cross point between one baseline and the line from the third endpoint to intersection
171 int i = 0;
172 do {
173 Line line1 = makeLineThrough((endpoints[i%3]->node->getPosition()),(endpoints[(i+1)%3]->node->getPosition()));
174 Line line2 = makeLineThrough((endpoints[(i+2)%3]->node->getPosition()),Intersection);
175 CrossPoint = line1.getIntersection(line2);
176 helper = (endpoints[(i+1)%3]->node->getPosition()) - (endpoints[i%3]->node->getPosition());
177 CrossPoint -= (endpoints[i%3]->node->getPosition()); // cross point was returned as absolute vector
178 const double s = CrossPoint.ScalarProduct(helper)/helper.NormSquared();
179 LOG(1, "INFO: Factor s is " << s << ".");
180 if ((s < -MYEPSILON) || ((s-1.) > MYEPSILON)) {
181 LOG(1, "INFO: Crosspoint " << CrossPoint << "outside of triangle.");
182 return false;
183 }
184 i++;
185 } while (i < 3);
186 LOG(1, "INFO: Crosspoint " << CrossPoint << " inside of triangle.");
187 return true;
188 }
189 catch (LinearAlgebraException &excp) {
190 LOG(1, boost::diagnostic_information(excp));
191 ELOG(1, "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!");
192 return false;
193 }
194 return true;
195}
196
197
198/** Finds the point on the triangle to the point \a *x.
199 * We call Vector::GetIntersectionWithPlane() with \a * and the center of the triangle to receive an intersection point.
200 * Then we check the in-plane part (the part projected down onto plane). We check whether it crosses one of the
201 * boundary lines. If it does, we return this intersection as closest point, otherwise the projected point down.
202 * Thus we test if it's really on the plane and whether it's inside the triangle on the plane or not.
203 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
204 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
205 * the first two basepoints) or not.
206 * \param *x point
207 * \param *ClosestPoint desired closest point inside triangle to \a *x, is absolute vector
208 * \return Distance squared between \a *x and closest point inside triangle
209 */
210double BoundaryTriangleSet::GetClosestPointInsideTriangle(const Vector &x, Vector &ClosestPoint) const
211{
212 Info FunctionInfo(__func__);
213 Vector Direction;
214
215 // 1. get intersection with plane
216 LOG(1, "INFO: Looking for closest point of triangle " << *this << " to " << x << ".");
217 GetCenter(Direction);
218 try {
219 Line l = makeLineThrough(x, Direction);
220 ClosestPoint = Plane(NormalVector, (endpoints[0]->node->getPosition())).GetIntersection(l);
221 }
222 catch (LinearAlgebraException &excp) {
223 (ClosestPoint) = (x);
224 }
225
226 // 2. Calculate in plane part of line (x, intersection)
227 Vector InPlane = (x) - (ClosestPoint); // points from plane intersection to straight-down point
228 InPlane.ProjectOntoPlane(NormalVector);
229 InPlane += ClosestPoint;
230
231 LOG(2, "INFO: Triangle is " << *this << ".");
232 LOG(2, "INFO: Line is from " << Direction << " to " << x << ".");
233 LOG(2, "INFO: In-plane part is " << InPlane << ".");
234
235 // Calculate cross point between one baseline and the desired point such that distance is shortest
236 double ShortestDistance = -1.;
237 bool InsideFlag = false;
238 Vector CrossDirection[3];
239 Vector CrossPoint[3];
240 Vector helper;
241 for (int i = 0; i < 3; i++) {
242 // treat direction of line as normal of a (cut)plane and the desired point x as the plane offset, the intersect line with point
243 Direction = (endpoints[(i+1)%3]->node->getPosition()) - (endpoints[i%3]->node->getPosition());
244 // calculate intersection, line can never be parallel to Direction (is the same vector as PlaneNormal);
245 Line l = makeLineThrough((endpoints[i%3]->node->getPosition()), (endpoints[(i+1)%3]->node->getPosition()));
246 CrossPoint[i] = Plane(Direction, InPlane).GetIntersection(l);
247 CrossDirection[i] = CrossPoint[i] - InPlane;
248 CrossPoint[i] -= (endpoints[i%3]->node->getPosition()); // cross point was returned as absolute vector
249 const double s = CrossPoint[i].ScalarProduct(Direction)/Direction.NormSquared();
250 LOG(2, "INFO: Factor s is " << s << ".");
251 if ((s >= -MYEPSILON) && ((s-1.) <= MYEPSILON)) {
252 CrossPoint[i] += (endpoints[i%3]->node->getPosition()); // make cross point absolute again
253 LOG(2, "INFO: Crosspoint is " << CrossPoint[i] << ", intersecting BoundaryLine between " << endpoints[i % 3]->node->getPosition() << " and " << endpoints[(i + 1) % 3]->node->getPosition() << ".");
254 const double distance = CrossPoint[i].DistanceSquared(x);
255 if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
256 ShortestDistance = distance;
257 (ClosestPoint) = CrossPoint[i];
258 }
259 } else
260 CrossPoint[i].Zero();
261 }
262 InsideFlag = true;
263 for (int i = 0; i < 3; i++) {
264 const double sign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 1) % 3]);
265 const double othersign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 2) % 3]);
266
267 if ((sign > -MYEPSILON) && (othersign > -MYEPSILON)) // have different sign
268 InsideFlag = false;
269 }
270 if (InsideFlag) {
271 (ClosestPoint) = InPlane;
272 ShortestDistance = InPlane.DistanceSquared(x);
273 } else { // also check endnodes
274 for (int i = 0; i < 3; i++) {
275 const double distance = x.DistanceSquared(endpoints[i]->node->getPosition());
276 if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
277 ShortestDistance = distance;
278 (ClosestPoint) = (endpoints[i]->node->getPosition());
279 }
280 }
281 }
282 LOG(1, "INFO: Closest Point is " << ClosestPoint << " with shortest squared distance is " << ShortestDistance << ".");
283 return ShortestDistance;
284}
285;
286
287/** Checks whether lines is any of the three boundary lines this triangle contains.
288 * \param *line line to test
289 * \return true - line is of the triangle, false - is not
290 */
291bool BoundaryTriangleSet::ContainsBoundaryLine(const BoundaryLineSet * const line) const
292{
293 Info FunctionInfo(__func__);
294 for (int i = 0; i < 3; i++)
295 if (line == lines[i])
296 return true;
297 return false;
298}
299;
300
301/** Checks whether point is any of the three endpoints this triangle contains.
302 * \param *point point to test
303 * \return true - point is of the triangle, false - is not
304 */
305bool BoundaryTriangleSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
306{
307 Info FunctionInfo(__func__);
308 for (int i = 0; i < 3; i++)
309 if (point == endpoints[i])
310 return true;
311 return false;
312}
313;
314
315/** Checks whether point is any of the three endpoints this triangle contains.
316 * \param *point TesselPoint to test
317 * \return true - point is of the triangle, false - is not
318 */
319bool BoundaryTriangleSet::ContainsBoundaryPoint(const TesselPoint * const point) const
320{
321 Info FunctionInfo(__func__);
322 for (int i = 0; i < 3; i++)
323 if (point == endpoints[i]->node)
324 return true;
325 return false;
326}
327;
328
329/** Checks whether three given \a *Points coincide with triangle's endpoints.
330 * \param *Points[3] pointer to BoundaryPointSet
331 * \return true - is the very triangle, false - is not
332 */
333bool BoundaryTriangleSet::IsPresentTupel(const BoundaryPointSet * const Points[3]) const
334{
335 Info FunctionInfo(__func__);
336 LOG(1, "INFO: Checking " << Points[0] << "," << Points[1] << "," << Points[2] << " against " << endpoints[0] << "," << endpoints[1] << "," << endpoints[2] << ".");
337 return (((endpoints[0] == Points[0]) || (endpoints[0] == Points[1]) || (endpoints[0] == Points[2])) && ((endpoints[1] == Points[0]) || (endpoints[1] == Points[1]) || (endpoints[1] == Points[2])) && ((endpoints[2] == Points[0]) || (endpoints[2] == Points[1]) || (endpoints[2] == Points[2])
338
339 ));
340}
341;
342
343/** Checks whether three given \a *Points coincide with triangle's endpoints.
344 * \param *Points[3] pointer to BoundaryPointSet
345 * \return true - is the very triangle, false - is not
346 */
347bool BoundaryTriangleSet::IsPresentTupel(const BoundaryTriangleSet * const T) const
348{
349 Info FunctionInfo(__func__);
350 return (((endpoints[0] == T->endpoints[0]) || (endpoints[0] == T->endpoints[1]) || (endpoints[0] == T->endpoints[2])) && ((endpoints[1] == T->endpoints[0]) || (endpoints[1] == T->endpoints[1]) || (endpoints[1] == T->endpoints[2])) && ((endpoints[2] == T->endpoints[0]) || (endpoints[2] == T->endpoints[1]) || (endpoints[2] == T->endpoints[2])
351
352 ));
353}
354;
355
356/** Returns the endpoint which is not contained in the given \a *line.
357 * \param *line baseline defining two endpoints
358 * \return pointer third endpoint or NULL if line does not belong to triangle.
359 */
360class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(const BoundaryLineSet * const line) const
361{
362 Info FunctionInfo(__func__);
363 // sanity check
364 if (!ContainsBoundaryLine(line))
365 return NULL;
366 for (int i = 0; i < 3; i++)
367 if (!line->ContainsBoundaryPoint(endpoints[i]))
368 return endpoints[i];
369 // actually, that' impossible :)
370 return NULL;
371}
372;
373
374/** Returns the baseline which does not contain the given boundary point \a *point.
375 * \param *point endpoint which is neither endpoint of the desired line
376 * \return pointer to desired third baseline
377 */
378class BoundaryLineSet *BoundaryTriangleSet::GetThirdLine(const BoundaryPointSet * const point) const
379{
380 Info FunctionInfo(__func__);
381 // sanity check
382 if (!ContainsBoundaryPoint(point))
383 return NULL;
384 for (int i = 0; i < 3; i++)
385 if (!lines[i]->ContainsBoundaryPoint(point))
386 return lines[i];
387 // actually, that' impossible :)
388 return NULL;
389}
390;
391
392/** Calculates the center point of the triangle.
393 * Is third of the sum of all endpoints.
394 * \param *center central point on return.
395 */
396void BoundaryTriangleSet::GetCenter(Vector & center) const
397{
398 Info FunctionInfo(__func__);
399 center.Zero();
400 for (int i = 0; i < 3; i++)
401 (center) += (endpoints[i]->node->getPosition());
402 center.Scale(1. / 3.);
403 LOG(1, "INFO: Center is at " << center << ".");
404}
405
406/**
407 * gets the Plane defined by the three triangle Basepoints
408 */
409Plane BoundaryTriangleSet::getPlane() const{
410 ASSERT(endpoints[0] && endpoints[1] && endpoints[2], "Triangle not fully defined");
411
412 return Plane(endpoints[0]->node->getPosition(),
413 endpoints[1]->node->getPosition(),
414 endpoints[2]->node->getPosition());
415}
416
417Vector BoundaryTriangleSet::getEndpoint(int i) const{
418 ASSERT(i>=0 && i<3,"Index of Endpoint out of Range");
419
420 return endpoints[i]->node->getPosition();
421}
422
423string BoundaryTriangleSet::getEndpointName(int i) const{
424 ASSERT(i>=0 && i<3,"Index of Endpoint out of Range");
425
426 return endpoints[i]->node->getName();
427}
428
429/** output operator for BoundaryTriangleSet.
430 * \param &ost output stream
431 * \param &a boundary triangle
432 */
433ostream &operator <<(ostream &ost, const BoundaryTriangleSet &a)
434{
435 ost << "[" << a.Nr << "|" << a.getEndpointName(0) << "," << a.getEndpointName(1) << "," << a.getEndpointName(2) << "]";
436 // ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
437 // << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
438 return ost;
439}
440;
441
Note: See TracBrowser for help on using the repository browser.