source: src/Fragmentation/Exporters/SphericalPointDistribution.cpp@ 39616b

Last change on this file since 39616b was 39616b, checked in by Frederik Heber <heber@…>, 11 years ago

findPointAlignment() calculates mean rotation angle.

  • added calculateCenterOfGravity(), as we should use the center of gravity and not the center of sphere as rotational center (i.e. point on the plane to be rotated).
  • Property mode set to 100644
File size: 50.5 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2014 Frederik Heber. 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 * SphericalPointDistribution.cpp
25 *
26 * Created on: May 30, 2014
27 * Author: heber
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 "SphericalPointDistribution.hpp"
38
39#include "CodePatterns/Assert.hpp"
40#include "CodePatterns/IteratorAdaptors.hpp"
41#include "CodePatterns/Log.hpp"
42#include "CodePatterns/toString.hpp"
43
44#include <algorithm>
45#include <boost/assign.hpp>
46#include <cmath>
47#include <functional>
48#include <iterator>
49#include <limits>
50#include <list>
51#include <numeric>
52#include <vector>
53#include <map>
54
55#include "LinearAlgebra/Line.hpp"
56#include "LinearAlgebra/Plane.hpp"
57#include "LinearAlgebra/RealSpaceMatrix.hpp"
58#include "LinearAlgebra/Vector.hpp"
59
60using namespace boost::assign;
61
62// static entities
63const double SphericalPointDistribution::warn_amplitude = 1e-2;
64const double SphericalPointDistribution::L1THRESHOLD = 1e-2;
65const double SphericalPointDistribution::L2THRESHOLD = 2e-1;
66
67typedef std::vector<double> DistanceArray_t;
68
69// class generator: taken from www.cplusplus.com example std::generate
70struct c_unique {
71 unsigned int current;
72 c_unique() {current=0;}
73 unsigned int operator()() {return current++;}
74} UniqueNumber;
75
76struct c_unique_list {
77 unsigned int current;
78 c_unique_list() {current=0;}
79 std::list<unsigned int> operator()() {return std::list<unsigned int>(1, current++);}
80} UniqueNumberList;
81
82/** Calculate the center of a given set of points in \a _positions but only
83 * for those indicated by \a _indices.
84 *
85 */
86inline
87Vector calculateGeographicMidpoint(
88 const SphericalPointDistribution::VectorArray_t &_positions,
89 const SphericalPointDistribution::IndexList_t &_indices)
90{
91 Vector Center;
92 Center.Zero();
93 for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
94 iter != _indices.end(); ++iter)
95 Center += _positions[*iter];
96 if (!_indices.empty())
97 Center *= 1./(double)_indices.size();
98
99 return Center;
100}
101
102inline
103double calculateMinimumDistance(
104 const Vector &_center,
105 const SphericalPointDistribution::VectorArray_t &_points,
106 const SphericalPointDistribution::IndexList_t & _indices)
107{
108 double MinimumDistance = 0.;
109 for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
110 iter != _indices.end(); ++iter) {
111 const double angle = _center.Angle(_points[*iter]);
112 MinimumDistance += angle*angle;
113 }
114 return sqrt(MinimumDistance);
115}
116
117/** Calculates the center of minimum distance for a given set of points \a _points.
118 *
119 * According to http://www.geomidpoint.com/calculation.html this goes a follows:
120 * -# Let CurrentPoint be the geographic midpoint found in Method A. this is used as the starting point for the search.
121 * -# Let MinimumDistance be the sum total of all distances from the current point to all locations in 'Your Places'.
122 * -# Find the total distance between each location in 'Your Places' and all other locations in 'Your Places'. If any one of these locations has a new smallest distance then that location becomes the new CurrentPoint and MinimumDistance.
123 * -# Let TestDistance be PI/2 radians (6225 miles or 10018 km).
124 * -# Find the total distance between each of 8 test points and all locations in 'Your Places'. The test points are arranged in a circular pattern around the CurrentPoint at a distance of TestDistance to the north, northeast, east, southeast, south, southwest, west and northwest.
125 * -# If any of these 8 points has a new smallest distance then that point becomes the new CurrentPoint and MinimumDistance and go back to step 5 using that point.
126 * -# If none of the 8 test points has a new smallest distance then divide TestDistance by 2 and go back to step 5 using the same point.
127 * -# Repeat steps 5 to 7 until no new smallest distance can be found or until TestDistance is less than 0.00000002 radians.
128 *
129 * \param _points set of points
130 * \return Center of minimum distance for all these points, is always of length 1
131 */
132Vector SphericalPointDistribution::calculateCenterOfMinimumDistance(
133 const SphericalPointDistribution::VectorArray_t &_positions,
134 const SphericalPointDistribution::IndexList_t &_indices)
135{
136 ASSERT( _positions.size() >= _indices.size(),
137 "calculateCenterOfMinimumDistance() - less positions than indices given.");
138 Vector center(1.,0.,0.);
139
140 /// first treat some special cases
141 // no positions given: return x axis vector (NOT zero!)
142 {
143 if (_indices.empty())
144 return center;
145 // one position given: return it directly
146 if (_indices.size() == (size_t)1)
147 return _positions[*_indices.begin()];
148 // two positions on a line given: return closest point to (1.,0.,0.)
149// IndexList_t::const_iterator indexiter = _indices.begin();
150// const unsigned int firstindex = *indexiter++;
151// const unsigned int secondindex = *indexiter;
152// if ( fabs(_positions[firstindex].ScalarProduct(_positions[secondindex]) + 1.)
153// < std::numeric_limits<double>::epsilon()*1e4) {
154// Vector candidate;
155// if (_positions[firstindex].ScalarProduct(center) > _positions[secondindex].ScalarProduct(center))
156// candidate = _positions[firstindex];
157// else
158// candidate = _positions[secondindex];
159// // non-uniqueness: all positions on great circle, normal to given line are valid
160// // so, we just pick one because returning a unique point is topmost priority
161// Vector normal;
162// normal.GetOneNormalVector(candidate);
163// Vector othernormal = candidate;
164// othernormal.VectorProduct(normal);
165// // now both normal and othernormal describe the plane containing the great circle
166// Plane greatcircle(normal, zeroVec, othernormal);
167// // check which axis is contained and pick the one not
168// if (greatcircle.isContained(center)) {
169// center = Vector(0.,1.,0.);
170// if (greatcircle.isContained(center))
171// center = Vector(0.,0.,1.);
172// // now we are done cause a plane cannot contain all three axis vectors
173// }
174// center = greatcircle.getClosestPoint(candidate);
175// // assure length of 1
176// center.Normalize();
177//
178// return center;
179// }
180 // given points lie on a great circle and go completely round it
181 // two or more positions on a great circle given: return closest point to (1.,0.,0.)
182 {
183 bool AllNormal = true;
184 Vector Normal;
185 {
186 IndexList_t::const_iterator indexiter = _indices.begin();
187 Normal = _positions[*indexiter++];
188 Normal.VectorProduct(_positions[*indexiter++]);
189 Normal.Normalize();
190 for (;(AllNormal) && (indexiter != _indices.end()); ++indexiter)
191 AllNormal &= _positions[*indexiter].IsNormalTo(Normal, 1e-8);
192 }
193 double AngleSum = 0.;
194 if (AllNormal) {
195 // check by angle sum whether points go round are cover just one half
196 IndexList_t::const_iterator indexiter = _indices.begin();
197 Vector CurrentVector = _positions[*indexiter++];
198 for(; indexiter != _indices.end(); ++indexiter) {
199 AngleSum += CurrentVector.Angle(_positions[*indexiter]);
200 CurrentVector = _positions[*indexiter];
201 }
202 }
203 if (AngleSum - M_PI > std::numeric_limits<double>::epsilon()*1e4) {
204// Vector candidate;
205// double oldSKP = -1.;
206// for (IndexList_t::const_iterator iter = _indices.begin();
207// iter != _indices.end(); ++iter) {
208// const double newSKP = _positions[*iter].ScalarProduct(center);
209// if (newSKP > oldSKP) {
210// candidate = _positions[*iter];
211// oldSKP = newSKP;
212// }
213// }
214 // non-uniqueness: all positions on great circle, normal to given line are valid
215 // so, we just pick one because returning a unique point is topmost priority
216// Vector normal;
217// normal.GetOneNormalVector(candidate);
218// Vector othernormal = candidate;
219// othernormal.VectorProduct(normal);
220// // now both normal and othernormal describe the plane containing the great circle
221// Plane greatcircle(normal, zeroVec, othernormal);
222 // check which axis is contained and pick the one not
223// if (greatcircle.isContained(center)) {
224// center = Vector(0.,1.,0.);
225// if (greatcircle.isContained(center))
226// center = Vector(0.,0.,1.);
227// // now we are done cause a plane cannot contain all three axis vectors
228// }
229// center = greatcircle.getClosestPoint(candidate);
230// center = greatcircle.getNormal();
231 center = Normal;
232 // assure length of 1
233 center.Normalize();
234
235 return center;
236 }
237 }
238 }
239
240 // start with geographic midpoint
241 center = calculateGeographicMidpoint(_positions, _indices);
242 if (!center.IsZero()) {
243 center.Normalize();
244 LOG(5, "DEBUG: Starting with geographical midpoint of " << _positions << " under indices "
245 << _indices << " is " << center);
246 } else {
247 // any point is good actually
248 center = _positions[0];
249 LOG(5, "DEBUG: Starting with first position " << center);
250 }
251
252 // calculate initial MinimumDistance
253 double MinimumDistance = calculateMinimumDistance(center, _positions, _indices);
254 LOG(6, "DEBUG: MinimumDistance to this center is " << MinimumDistance);
255
256 // check all present points whether they may serve as a better center
257 for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
258 iter != _indices.end(); ++iter) {
259 const Vector &centerCandidate = _positions[*iter];
260 const double candidateDistance = calculateMinimumDistance(centerCandidate, _positions, _indices);
261 if (candidateDistance < MinimumDistance) {
262 MinimumDistance = candidateDistance;
263 center = centerCandidate;
264 LOG(6, "DEBUG: new MinimumDistance to current test point " << MinimumDistance
265 << " is " << center);
266 }
267 }
268 LOG(6, "DEBUG: new MinimumDistance to center " << center << " is " << MinimumDistance);
269
270 // now iterate over TestDistance
271 double TestDistance = Vector(1.,0.,0.).Angle(Vector(0.,1.,0.));
272// LOG(6, "DEBUG: initial TestDistance is " << TestDistance);
273
274 const double threshold = sqrt(std::numeric_limits<double>::epsilon());
275 // check each of eight test points at N, NE, E, SE, S, SW, W, NW
276 typedef std::vector<double> angles_t;
277 angles_t testangles;
278 testangles += 0./180.*M_PI, 45./180.*M_PI, 90./180.*M_PI, 135./180.*M_PI,
279 180./180.*M_PI, 225./180.*M_PI, 270./180.*M_PI, 315./180.*M_PI;
280 while (TestDistance > threshold) {
281 Vector OneNormal;
282 OneNormal.GetOneNormalVector(center);
283 Line RotationAxis(zeroVec, OneNormal);
284 Vector North = RotationAxis.rotateVector(center,TestDistance);
285 Line CompassRose(zeroVec, center);
286 bool updatedflag = false;
287 for (angles_t::const_iterator angleiter = testangles.begin();
288 angleiter != testangles.end(); ++angleiter) {
289 Vector centerCandidate = CompassRose.rotateVector(North, *angleiter);
290// centerCandidate.Normalize();
291 const double candidateDistance = calculateMinimumDistance(centerCandidate, _positions, _indices);
292 if (candidateDistance < MinimumDistance) {
293 MinimumDistance = candidateDistance;
294 center = centerCandidate;
295 updatedflag = true;
296 LOG(7, "DEBUG: new MinimumDistance to test point at " << *angleiter/M_PI*180.
297 << "° is " << MinimumDistance);
298 }
299 }
300
301 // if no new point, decrease TestDistance
302 if (!updatedflag) {
303 TestDistance *= 0.5;
304// LOG(6, "DEBUG: TestDistance is now " << TestDistance);
305 }
306 }
307 LOG(4, "DEBUG: Final MinimumDistance to center " << center << " is " << MinimumDistance);
308
309 return center;
310}
311
312Vector calculateCenterOfMinimumDistance(
313 const SphericalPointDistribution::PolygonWithIndices &_points)
314{
315 return SphericalPointDistribution::calculateCenterOfMinimumDistance(_points.polygon, _points.indices);
316}
317
318/** Calculate the center of a given set of points in \a _positions but only
319 * for those indicated by \a _indices.
320 *
321 */
322inline
323Vector calculateCenterOfGravity(
324 const SphericalPointDistribution::VectorArray_t &_positions,
325 const SphericalPointDistribution::IndexList_t &_indices)
326{
327 Vector Center;
328 Center.Zero();
329 for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
330 iter != _indices.end(); ++iter)
331 Center += _positions[*iter];
332 if (!_indices.empty())
333 Center *= 1./(double)_indices.size();
334
335 return Center;
336}
337
338/** Calculate the center of a given set of points in \a _positions but only
339 * for those indicated by \a _indices.
340 *
341 */
342inline
343Vector calculateCenter(
344 const SphericalPointDistribution::VectorArray_t &_positions,
345 const SphericalPointDistribution::IndexList_t &_indices)
346{
347// Vector Center;
348// Center.Zero();
349// for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
350// iter != _indices.end(); ++iter)
351// Center += _positions[*iter];
352// if (!_indices.empty())
353// Center *= 1./(double)_indices.size();
354//
355// return Center;
356 return SphericalPointDistribution::calculateCenterOfMinimumDistance(_positions, _indices);
357}
358
359/** Calculate the center of a given set of points in \a _positions but only
360 * for those indicated by \a _indices.
361 *
362 */
363inline
364Vector calculateCenter(
365 const SphericalPointDistribution::PolygonWithIndices &_polygon)
366{
367 return calculateCenter(_polygon.polygon, _polygon.indices);
368}
369
370inline
371DistanceArray_t calculatePairwiseDistances(
372 const SphericalPointDistribution::VectorArray_t &_points,
373 const SphericalPointDistribution::IndexTupleList_t &_indices
374 )
375{
376 DistanceArray_t result;
377 for (SphericalPointDistribution::IndexTupleList_t::const_iterator firstiter = _indices.begin();
378 firstiter != _indices.end(); ++firstiter) {
379
380 // calculate first center from possible tuple of indices
381 Vector FirstCenter;
382 ASSERT(!firstiter->empty(), "calculatePairwiseDistances() - there is an empty tuple.");
383 if (firstiter->size() == 1) {
384 FirstCenter = _points[*firstiter->begin()];
385 } else {
386 FirstCenter = calculateCenter( _points, *firstiter);
387 if (!FirstCenter.IsZero())
388 FirstCenter.Normalize();
389 }
390
391 for (SphericalPointDistribution::IndexTupleList_t::const_iterator seconditer = firstiter;
392 seconditer != _indices.end(); ++seconditer) {
393 if (firstiter == seconditer)
394 continue;
395
396 // calculate second center from possible tuple of indices
397 Vector SecondCenter;
398 ASSERT(!seconditer->empty(), "calculatePairwiseDistances() - there is an empty tuple.");
399 if (seconditer->size() == 1) {
400 SecondCenter = _points[*seconditer->begin()];
401 } else {
402 SecondCenter = calculateCenter( _points, *seconditer);
403 if (!SecondCenter.IsZero())
404 SecondCenter.Normalize();
405 }
406
407 // calculate distance between both centers
408 double distance = 2.; // greatest distance on surface of sphere with radius 1.
409 if ((!FirstCenter.IsZero()) && (!SecondCenter.IsZero()))
410 distance = (FirstCenter - SecondCenter).NormSquared();
411 result.push_back(distance);
412 }
413 }
414 return result;
415}
416
417/** Decides by an orthonormal third vector whether the sign of the rotation
418 * angle should be negative or positive.
419 *
420 * \return -1 or 1
421 */
422inline
423double determineSignOfRotation(
424 const Vector &_oldPosition,
425 const Vector &_newPosition,
426 const Vector &_RotationAxis
427 )
428{
429 Vector dreiBein(_oldPosition);
430 dreiBein.VectorProduct(_RotationAxis);
431 ASSERT( !dreiBein.IsZero(), "determineSignOfRotation() - dreiBein is zero.");
432 dreiBein.Normalize();
433 const double sign =
434 (dreiBein.ScalarProduct(_newPosition) < 0.) ? -1. : +1.;
435 LOG(6, "DEBUG: oldCenter on plane is " << _oldPosition
436 << ", newCenter on plane is " << _newPosition
437 << ", and dreiBein is " << dreiBein);
438 return sign;
439}
440
441/** Convenience function to recalculate old and new center for determining plane
442 * rotation.
443 */
444inline
445void calculateOldAndNewCenters(
446 Vector &_oldCenter,
447 Vector &_newCenter,
448 const SphericalPointDistribution::PolygonWithIndices &_referencepositions,
449 const SphericalPointDistribution::PolygonWithIndices &_currentpositions)
450{
451 _oldCenter = calculateCenter(_referencepositions.polygon, _referencepositions.indices);
452 // C++11 defines a copy_n function ...
453 _newCenter = calculateCenter( _currentpositions.polygon, _currentpositions.indices);
454}
455/** Returns squared L2 error of the given \a _Matching.
456 *
457 * We compare the pair-wise distances of each associated matching
458 * and check whether these distances each match between \a _old and
459 * \a _new.
460 *
461 * \param _old first set of points (fewer or equal to \a _new)
462 * \param _new second set of points
463 * \param _Matching matching between the two sets
464 * \return pair with L1 and squared L2 error
465 */
466std::pair<double, double> SphericalPointDistribution::calculateErrorOfMatching(
467 const VectorArray_t &_old,
468 const VectorArray_t &_new,
469 const IndexTupleList_t &_Matching)
470{
471 std::pair<double, double> errors( std::make_pair( 0., 0. ) );
472
473 if (_Matching.size() > 1) {
474 LOG(5, "INFO: Matching is " << _Matching);
475
476 // calculate all pair-wise distances
477 IndexTupleList_t keys(_old.size(), IndexList_t() );
478 std::generate (keys.begin(), keys.end(), UniqueNumberList);
479
480 const DistanceArray_t firstdistances = calculatePairwiseDistances(_old, keys);
481 const DistanceArray_t seconddistances = calculatePairwiseDistances(_new, _Matching);
482
483 ASSERT( firstdistances.size() == seconddistances.size(),
484 "calculateL2ErrorOfMatching() - mismatch in pair-wise distance array sizes.");
485 DistanceArray_t::const_iterator firstiter = firstdistances.begin();
486 DistanceArray_t::const_iterator seconditer = seconddistances.begin();
487 for (;(firstiter != firstdistances.end()) && (seconditer != seconddistances.end());
488 ++firstiter, ++seconditer) {
489 const double gap = fabs(*firstiter - *seconditer);
490 // L1 error
491 if (errors.first < gap)
492 errors.first = gap;
493 // L2 error
494 errors.second += gap*gap;
495 }
496 // there is at least one distance, we've checked that before
497 errors.second *= 1./(double)firstdistances.size();
498 } else {
499 // check whether we have any zero centers: Combining points on new sphere may result
500 // in zero centers
501 for (SphericalPointDistribution::IndexTupleList_t::const_iterator iter = _Matching.begin();
502 iter != _Matching.end(); ++iter) {
503 if ((iter->size() != 1) && (calculateCenter( _new, *iter).IsZero())) {
504 errors.first = 2.;
505 errors.second = 2.;
506 }
507 }
508 }
509 LOG(4, "INFO: Resulting errors for matching (L1, L2): "
510 << errors.first << "," << errors.second << ".");
511
512 return errors;
513}
514
515SphericalPointDistribution::Polygon_t SphericalPointDistribution::removeMatchingPoints(
516 const PolygonWithIndices &_points
517 )
518{
519 SphericalPointDistribution::Polygon_t remainingpoints;
520 IndexArray_t indices(_points.indices.begin(), _points.indices.end());
521 std::sort(indices.begin(), indices.end());
522 LOG(4, "DEBUG: sorted matching is " << indices);
523 IndexArray_t remainingindices(_points.polygon.size(), -1);
524 std::generate(remainingindices.begin(), remainingindices.end(), UniqueNumber);
525 IndexArray_t::iterator remainiter = std::set_difference(
526 remainingindices.begin(), remainingindices.end(),
527 indices.begin(), indices.end(),
528 remainingindices.begin());
529 remainingindices.erase(remainiter, remainingindices.end());
530 LOG(4, "DEBUG: remaining indices are " << remainingindices);
531 for (IndexArray_t::const_iterator iter = remainingindices.begin();
532 iter != remainingindices.end(); ++iter) {
533 remainingpoints.push_back(_points.polygon[*iter]);
534 }
535
536 return remainingpoints;
537}
538
539/** Recursive function to go through all possible matchings.
540 *
541 * \param _MCS structure holding global information to the recursion
542 * \param _matching current matching being build up
543 * \param _indices contains still available indices
544 * \param _remainingweights current weights to fill (each weight a place)
545 * \param _remainiter iterator over the weights, indicating the current position we match
546 * \param _matchingsize
547 */
548void SphericalPointDistribution::recurseMatchings(
549 MatchingControlStructure &_MCS,
550 IndexTupleList_t &_matching,
551 IndexList_t _indices,
552 WeightsArray_t &_remainingweights,
553 WeightsArray_t::iterator _remainiter,
554 const unsigned int _matchingsize
555 )
556{
557 LOG(5, "DEBUG: Recursing with current matching " << _matching
558 << ", remaining indices " << _indices
559 << ", and remaining weights " << _matchingsize);
560 if (!_MCS.foundflag) {
561 LOG(5, "DEBUG: Current matching has size " << _matching.size() << ", places left " << _matchingsize);
562 if (_matchingsize > 0) {
563 // go through all indices
564 for (IndexList_t::iterator iter = _indices.begin();
565 (iter != _indices.end()) && (!_MCS.foundflag);) {
566
567 // check whether we can stay in the current bin or have to move on to next one
568 if (*_remainiter == 0) {
569 // we need to move on
570 if (_remainiter != _remainingweights.end()) {
571 ++_remainiter;
572 } else {
573 // as we check _matchingsize > 0 this should be impossible
574 ASSERT( 0, "recurseMatchings() - we must not come to this position.");
575 }
576 }
577
578 // advance in matching to current bin to fill in
579 const size_t OldIndex = std::distance(_remainingweights.begin(), _remainiter);
580 while (_matching.size() <= OldIndex) { // add empty lists if new bin is opened
581 LOG(6, "DEBUG: Extending _matching.");
582 _matching.push_back( IndexList_t() );
583 }
584 IndexTupleList_t::iterator filliniter = _matching.begin();
585 std::advance(filliniter, OldIndex);
586
587 // check whether connection between bins' indices and candidate is satisfied
588 if (!_MCS.adjacency.empty()) {
589 adjacency_t::const_iterator finder = _MCS.adjacency.find(*iter);
590 ASSERT( finder != _MCS.adjacency.end(),
591 "recurseMatchings() - "+toString(*iter)+" is not in adjacency list.");
592 if ((!filliniter->empty())
593 && (finder->second.find(*filliniter->begin()) == finder->second.end())) {
594 LOG(5, "DEBUG; Skipping index " << *iter
595 << " as is not connected to current set." << *filliniter << ".");
596 ++iter; // note that index-loop does not contain incrementor
597 continue;
598 }
599 }
600
601 // add index to matching
602 filliniter->push_back(*iter);
603 --(*_remainiter);
604 LOG(6, "DEBUG: Adding " << *iter << " to matching at " << OldIndex << ".");
605 // remove index but keep iterator to position (is the next to erase element)
606 IndexList_t::iterator backupiter = _indices.erase(iter);
607 // recurse with decreased _matchingsize
608 recurseMatchings(_MCS, _matching, _indices, _remainingweights, _remainiter, _matchingsize-1);
609 // re-add chosen index and reset index to new position
610 _indices.insert(backupiter, filliniter->back());
611 iter = backupiter;
612 // remove index from _matching to make space for the next one
613 filliniter->pop_back();
614 ++(*_remainiter);
615 }
616 // gone through all indices then exit recursion
617 if (_matching.empty())
618 _MCS.foundflag = true;
619 } else {
620 LOG(4, "INFO: Found matching " << _matching);
621 // calculate errors
622 std::pair<double, double> errors = calculateErrorOfMatching(
623 _MCS.oldpoints, _MCS.newpoints, _matching);
624 if (errors.first < L1THRESHOLD) {
625 _MCS.bestmatching = _matching;
626 _MCS.foundflag = true;
627 } else if (_MCS.bestL2 > errors.second) {
628 _MCS.bestmatching = _matching;
629 _MCS.bestL2 = errors.second;
630 }
631 }
632 }
633}
634
635SphericalPointDistribution::MatchingControlStructure::MatchingControlStructure(
636 const adjacency_t &_adjacency,
637 const VectorArray_t &_oldpoints,
638 const VectorArray_t &_newpoints,
639 const WeightsArray_t &_weights
640 ) :
641 foundflag(false),
642 bestL2(std::numeric_limits<double>::max()),
643 adjacency(_adjacency),
644 oldpoints(_oldpoints),
645 newpoints(_newpoints),
646 weights(_weights)
647{}
648
649/** Finds combinatorially the best matching between points in \a _polygon
650 * and \a _newpolygon.
651 *
652 * We find the matching with the smallest L2 error, where we break when we stumble
653 * upon a matching with zero error.
654 *
655 * As points in \a _polygon may be have a weight greater 1 we have to match it to
656 * multiple points in \a _newpolygon. Eventually, these multiple points are combined
657 * for their center of weight, which is the only thing follow-up function see of
658 * these multiple points. Hence, we actually modify \a _newpolygon in the process
659 * such that the returned IndexList_t indicates a bijective mapping in the end.
660 *
661 * \sa recurseMatchings() for going through all matchings
662 *
663 * \param _polygon here, we have indices 0,1,2,...
664 * \param _newpolygon and here we need to find the correct indices
665 * \return control structure containing the matching and more
666 */
667SphericalPointDistribution::MatchingControlStructure
668SphericalPointDistribution::findBestMatching(
669 const WeightedPolygon_t &_polygon
670 )
671{
672 // transform lists into arrays
673 VectorArray_t oldpoints;
674 VectorArray_t newpoints;
675 WeightsArray_t weights;
676 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
677 iter != _polygon.end(); ++iter) {
678 oldpoints.push_back(iter->first);
679 weights.push_back(iter->second);
680 }
681 newpoints.insert(newpoints.begin(), points.begin(), points.end() );
682 MatchingControlStructure MCS(adjacency, oldpoints, newpoints, weights);
683
684 // search for bestmatching combinatorially
685 {
686 // translate polygon into vector to enable index addressing
687 IndexList_t indices(points.size());
688 std::generate(indices.begin(), indices.end(), UniqueNumber);
689 IndexTupleList_t matching;
690
691 // walk through all matchings
692 WeightsArray_t remainingweights = MCS.weights;
693 unsigned int placesleft = std::accumulate(remainingweights.begin(), remainingweights.end(), 0);
694 recurseMatchings(MCS, matching, indices, remainingweights, remainingweights.begin(), placesleft);
695 }
696 if (MCS.foundflag)
697 LOG(3, "Found a best matching beneath L1 threshold of " << L1THRESHOLD);
698 else {
699 if (MCS.bestL2 < warn_amplitude)
700 LOG(3, "Picking matching is " << MCS.bestmatching << " with best L2 error of "
701 << MCS.bestL2);
702 else if (MCS.bestL2 < L2THRESHOLD)
703 ELOG(2, "Picking matching is " << MCS.bestmatching
704 << " with rather large L2 error of " << MCS.bestL2);
705 else
706 ASSERT(0, "findBestMatching() - matching "+toString(MCS.bestmatching)
707 +" has L2 error of "+toString(MCS.bestL2)+" that is too large.");
708 }
709
710 return MCS;
711}
712
713SphericalPointDistribution::IndexList_t SphericalPointDistribution::joinPoints(
714 Polygon_t &_newpolygon,
715 const VectorArray_t &_newpoints,
716 const IndexTupleList_t &_bestmatching
717 )
718{
719 // combine all multiple points
720 IndexList_t IndexList;
721 IndexArray_t removalpoints;
722 unsigned int UniqueIndex = _newpolygon.size(); // all indices up to size are used right now
723 VectorArray_t newCenters;
724 newCenters.reserve(_bestmatching.size());
725 for (IndexTupleList_t::const_iterator tupleiter = _bestmatching.begin();
726 tupleiter != _bestmatching.end(); ++tupleiter) {
727 ASSERT (tupleiter->size() > 0,
728 "findBestMatching() - encountered tuple in bestmatching with size 0.");
729 if (tupleiter->size() == 1) {
730 // add point and index
731 IndexList.push_back(*tupleiter->begin());
732 } else {
733 // combine into weighted and normalized center
734 Vector Center = calculateCenter(_newpoints, *tupleiter);
735 Center.Normalize();
736 _newpolygon.push_back(Center);
737 LOG(5, "DEBUG: Combining " << tupleiter->size() << " points to weighted center "
738 << Center << " with new index " << UniqueIndex);
739 // mark for removal
740 removalpoints.insert(removalpoints.end(), tupleiter->begin(), tupleiter->end());
741 // add new index
742 IndexList.push_back(UniqueIndex++);
743 }
744 }
745 // IndexList is now our new bestmatching (that is bijective)
746 LOG(4, "DEBUG: Our new bijective IndexList reads as " << IndexList);
747
748 // modifying _newpolygon: remove all points in removalpoints, add those in newCenters
749 Polygon_t allnewpoints = _newpolygon;
750 {
751 _newpolygon.clear();
752 std::sort(removalpoints.begin(), removalpoints.end());
753 size_t i = 0;
754 IndexArray_t::const_iterator removeiter = removalpoints.begin();
755 for (Polygon_t::iterator iter = allnewpoints.begin();
756 iter != allnewpoints.end(); ++iter, ++i) {
757 if ((removeiter != removalpoints.end()) && (i == *removeiter)) {
758 // don't add, go to next remove index
759 ++removeiter;
760 } else {
761 // otherwise add points
762 _newpolygon.push_back(*iter);
763 }
764 }
765 }
766 LOG(4, "DEBUG: The polygon with recentered points removed is " << _newpolygon);
767
768 // map IndexList to new shrinked _newpolygon
769 typedef std::set<unsigned int> IndexSet_t;
770 IndexSet_t SortedIndexList(IndexList.begin(), IndexList.end());
771 IndexList.clear();
772 {
773 size_t offset = 0;
774 IndexSet_t::const_iterator listiter = SortedIndexList.begin();
775 IndexArray_t::const_iterator removeiter = removalpoints.begin();
776 for (size_t i = 0; i < allnewpoints.size(); ++i) {
777 if ((removeiter != removalpoints.end()) && (i == *removeiter)) {
778 ++offset;
779 ++removeiter;
780 } else if ((listiter != SortedIndexList.end()) && (i == *listiter)) {
781 IndexList.push_back(*listiter - offset);
782 ++listiter;
783 }
784 }
785 }
786 LOG(4, "DEBUG: Our new bijective IndexList corrected for removed points reads as "
787 << IndexList);
788
789 return IndexList;
790}
791
792SphericalPointDistribution::Rotation_t SphericalPointDistribution::findPlaneAligningRotation(
793 const PolygonWithIndices &_referencepositions,
794 const PolygonWithIndices &_currentpositions
795 )
796{
797 bool dontcheck = false;
798 // initialize to no rotation
799 Rotation_t Rotation;
800 Rotation.first.Zero();
801 Rotation.first[0] = 1.;
802 Rotation.second = 0.;
803
804 // calculate center of triangle/line/point consisting of first points of matching
805 Vector oldCenter;
806 Vector newCenter;
807 calculateOldAndNewCenters(
808 oldCenter, newCenter,
809 _referencepositions, _currentpositions);
810
811 ASSERT( !oldCenter.IsZero() && !newCenter.IsZero(),
812 "findPlaneAligningRotation() - either old "+toString(oldCenter)
813 +" or new center "+toString(newCenter)+" are zero.");
814 LOG(4, "DEBUG: oldCenter is " << oldCenter << ", newCenter is " << newCenter);
815 if (!oldCenter.IsEqualTo(newCenter)) {
816 // calculate rotation axis and angle
817 Rotation.first = oldCenter;
818 Rotation.first.VectorProduct(newCenter);
819 Rotation.first.Normalize();
820 // construct reference vector to determine direction of rotation
821 const double sign = determineSignOfRotation(newCenter, oldCenter, Rotation.first);
822 Rotation.second = sign * oldCenter.Angle(newCenter);
823 } else {
824 // no rotation required anymore
825 }
826
827#ifndef NDEBUG
828 // check: rotation brings newCenter onto oldCenter position
829 if (!dontcheck) {
830 Line Axis(zeroVec, Rotation.first);
831 Vector test = Axis.rotateVector(newCenter, Rotation.second);
832 LOG(4, "CHECK: rotated newCenter is " << test
833 << ", oldCenter is " << oldCenter);
834 ASSERT( (test - oldCenter).NormSquared() < std::numeric_limits<double>::epsilon()*1e4,
835 "matchSphericalPointDistributions() - rotation does not work as expected by "
836 +toString((test - oldCenter).NormSquared())+".");
837 }
838#endif
839
840 return Rotation;
841}
842
843SphericalPointDistribution::Rotation_t SphericalPointDistribution::findPointAligningRotation(
844 const PolygonWithIndices &remainingold,
845 const PolygonWithIndices &remainingnew)
846{
847 // initialize rotation to zero
848 Rotation_t Rotation;
849 Rotation.first.Zero();
850 Rotation.first[0] = 1.;
851 Rotation.second = 0.;
852
853 // recalculate center
854 Vector oldCenter;
855 Vector newCenter;
856 calculateOldAndNewCenters(
857 oldCenter, newCenter,
858 remainingold, remainingnew);
859
860 // we rotate at oldCenter and around the radial direction, which is again given
861 // by oldCenter.
862 Rotation.first = oldCenter;
863 Rotation.first.Normalize(); // note weighted sum of normalized weight is not normalized
864
865 // calculate center of the rotational plane
866 newCenter = calculateCenterOfGravity(remainingnew.polygon, remainingnew.indices);
867 oldCenter = calculateCenterOfGravity(remainingold.polygon, remainingold.indices);
868 LOG(6, "DEBUG: Using oldCenter " << oldCenter << " as rotation center and "
869 << Rotation.first << " as axis.");
870
871 LOG(6, "DEBUG: old indices are " << remainingold.indices
872 << ", new indices are " << remainingnew.indices);
873 IndexList_t::const_iterator newiter = remainingnew.indices.begin();
874 IndexList_t::const_iterator olditer = remainingold.indices.begin();
875 for (;
876 (newiter != remainingnew.indices.end()) && (olditer != remainingold.indices.end());
877 ++newiter,++olditer) {
878 Vector newPosition = remainingnew.polygon[*newiter];
879 Vector oldPosition = remainingold.polygon[*olditer];
880 LOG(6, "DEBUG: oldPosition is " << oldPosition << " (length: "
881 << oldPosition.Norm() << ") and newPosition is " << newPosition << " length(: "
882 << newPosition.Norm() << ")");
883
884 if (!oldPosition.IsEqualTo(newPosition)) {
885 oldPosition -= oldCenter;
886 newPosition -= newCenter;
887 oldPosition = (oldPosition - oldPosition.Projection(Rotation.first));
888 newPosition = (newPosition - newPosition.Projection(Rotation.first));
889 LOG(6, "DEBUG: Positions after projection are " << oldPosition << " and " << newPosition);
890
891 // construct reference vector to determine direction of rotation
892 const double sign = determineSignOfRotation(newPosition, oldPosition, Rotation.first);
893 LOG(6, "DEBUG: Determining angle between " << oldPosition << " and " << newPosition);
894 const double angle = sign * newPosition.Angle(oldPosition);
895 LOG(6, "DEBUG: Adding " << angle << " to weighted rotation sum.");
896 Rotation.second += angle;
897 } else {
898 LOG(6, "DEBUG: oldPosition and newPosition are equivalent, hence no orientating rotation.");
899 }
900 }
901 Rotation.second *= 1./(double)remainingnew.indices.size();
902
903 return Rotation;
904}
905
906void SphericalPointDistribution::initSelf(const int _NumberOfPoints)
907{
908 switch (_NumberOfPoints)
909 {
910 case 0:
911 points = get<0>();
912 adjacency = getConnections<0>();
913 break;
914 case 1:
915 points = get<1>();
916 adjacency = getConnections<1>();
917 break;
918 case 2:
919 points = get<2>();
920 adjacency = getConnections<2>();
921 break;
922 case 3:
923 points = get<3>();
924 adjacency = getConnections<3>();
925 break;
926 case 4:
927 points = get<4>();
928 adjacency = getConnections<4>();
929 break;
930 case 5:
931 points = get<5>();
932 adjacency = getConnections<5>();
933 break;
934 case 6:
935 points = get<6>();
936 adjacency = getConnections<6>();
937 break;
938 case 7:
939 points = get<7>();
940 adjacency = getConnections<7>();
941 break;
942 case 8:
943 points = get<8>();
944 adjacency = getConnections<8>();
945 break;
946 case 9:
947 points = get<9>();
948 adjacency = getConnections<9>();
949 break;
950 case 10:
951 points = get<10>();
952 adjacency = getConnections<10>();
953 break;
954 case 11:
955 points = get<11>();
956 adjacency = getConnections<11>();
957 break;
958 case 12:
959 points = get<12>();
960 adjacency = getConnections<12>();
961 break;
962 case 14:
963 points = get<14>();
964 adjacency = getConnections<14>();
965 break;
966 default:
967 ASSERT(0, "SphericalPointDistribution::initSelf() - cannot deal with the case "
968 +toString(_NumberOfPoints)+".");
969 }
970 LOG(3, "DEBUG: Ideal polygon is " << points);
971}
972
973SphericalPointDistribution::Polygon_t
974SphericalPointDistribution::getRemainingPoints(
975 const WeightedPolygon_t &_polygon,
976 const int _N)
977{
978 SphericalPointDistribution::Polygon_t remainingpoints;
979
980 // initialze to given number of points
981 initSelf(_N);
982 LOG(2, "INFO: Matching old polygon " << _polygon
983 << " with new polygon " << points);
984
985 // check whether any points will remain vacant
986 int RemainingPoints = _N;
987 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
988 iter != _polygon.end(); ++iter)
989 RemainingPoints -= iter->second;
990 if (RemainingPoints == 0)
991 return remainingpoints;
992
993 if (_N > 0) {
994 // combine multiple points and create simple IndexList from IndexTupleList
995 MatchingControlStructure MCS = findBestMatching(_polygon);
996 IndexList_t bestmatching = joinPoints(points, MCS.newpoints, MCS.bestmatching);
997 LOG(2, "INFO: Best matching is " << bestmatching);
998
999 const size_t NumberIds = std::min(bestmatching.size(), (size_t)3);
1000 // create old set
1001 PolygonWithIndices oldSet;
1002 oldSet.indices.resize(NumberIds, -1);
1003 std::generate(oldSet.indices.begin(), oldSet.indices.end(), UniqueNumber);
1004 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
1005 iter != _polygon.end(); ++iter)
1006 oldSet.polygon.push_back(iter->first);
1007
1008 // _newpolygon has changed, so now convert to array with matched indices
1009 PolygonWithIndices newSet;
1010 SphericalPointDistribution::IndexList_t::const_iterator beginiter = bestmatching.begin();
1011 SphericalPointDistribution::IndexList_t::const_iterator enditer = bestmatching.begin();
1012 std::advance(enditer, NumberIds);
1013 newSet.indices.resize(NumberIds, -1);
1014 std::copy(beginiter, enditer, newSet.indices.begin());
1015 std::copy(points.begin(),points.end(), std::back_inserter(newSet.polygon));
1016
1017 // determine rotation angles to align the two point distributions with
1018 // respect to bestmatching:
1019 // we use the center between the three first matching points
1020 /// the first rotation brings these two centers to coincide
1021 PolygonWithIndices rotatednewSet = newSet;
1022 {
1023 Rotation_t Rotation = findPlaneAligningRotation(oldSet, newSet);
1024 LOG(5, "DEBUG: Rotating coordinate system by " << Rotation.second
1025 << " around axis " << Rotation.first);
1026 Line Axis(zeroVec, Rotation.first);
1027
1028 // apply rotation angle to bring newCenter to oldCenter
1029 for (VectorArray_t::iterator iter = rotatednewSet.polygon.begin();
1030 iter != rotatednewSet.polygon.end(); ++iter) {
1031 Vector &current = *iter;
1032 LOG(6, "DEBUG: Original point is " << current);
1033 current = Axis.rotateVector(current, Rotation.second);
1034 LOG(6, "DEBUG: Rotated point is " << current);
1035 }
1036
1037#ifndef NDEBUG
1038 // check: rotated "newCenter" should now equal oldCenter
1039 // we don't check in case of two points as these lie on a great circle
1040 // and the center cannot stably be recalculated. We may reactivate this
1041 // when we calculate centers only once
1042 if (oldSet.indices.size() > 2) {
1043 Vector oldCenter;
1044 Vector rotatednewCenter;
1045 calculateOldAndNewCenters(
1046 oldCenter, rotatednewCenter,
1047 oldSet, rotatednewSet);
1048 oldCenter.Normalize();
1049 rotatednewCenter.Normalize();
1050 // check whether centers are anti-parallel (factor -1)
1051 // then we have the "non-unique poles" situation: points lie on great circle
1052 // and both poles are valid solution
1053 if (fabs(oldCenter.ScalarProduct(rotatednewCenter) + 1.)
1054 < std::numeric_limits<double>::epsilon()*1e4)
1055 rotatednewCenter *= -1.;
1056 LOG(4, "CHECK: rotatednewCenter is " << rotatednewCenter
1057 << ", oldCenter is " << oldCenter);
1058 const double difference = (rotatednewCenter - oldCenter).NormSquared();
1059 ASSERT( difference < std::numeric_limits<double>::epsilon()*1e4,
1060 "matchSphericalPointDistributions() - rotation does not work as expected by "
1061 +toString(difference)+".");
1062 }
1063#endif
1064 }
1065 /// the second (orientation) rotation aligns the planes such that the
1066 /// points themselves coincide
1067 if (bestmatching.size() > 1) {
1068 Rotation_t Rotation = findPointAligningRotation(oldSet, rotatednewSet);
1069
1070 // construct RotationAxis and two points on its plane, defining the angle
1071 Rotation.first.Normalize();
1072 const Line RotationAxis(zeroVec, Rotation.first);
1073
1074 LOG(5, "DEBUG: Rotating around self is " << Rotation.second
1075 << " around axis " << RotationAxis);
1076
1077#ifndef NDEBUG
1078 // check: first bestmatching in rotated_newpolygon and remainingnew
1079 // should now equal
1080 {
1081 const IndexList_t::const_iterator iter = bestmatching.begin();
1082
1083 // check whether both old and newPosition are at same distance to oldCenter
1084 Vector oldCenter = calculateCenter(oldSet);
1085 const double distance = fabs(
1086 (oldSet.polygon[0] - oldCenter).NormSquared()
1087 - (rotatednewSet.polygon[*iter] - oldCenter).NormSquared()
1088 );
1089 LOG(4, "CHECK: Squared distance between oldPosition and newPosition "
1090 << " with respect to oldCenter " << oldCenter << " is " << distance);
1091// ASSERT( distance < warn_amplitude,
1092// "matchSphericalPointDistributions() - old and newPosition's squared distance to oldCenter differs by "
1093// +toString(distance));
1094
1095 Vector rotatednew = RotationAxis.rotateVector(
1096 rotatednewSet.polygon[*iter],
1097 Rotation.second);
1098 LOG(4, "CHECK: rotated first new bestmatching is " << rotatednew
1099 << " while old was " << oldSet.polygon[0]);
1100 const double difference = (rotatednew - oldSet.polygon[0]).NormSquared();
1101 ASSERT( difference < distance+warn_amplitude,
1102 "matchSphericalPointDistributions() - orientation rotation ends up off by "
1103 +toString(difference)+", more than "
1104 +toString(distance+warn_amplitude)+".");
1105 }
1106#endif
1107
1108 for (VectorArray_t::iterator iter = rotatednewSet.polygon.begin();
1109 iter != rotatednewSet.polygon.end(); ++iter) {
1110 Vector &current = *iter;
1111 LOG(6, "DEBUG: Original point is " << current);
1112 current = RotationAxis.rotateVector(current, Rotation.second);
1113 LOG(6, "DEBUG: Rotated point is " << current);
1114 }
1115 }
1116
1117 // remove all points in matching and return remaining ones
1118 SphericalPointDistribution::Polygon_t remainingpoints =
1119 removeMatchingPoints(rotatednewSet);
1120 LOG(2, "INFO: Remaining points are " << remainingpoints);
1121 return remainingpoints;
1122 } else
1123 return points;
1124}
1125
1126SphericalPointDistribution::PolygonWithIndexTuples
1127SphericalPointDistribution::getAssociatedPoints(
1128 const WeightedPolygon_t &_polygon,
1129 const int _N)
1130{
1131 SphericalPointDistribution::PolygonWithIndexTuples associatedpoints;
1132
1133 // initialze to given number of points
1134 initSelf(_N);
1135 LOG(2, "INFO: Matching old polygon " << _polygon
1136 << " with new polygon " << points);
1137
1138 // check whether there are any points to associate
1139 if (_polygon.empty()) {
1140 associatedpoints.polygon.insert(
1141 associatedpoints.polygon.end(),
1142 points.begin(), points.end());
1143 return associatedpoints;
1144 }
1145
1146 if (_N > 0) {
1147 // combine multiple points and create simple IndexList from IndexTupleList
1148 MatchingControlStructure MCS = findBestMatching(_polygon);
1149 IndexList_t bestmatching = joinPoints(points, MCS.newpoints, MCS.bestmatching);
1150 LOG(2, "INFO: Best matching is " << bestmatching);
1151
1152 // gather the associated points (not the joined ones)
1153 associatedpoints.polygon = MCS.newpoints;
1154 // gather indices
1155 associatedpoints.indices = MCS.bestmatching;
1156
1157 /// now we only need to rotate the associated points to match the given ones
1158 /// with respect to the joined points in points
1159
1160 const size_t NumberIds = std::min(bestmatching.size(), (size_t)3);
1161 // create old set
1162 PolygonWithIndices oldSet;
1163 oldSet.indices.resize(NumberIds, -1);
1164 std::generate(oldSet.indices.begin(), oldSet.indices.end(), UniqueNumber);
1165 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
1166 iter != _polygon.end(); ++iter)
1167 oldSet.polygon.push_back(iter->first);
1168
1169 // _newpolygon has changed, so now convert to array with matched indices
1170 PolygonWithIndices newSet;
1171 SphericalPointDistribution::IndexList_t::const_iterator beginiter = bestmatching.begin();
1172 SphericalPointDistribution::IndexList_t::const_iterator enditer = bestmatching.begin();
1173 std::advance(enditer, NumberIds);
1174 newSet.indices.resize(NumberIds, -1);
1175 std::copy(beginiter, enditer, newSet.indices.begin());
1176 std::copy(points.begin(),points.end(), std::back_inserter(newSet.polygon));
1177
1178 // determine rotation angles to align the two point distributions with
1179 // respect to bestmatching:
1180 // we use the center between the three first matching points
1181 /// the first rotation brings these two centers to coincide
1182 PolygonWithIndices rotatednewSet = newSet;
1183 {
1184 Rotation_t Rotation = findPlaneAligningRotation(oldSet, newSet);
1185 LOG(5, "DEBUG: Rotating coordinate system by " << Rotation.second
1186 << " around axis " << Rotation.first);
1187 Line Axis(zeroVec, Rotation.first);
1188
1189 // apply rotation angle to bring newCenter to oldCenter in joined points
1190 for (VectorArray_t::iterator iter = rotatednewSet.polygon.begin();
1191 iter != rotatednewSet.polygon.end(); ++iter) {
1192 Vector &current = *iter;
1193 LOG(6, "DEBUG: Original joined point is " << current);
1194 current = Axis.rotateVector(current, Rotation.second);
1195 LOG(6, "DEBUG: Rotated joined point is " << current);
1196 }
1197
1198 // apply rotation angle to the whole set of associated points
1199 for (VectorArray_t::iterator iter = associatedpoints.polygon.begin();
1200 iter != associatedpoints.polygon.end(); ++iter) {
1201 Vector &current = *iter;
1202 LOG(6, "DEBUG: Original associated point is " << current);
1203 current = Axis.rotateVector(current, Rotation.second);
1204 LOG(6, "DEBUG: Rotated associated point is " << current);
1205 }
1206
1207#ifndef NDEBUG
1208 // check: rotated "newCenter" should now equal oldCenter
1209 // we don't check in case of two points as these lie on a great circle
1210 // and the center cannot stably be recalculated. We may reactivate this
1211 // when we calculate centers only once
1212 if (oldSet.indices.size() > 2) {
1213 Vector oldCenter;
1214 Vector rotatednewCenter;
1215 calculateOldAndNewCenters(
1216 oldCenter, rotatednewCenter,
1217 oldSet, rotatednewSet);
1218 oldCenter.Normalize();
1219 rotatednewCenter.Normalize();
1220 // check whether centers are anti-parallel (factor -1)
1221 // then we have the "non-unique poles" situation: points lie on great circle
1222 // and both poles are valid solution
1223 if (fabs(oldCenter.ScalarProduct(rotatednewCenter) + 1.)
1224 < std::numeric_limits<double>::epsilon()*1e4)
1225 rotatednewCenter *= -1.;
1226 LOG(4, "CHECK: rotatednewCenter is " << rotatednewCenter
1227 << ", oldCenter is " << oldCenter);
1228 const double difference = (rotatednewCenter - oldCenter).NormSquared();
1229 ASSERT( difference < std::numeric_limits<double>::epsilon()*1e4,
1230 "matchSphericalPointDistributions() - rotation does not work as expected by "
1231 +toString(difference)+".");
1232 }
1233#endif
1234 }
1235 /// the second (orientation) rotation aligns the planes such that the
1236 /// points themselves coincide
1237 if (bestmatching.size() > 1) {
1238 Rotation_t Rotation = findPointAligningRotation(oldSet, rotatednewSet);
1239
1240 // construct RotationAxis and two points on its plane, defining the angle
1241 Rotation.first.Normalize();
1242 const Line RotationAxis(zeroVec, Rotation.first);
1243
1244 LOG(5, "DEBUG: Rotating around self is " << Rotation.second
1245 << " around axis " << RotationAxis);
1246
1247#ifndef NDEBUG
1248 // check: first bestmatching in rotated_newpolygon and remainingnew
1249 // should now equal
1250 {
1251 const IndexList_t::const_iterator iter = bestmatching.begin();
1252
1253 // check whether both old and newPosition are at same distance to oldCenter
1254 Vector oldCenter = calculateCenter(oldSet);
1255 const double distance = fabs(
1256 (oldSet.polygon[0] - oldCenter).NormSquared()
1257 - (rotatednewSet.polygon[*iter] - oldCenter).NormSquared()
1258 );
1259 LOG(4, "CHECK: Squared distance between oldPosition and newPosition "
1260 << " with respect to oldCenter " << oldCenter << " is " << distance);
1261// ASSERT( distance < warn_amplitude,
1262// "matchSphericalPointDistributions() - old and newPosition's squared distance to oldCenter differs by "
1263// +toString(distance));
1264
1265 Vector rotatednew = RotationAxis.rotateVector(
1266 rotatednewSet.polygon[*iter],
1267 Rotation.second);
1268 LOG(4, "CHECK: rotated first new bestmatching is " << rotatednew
1269 << " while old was " << oldSet.polygon[0]);
1270 const double difference = (rotatednew - oldSet.polygon[0]).NormSquared();
1271 ASSERT( difference < distance+warn_amplitude,
1272 "matchSphericalPointDistributions() - orientation rotation ends up off by "
1273 +toString(difference)+", more than "
1274 +toString(distance+warn_amplitude)+".");
1275 }
1276#endif
1277
1278 // align the set of associated points only here
1279 for (VectorArray_t::iterator iter = associatedpoints.polygon.begin();
1280 iter != associatedpoints.polygon.end(); ++iter) {
1281 Vector &current = *iter;
1282 LOG(6, "DEBUG: Original associated point is " << current);
1283 current = RotationAxis.rotateVector(current, Rotation.second);
1284 LOG(6, "DEBUG: Rotated associated point is " << current);
1285 }
1286 }
1287 }
1288
1289 return associatedpoints;
1290}
1291
1292SphericalPointDistribution::PolygonWithIndexTuples
1293SphericalPointDistribution::getIdentityAssociation(
1294 const WeightedPolygon_t &_polygon)
1295{
1296 unsigned int index = 0;
1297 SphericalPointDistribution::PolygonWithIndexTuples returnpolygon;
1298 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
1299 iter != _polygon.end(); ++iter, ++index) {
1300 returnpolygon.polygon.push_back( iter->first );
1301 ASSERT( iter->second == 1,
1302 "getIdentityAssociation() - bond with direction "
1303 +toString(iter->second)
1304 +" has degree higher than 1, getIdentityAssociation makes no sense.");
1305 returnpolygon.indices.push_back( IndexList_t(1, index) );
1306 }
1307 return returnpolygon;
1308}
Note: See TracBrowser for help on using the repository browser.