source: src/Tesselation/BoundaryTriangleSet.cpp@ 41a467

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 41a467 was 47d041, checked in by Frederik Heber <heber@…>, 13 years ago

HUGE: Removed all calls to Log(), eLog(), replaced by LOG() and ELOG().

  • Replaced DoLog(.) && (Log() << Verbose(.) << ... << std::endl) by Log(., ...).
  • Replaced Log() << Verbose(.) << .. << by Log(., ...)
  • on multiline used stringstream to generate and message which was finally used in LOG(., output.str())
  • there should be no more occurence of Log(). LOG() and ELOG() must be used instead.
  • Eventually, this will allow for storing all errors and re-printing them on program exit which would be very helpful to ascertain error-free runs for the user.
  • 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 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 "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}
195;
196
197/** Finds the point on the triangle to the point \a *x.
198 * We call Vector::GetIntersectionWithPlane() with \a * and the center of the triangle to receive an intersection point.
199 * Then we check the in-plane part (the part projected down onto plane). We check whether it crosses one of the
200 * boundary lines. If it does, we return this intersection as closest point, otherwise the projected point down.
201 * Thus we test if it's really on the plane and whether it's inside the triangle on the plane or not.
202 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
203 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
204 * the first two basepoints) or not.
205 * \param *x point
206 * \param *ClosestPoint desired closest point inside triangle to \a *x, is absolute vector
207 * \return Distance squared between \a *x and closest point inside triangle
208 */
209double BoundaryTriangleSet::GetClosestPointInsideTriangle(const Vector &x, Vector &ClosestPoint) const
210{
211 Info FunctionInfo(__func__);
212 Vector Direction;
213
214 // 1. get intersection with plane
215 LOG(1, "INFO: Looking for closest point of triangle " << *this << " to " << x << ".");
216 GetCenter(Direction);
217 try {
218 Line l = makeLineThrough(x, Direction);
219 ClosestPoint = Plane(NormalVector, (endpoints[0]->node->getPosition())).GetIntersection(l);
220 }
221 catch (LinearAlgebraException &excp) {
222 (ClosestPoint) = (x);
223 }
224
225 // 2. Calculate in plane part of line (x, intersection)
226 Vector InPlane = (x) - (ClosestPoint); // points from plane intersection to straight-down point
227 InPlane.ProjectOntoPlane(NormalVector);
228 InPlane += ClosestPoint;
229
230 LOG(2, "INFO: Triangle is " << *this << ".");
231 LOG(2, "INFO: Line is from " << Direction << " to " << x << ".");
232 LOG(2, "INFO: In-plane part is " << InPlane << ".");
233
234 // Calculate cross point between one baseline and the desired point such that distance is shortest
235 double ShortestDistance = -1.;
236 bool InsideFlag = false;
237 Vector CrossDirection[3];
238 Vector CrossPoint[3];
239 Vector helper;
240 for (int i = 0; i < 3; i++) {
241 // treat direction of line as normal of a (cut)plane and the desired point x as the plane offset, the intersect line with point
242 Direction = (endpoints[(i+1)%3]->node->getPosition()) - (endpoints[i%3]->node->getPosition());
243 // calculate intersection, line can never be parallel to Direction (is the same vector as PlaneNormal);
244 Line l = makeLineThrough((endpoints[i%3]->node->getPosition()), (endpoints[(i+1)%3]->node->getPosition()));
245 CrossPoint[i] = Plane(Direction, InPlane).GetIntersection(l);
246 CrossDirection[i] = CrossPoint[i] - InPlane;
247 CrossPoint[i] -= (endpoints[i%3]->node->getPosition()); // cross point was returned as absolute vector
248 const double s = CrossPoint[i].ScalarProduct(Direction)/Direction.NormSquared();
249 LOG(2, "INFO: Factor s is " << s << ".");
250 if ((s >= -MYEPSILON) && ((s-1.) <= MYEPSILON)) {
251 CrossPoint[i] += (endpoints[i%3]->node->getPosition()); // make cross point absolute again
252 LOG(2, "INFO: Crosspoint is " << CrossPoint[i] << ", intersecting BoundaryLine between " << endpoints[i % 3]->node->getPosition() << " and " << endpoints[(i + 1) % 3]->node->getPosition() << ".");
253 const double distance = CrossPoint[i].DistanceSquared(x);
254 if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
255 ShortestDistance = distance;
256 (ClosestPoint) = CrossPoint[i];
257 }
258 } else
259 CrossPoint[i].Zero();
260 }
261 InsideFlag = true;
262 for (int i = 0; i < 3; i++) {
263 const double sign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 1) % 3]);
264 const double othersign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 2) % 3]);
265
266 if ((sign > -MYEPSILON) && (othersign > -MYEPSILON)) // have different sign
267 InsideFlag = false;
268 }
269 if (InsideFlag) {
270 (ClosestPoint) = InPlane;
271 ShortestDistance = InPlane.DistanceSquared(x);
272 } else { // also check endnodes
273 for (int i = 0; i < 3; i++) {
274 const double distance = x.DistanceSquared(endpoints[i]->node->getPosition());
275 if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
276 ShortestDistance = distance;
277 (ClosestPoint) = (endpoints[i]->node->getPosition());
278 }
279 }
280 }
281 LOG(1, "INFO: Closest Point is " << ClosestPoint << " with shortest squared distance is " << ShortestDistance << ".");
282 return ShortestDistance;
283}
284;
285
286/** Checks whether lines is any of the three boundary lines this triangle contains.
287 * \param *line line to test
288 * \return true - line is of the triangle, false - is not
289 */
290bool BoundaryTriangleSet::ContainsBoundaryLine(const BoundaryLineSet * const line) const
291{
292 Info FunctionInfo(__func__);
293 for (int i = 0; i < 3; i++)
294 if (line == lines[i])
295 return true;
296 return false;
297}
298;
299
300/** Checks whether point is any of the three endpoints this triangle contains.
301 * \param *point point to test
302 * \return true - point is of the triangle, false - is not
303 */
304bool BoundaryTriangleSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
305{
306 Info FunctionInfo(__func__);
307 for (int i = 0; i < 3; i++)
308 if (point == endpoints[i])
309 return true;
310 return false;
311}
312;
313
314/** Checks whether point is any of the three endpoints this triangle contains.
315 * \param *point TesselPoint to test
316 * \return true - point is of the triangle, false - is not
317 */
318bool BoundaryTriangleSet::ContainsBoundaryPoint(const TesselPoint * const point) const
319{
320 Info FunctionInfo(__func__);
321 for (int i = 0; i < 3; i++)
322 if (point == endpoints[i]->node)
323 return true;
324 return false;
325}
326;
327
328/** Checks whether three given \a *Points coincide with triangle's endpoints.
329 * \param *Points[3] pointer to BoundaryPointSet
330 * \return true - is the very triangle, false - is not
331 */
332bool BoundaryTriangleSet::IsPresentTupel(const BoundaryPointSet * const Points[3]) const
333{
334 Info FunctionInfo(__func__);
335 LOG(1, "INFO: Checking " << Points[0] << "," << Points[1] << "," << Points[2] << " against " << endpoints[0] << "," << endpoints[1] << "," << endpoints[2] << ".");
336 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])
337
338 ));
339}
340;
341
342/** Checks whether three given \a *Points coincide with triangle's endpoints.
343 * \param *Points[3] pointer to BoundaryPointSet
344 * \return true - is the very triangle, false - is not
345 */
346bool BoundaryTriangleSet::IsPresentTupel(const BoundaryTriangleSet * const T) const
347{
348 Info FunctionInfo(__func__);
349 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])
350
351 ));
352}
353;
354
355/** Returns the endpoint which is not contained in the given \a *line.
356 * \param *line baseline defining two endpoints
357 * \return pointer third endpoint or NULL if line does not belong to triangle.
358 */
359class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(const BoundaryLineSet * const line) const
360{
361 Info FunctionInfo(__func__);
362 // sanity check
363 if (!ContainsBoundaryLine(line))
364 return NULL;
365 for (int i = 0; i < 3; i++)
366 if (!line->ContainsBoundaryPoint(endpoints[i]))
367 return endpoints[i];
368 // actually, that' impossible :)
369 return NULL;
370}
371;
372
373/** Returns the baseline which does not contain the given boundary point \a *point.
374 * \param *point endpoint which is neither endpoint of the desired line
375 * \return pointer to desired third baseline
376 */
377class BoundaryLineSet *BoundaryTriangleSet::GetThirdLine(const BoundaryPointSet * const point) const
378{
379 Info FunctionInfo(__func__);
380 // sanity check
381 if (!ContainsBoundaryPoint(point))
382 return NULL;
383 for (int i = 0; i < 3; i++)
384 if (!lines[i]->ContainsBoundaryPoint(point))
385 return lines[i];
386 // actually, that' impossible :)
387 return NULL;
388}
389;
390
391/** Calculates the center point of the triangle.
392 * Is third of the sum of all endpoints.
393 * \param *center central point on return.
394 */
395void BoundaryTriangleSet::GetCenter(Vector & center) const
396{
397 Info FunctionInfo(__func__);
398 center.Zero();
399 for (int i = 0; i < 3; i++)
400 (center) += (endpoints[i]->node->getPosition());
401 center.Scale(1. / 3.);
402 LOG(1, "INFO: Center is at " << center << ".");
403}
404
405/**
406 * gets the Plane defined by the three triangle Basepoints
407 */
408Plane BoundaryTriangleSet::getPlane() const{
409 ASSERT(endpoints[0] && endpoints[1] && endpoints[2], "Triangle not fully defined");
410
411 return Plane(endpoints[0]->node->getPosition(),
412 endpoints[1]->node->getPosition(),
413 endpoints[2]->node->getPosition());
414}
415
416Vector BoundaryTriangleSet::getEndpoint(int i) const{
417 ASSERT(i>=0 && i<3,"Index of Endpoint out of Range");
418
419 return endpoints[i]->node->getPosition();
420}
421
422string BoundaryTriangleSet::getEndpointName(int i) const{
423 ASSERT(i>=0 && i<3,"Index of Endpoint out of Range");
424
425 return endpoints[i]->node->getName();
426}
427
428/** output operator for BoundaryTriangleSet.
429 * \param &ost output stream
430 * \param &a boundary triangle
431 */
432ostream &operator <<(ostream &ost, const BoundaryTriangleSet &a)
433{
434 ost << "[" << a.Nr << "|" << a.getEndpointName(0) << "," << a.getEndpointName(1) << "," << a.getEndpointName(2) << "]";
435 // ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
436 // << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
437 return ost;
438}
439;
440
Note: See TracBrowser for help on using the repository browser.