source: src/Fragmentation/Exporters/SphericalPointDistribution.cpp@ 4492f1

Last change on this file since 4492f1 was 66700f2, checked in by Frederik Heber <heber@…>, 9 years ago

Added calculation of center of minimum distance by bisection.

  • this will give us a unique a definite point independent of the (rotational) position of the point set on the unit sphere.
  • added unit test.
  • TESTFIX: Marked SphericalPointDistributionUnitTest as XFAIL.
  • Property mode set to 100644
File size: 39.4 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::SQRT_3(sqrt(3.0));
64const double SphericalPointDistribution::warn_amplitude = 1e-2;
65const double SphericalPointDistribution::L1THRESHOLD = 1e-2;
66const double SphericalPointDistribution::L2THRESHOLD = 2e-1;
67
68typedef std::vector<double> DistanceArray_t;
69
70// class generator: taken from www.cplusplus.com example std::generate
71struct c_unique {
72 unsigned int current;
73 c_unique() {current=0;}
74 unsigned int operator()() {return current++;}
75} UniqueNumber;
76
77struct c_unique_list {
78 unsigned int current;
79 c_unique_list() {current=0;}
80 std::list<unsigned int> operator()() {return std::list<unsigned int>(1, current++);}
81} UniqueNumberList;
82
83/** Calculate the center of a given set of points in \a _positions but only
84 * for those indicated by \a _indices.
85 *
86 */
87inline
88Vector calculateGeographicMidpoint(
89 const SphericalPointDistribution::VectorArray_t &_positions,
90 const SphericalPointDistribution::IndexList_t &_indices)
91{
92 Vector Center;
93 Center.Zero();
94 for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
95 iter != _indices.end(); ++iter)
96 Center += _positions[*iter];
97 if (!_indices.empty())
98 Center *= 1./(double)_indices.size();
99
100 return Center;
101}
102
103inline
104double calculateMinimumDistance(
105 const Vector &_center,
106 const SphericalPointDistribution::VectorArray_t &_points,
107 const SphericalPointDistribution::IndexList_t & _indices)
108{
109 double MinimumDistance = 0.;
110 for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
111 iter != _indices.end(); ++iter) {
112 const double angle = _center.Angle(_points[*iter]);
113 MinimumDistance += angle*angle;
114 }
115 return sqrt(MinimumDistance);
116}
117
118/** Calculates the center of minimum distance for a given set of points \a _points.
119 *
120 * According to http://www.geomidpoint.com/calculation.html this goes a follows:
121 * -# Let CurrentPoint be the geographic midpoint found in Method A. this is used as the starting point for the search.
122 * -# Let MinimumDistance be the sum total of all distances from the current point to all locations in 'Your Places'.
123 * -# 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.
124 * -# Let TestDistance be PI/2 radians (6225 miles or 10018 km).
125 * -# 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.
126 * -# 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.
127 * -# 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.
128 * -# Repeat steps 5 to 7 until no new smallest distance can be found or until TestDistance is less than 0.00000002 radians.
129 *
130 * \param _points set of points
131 * \return Center of minimum distance for all these points, is always of length 1
132 */
133Vector SphericalPointDistribution::calculateCenterOfMinimumDistance(
134 const SphericalPointDistribution::VectorArray_t &_positions,
135 const SphericalPointDistribution::IndexList_t &_indices)
136{
137 ASSERT( _positions.size() >= _indices.size(),
138 "calculateCenterOfMinimumDistance() - less positions than indices given.");
139 Vector center(1.,0.,0.);
140
141 /// first treat some special cases
142 // no positions given: return x axis vector (NOT zero!)
143 {
144 if (_indices.empty())
145 return center;
146 // one position given: return it directly
147 if (_positions.size() == (size_t)1)
148 return _positions[0];
149 // two positions on a line given: return closest point to (1.,0.,0.)
150 if (fabs(_positions[0].ScalarProduct(_positions[1]) + 1.)
151 < std::numeric_limits<double>::epsilon()*1e4) {
152 Vector candidate;
153 if (_positions[0].ScalarProduct(center) > _positions[1].ScalarProduct(center))
154 candidate = _positions[0];
155 else
156 candidate = _positions[1];
157 // non-uniqueness: all positions on great circle, normal to given line are valid
158 // so, we just pick one because returning a unique point is topmost priority
159 Vector normal;
160 normal.GetOneNormalVector(candidate);
161 Vector othernormal = candidate;
162 othernormal.VectorProduct(normal);
163 // now both normal and othernormal describe the plane containing the great circle
164 Plane greatcircle(normal, zeroVec, othernormal);
165 // check which axis is contained and pick the one not
166 if (greatcircle.isContained(center)) {
167 center = Vector(0.,1.,0.);
168 if (greatcircle.isContained(center))
169 center = Vector(0.,0.,1.);
170 // now we are done cause a plane cannot contain all three axis vectors
171 }
172 center = greatcircle.getClosestPoint(candidate);
173 // assure length of 1
174 center.Normalize();
175 }
176 }
177
178 // start with geographic midpoint
179 center = calculateGeographicMidpoint(_positions, _indices);
180 if (!center.IsZero()) {
181 center.Normalize();
182 LOG(4, "DEBUG: Starting with geographical midpoint of " << _positions << " under indices "
183 << _indices << " is " << center);
184 } else {
185 // any point is good actually
186 center = _positions[0];
187 LOG(4, "DEBUG: Starting with first position " << center);
188 }
189
190 // calculate initial MinimumDistance
191 double MinimumDistance = calculateMinimumDistance(center, _positions, _indices);
192 LOG(5, "DEBUG: MinimumDistance to this center is " << MinimumDistance);
193
194 // check all present points whether they may serve as a better center
195 for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
196 iter != _indices.end(); ++iter) {
197 const Vector &centerCandidate = _positions[*iter];
198 const double candidateDistance = calculateMinimumDistance(centerCandidate, _positions, _indices);
199 if (candidateDistance < MinimumDistance) {
200 MinimumDistance = candidateDistance;
201 center = centerCandidate;
202 LOG(5, "DEBUG: new MinimumDistance to current test point " << MinimumDistance
203 << " is " << center);
204 }
205 }
206 LOG(5, "DEBUG: new MinimumDistance to center " << center << " is " << MinimumDistance);
207
208 // now iterate over TestDistance
209 double TestDistance = Vector(1.,0.,0.).Angle(Vector(0.,1.,0.));
210// LOG(6, "DEBUG: initial TestDistance is " << TestDistance);
211
212 const double threshold = sqrt(std::numeric_limits<double>::epsilon());
213 // check each of eight test points at N, NE, E, SE, S, SW, W, NW
214 typedef std::vector<double> angles_t;
215 angles_t testangles;
216 testangles += 0./180.*M_PI, 45./180.*M_PI, 90./180.*M_PI, 135./180.*M_PI,
217 180./180.*M_PI, 225./180.*M_PI, 270./180.*M_PI, 315./180.*M_PI;
218 while (TestDistance > threshold) {
219 Vector OneNormal;
220 OneNormal.GetOneNormalVector(center);
221 Line RotationAxis(zeroVec, OneNormal);
222 Vector North = RotationAxis.rotateVector(center,TestDistance);
223 Line CompassRose(zeroVec, center);
224 bool updatedflag = false;
225 for (angles_t::const_iterator angleiter = testangles.begin();
226 angleiter != testangles.end(); ++angleiter) {
227 Vector centerCandidate = CompassRose.rotateVector(North, *angleiter);
228// centerCandidate.Normalize();
229 const double candidateDistance = calculateMinimumDistance(centerCandidate, _positions, _indices);
230 if (candidateDistance < MinimumDistance) {
231 MinimumDistance = candidateDistance;
232 center = centerCandidate;
233 updatedflag = true;
234 LOG(5, "DEBUG: new MinimumDistance to test point at " << *angleiter/M_PI*180.
235 << "° is " << MinimumDistance);
236 }
237 }
238
239 // if no new point, decrease TestDistance
240 if (!updatedflag) {
241 TestDistance *= 0.5;
242// LOG(6, "DEBUG: TestDistance is now " << TestDistance);
243 }
244 }
245 LOG(4, "DEBUG: Final MinimumDistance to center " << center << " is " << MinimumDistance);
246
247 return center;
248}
249
250Vector calculateCenterOfMinimumDistance(
251 const SphericalPointDistribution::PolygonWithIndices &_points)
252{
253 return SphericalPointDistribution::calculateCenterOfMinimumDistance(_points.polygon, _points.indices);
254}
255
256/** Calculate the center of a given set of points in \a _positions but only
257 * for those indicated by \a _indices.
258 *
259 */
260inline
261Vector calculateCenter(
262 const SphericalPointDistribution::VectorArray_t &_positions,
263 const SphericalPointDistribution::IndexList_t &_indices)
264{
265// Vector Center;
266// Center.Zero();
267// for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
268// iter != _indices.end(); ++iter)
269// Center += _positions[*iter];
270// if (!_indices.empty())
271// Center *= 1./(double)_indices.size();
272//
273// return Center;
274 return SphericalPointDistribution::calculateCenterOfMinimumDistance(_positions, _indices);
275}
276
277/** Calculate the center of a given set of points in \a _positions but only
278 * for those indicated by \a _indices.
279 *
280 */
281inline
282Vector calculateCenter(
283 const SphericalPointDistribution::PolygonWithIndices &_polygon)
284{
285 return calculateCenter(_polygon.polygon, _polygon.indices);
286}
287
288inline
289DistanceArray_t calculatePairwiseDistances(
290 const SphericalPointDistribution::VectorArray_t &_points,
291 const SphericalPointDistribution::IndexTupleList_t &_indices
292 )
293{
294 DistanceArray_t result;
295 for (SphericalPointDistribution::IndexTupleList_t::const_iterator firstiter = _indices.begin();
296 firstiter != _indices.end(); ++firstiter) {
297
298 // calculate first center from possible tuple of indices
299 Vector FirstCenter;
300 ASSERT(!firstiter->empty(), "calculatePairwiseDistances() - there is an empty tuple.");
301 if (firstiter->size() == 1) {
302 FirstCenter = _points[*firstiter->begin()];
303 } else {
304 FirstCenter = calculateCenter( _points, *firstiter);
305 if (!FirstCenter.IsZero())
306 FirstCenter.Normalize();
307 }
308
309 for (SphericalPointDistribution::IndexTupleList_t::const_iterator seconditer = firstiter;
310 seconditer != _indices.end(); ++seconditer) {
311 if (firstiter == seconditer)
312 continue;
313
314 // calculate second center from possible tuple of indices
315 Vector SecondCenter;
316 ASSERT(!seconditer->empty(), "calculatePairwiseDistances() - there is an empty tuple.");
317 if (seconditer->size() == 1) {
318 SecondCenter = _points[*seconditer->begin()];
319 } else {
320 SecondCenter = calculateCenter( _points, *seconditer);
321 if (!SecondCenter.IsZero())
322 SecondCenter.Normalize();
323 }
324
325 // calculate distance between both centers
326 double distance = 2.; // greatest distance on surface of sphere with radius 1.
327 if ((!FirstCenter.IsZero()) && (!SecondCenter.IsZero()))
328 distance = (FirstCenter - SecondCenter).NormSquared();
329 result.push_back(distance);
330 }
331 }
332 return result;
333}
334
335/** Decides by an orthonormal third vector whether the sign of the rotation
336 * angle should be negative or positive.
337 *
338 * \return -1 or 1
339 */
340inline
341double determineSignOfRotation(
342 const Vector &_oldPosition,
343 const Vector &_newPosition,
344 const Vector &_RotationAxis
345 )
346{
347 Vector dreiBein(_oldPosition);
348 dreiBein.VectorProduct(_RotationAxis);
349 ASSERT( !dreiBein.IsZero(), "determineSignOfRotation() - dreiBein is zero.");
350 dreiBein.Normalize();
351 const double sign =
352 (dreiBein.ScalarProduct(_newPosition) < 0.) ? -1. : +1.;
353 LOG(6, "DEBUG: oldCenter on plane is " << _oldPosition
354 << ", newCenter on plane is " << _newPosition
355 << ", and dreiBein is " << dreiBein);
356 return sign;
357}
358
359/** Convenience function to recalculate old and new center for determining plane
360 * rotation.
361 */
362inline
363void calculateOldAndNewCenters(
364 Vector &_oldCenter,
365 Vector &_newCenter,
366 const SphericalPointDistribution::PolygonWithIndices &_referencepositions,
367 const SphericalPointDistribution::PolygonWithIndices &_currentpositions)
368{
369 _oldCenter = calculateCenter(_referencepositions.polygon, _referencepositions.indices);
370 // C++11 defines a copy_n function ...
371 _newCenter = calculateCenter( _currentpositions.polygon, _currentpositions.indices);
372}
373/** Returns squared L2 error of the given \a _Matching.
374 *
375 * We compare the pair-wise distances of each associated matching
376 * and check whether these distances each match between \a _old and
377 * \a _new.
378 *
379 * \param _old first set of returnpolygon (fewer or equal to \a _new)
380 * \param _new second set of returnpolygon
381 * \param _Matching matching between the two sets
382 * \return pair with L1 and squared L2 error
383 */
384std::pair<double, double> SphericalPointDistribution::calculateErrorOfMatching(
385 const VectorArray_t &_old,
386 const VectorArray_t &_new,
387 const IndexTupleList_t &_Matching)
388{
389 std::pair<double, double> errors( std::make_pair( 0., 0. ) );
390
391 if (_Matching.size() > 1) {
392 LOG(5, "INFO: Matching is " << _Matching);
393
394 // calculate all pair-wise distances
395 IndexTupleList_t keys(_old.size(), IndexList_t() );
396 std::generate (keys.begin(), keys.end(), UniqueNumberList);
397
398 const DistanceArray_t firstdistances = calculatePairwiseDistances(_old, keys);
399 const DistanceArray_t seconddistances = calculatePairwiseDistances(_new, _Matching);
400
401 ASSERT( firstdistances.size() == seconddistances.size(),
402 "calculateL2ErrorOfMatching() - mismatch in pair-wise distance array sizes.");
403 DistanceArray_t::const_iterator firstiter = firstdistances.begin();
404 DistanceArray_t::const_iterator seconditer = seconddistances.begin();
405 for (;(firstiter != firstdistances.end()) && (seconditer != seconddistances.end());
406 ++firstiter, ++seconditer) {
407 const double gap = fabs(*firstiter - *seconditer);
408 // L1 error
409 if (errors.first < gap)
410 errors.first = gap;
411 // L2 error
412 errors.second += gap*gap;
413 }
414 } else {
415 // check whether we have any zero centers: Combining points on new sphere may result
416 // in zero centers
417 for (SphericalPointDistribution::IndexTupleList_t::const_iterator iter = _Matching.begin();
418 iter != _Matching.end(); ++iter) {
419 if ((iter->size() != 1) && (calculateCenter( _new, *iter).IsZero())) {
420 errors.first = 2.;
421 errors.second = 2.;
422 }
423 }
424 }
425 LOG(4, "INFO: Resulting errors for matching (L1, L2): "
426 << errors.first << "," << errors.second << ".");
427
428 return errors;
429}
430
431SphericalPointDistribution::Polygon_t SphericalPointDistribution::removeMatchingPoints(
432 const PolygonWithIndices &_points
433 )
434{
435 SphericalPointDistribution::Polygon_t remainingpoints;
436 IndexArray_t indices(_points.indices.begin(), _points.indices.end());
437 std::sort(indices.begin(), indices.end());
438 LOG(4, "DEBUG: sorted matching is " << indices);
439 IndexArray_t remainingindices(_points.polygon.size(), -1);
440 std::generate(remainingindices.begin(), remainingindices.end(), UniqueNumber);
441 IndexArray_t::iterator remainiter = std::set_difference(
442 remainingindices.begin(), remainingindices.end(),
443 indices.begin(), indices.end(),
444 remainingindices.begin());
445 remainingindices.erase(remainiter, remainingindices.end());
446 LOG(4, "DEBUG: remaining indices are " << remainingindices);
447 for (IndexArray_t::const_iterator iter = remainingindices.begin();
448 iter != remainingindices.end(); ++iter) {
449 remainingpoints.push_back(_points.polygon[*iter]);
450 }
451
452 return remainingpoints;
453}
454
455/** Recursive function to go through all possible matchings.
456 *
457 * \param _MCS structure holding global information to the recursion
458 * \param _matching current matching being build up
459 * \param _indices contains still available indices
460 * \param _remainingweights current weights to fill (each weight a place)
461 * \param _remainiter iterator over the weights, indicating the current position we match
462 * \param _matchingsize
463 */
464void SphericalPointDistribution::recurseMatchings(
465 MatchingControlStructure &_MCS,
466 IndexTupleList_t &_matching,
467 IndexList_t _indices,
468 WeightsArray_t &_remainingweights,
469 WeightsArray_t::iterator _remainiter,
470 const unsigned int _matchingsize
471 )
472{
473 LOG(5, "DEBUG: Recursing with current matching " << _matching
474 << ", remaining indices " << _indices
475 << ", and remaining weights " << _matchingsize);
476 if (!_MCS.foundflag) {
477 LOG(5, "DEBUG: Current matching has size " << _matching.size() << ", places left " << _matchingsize);
478 if (_matchingsize > 0) {
479 // go through all indices
480 for (IndexList_t::iterator iter = _indices.begin();
481 (iter != _indices.end()) && (!_MCS.foundflag);) {
482 // check whether we can stay in the current bin or have to move on to next one
483 if (*_remainiter == 0) {
484 // we need to move on
485 if (_remainiter != _remainingweights.end()) {
486 ++_remainiter;
487 } else {
488 // as we check _matchingsize > 0 this should be impossible
489 ASSERT( 0, "recurseMatchings() - we must not come to this position.");
490 }
491 }
492 // advance in matching to same position
493 const size_t OldIndex = std::distance(_remainingweights.begin(), _remainiter);
494 while (_matching.size() <= OldIndex) { // add empty lists of new bin is opened
495 LOG(6, "DEBUG: Extending _matching.");
496 _matching.push_back( IndexList_t() );
497 }
498 IndexTupleList_t::iterator filliniter = _matching.begin();
499 std::advance(filliniter, OldIndex);
500 // add index to matching
501 filliniter->push_back(*iter);
502 --(*_remainiter);
503 LOG(6, "DEBUG: Adding " << *iter << " to matching at " << OldIndex << ".");
504 // remove index but keep iterator to position (is the next to erase element)
505 IndexList_t::iterator backupiter = _indices.erase(iter);
506 // recurse with decreased _matchingsize
507 recurseMatchings(_MCS, _matching, _indices, _remainingweights, _remainiter, _matchingsize-1);
508 // re-add chosen index and reset index to new position
509 _indices.insert(backupiter, filliniter->back());
510 iter = backupiter;
511 // remove index from _matching to make space for the next one
512 filliniter->pop_back();
513 ++(*_remainiter);
514 }
515 // gone through all indices then exit recursion
516 if (_matching.empty())
517 _MCS.foundflag = true;
518 } else {
519 LOG(4, "INFO: Found matching " << _matching);
520 // calculate errors
521 std::pair<double, double> errors = calculateErrorOfMatching(
522 _MCS.oldpoints, _MCS.newpoints, _matching);
523 if (errors.first < L1THRESHOLD) {
524 _MCS.bestmatching = _matching;
525 _MCS.foundflag = true;
526 } else if (_MCS.bestL2 > errors.second) {
527 _MCS.bestmatching = _matching;
528 _MCS.bestL2 = errors.second;
529 }
530 }
531 }
532}
533
534/** Finds combinatorially the best matching between points in \a _polygon
535 * and \a _newpolygon.
536 *
537 * We find the matching with the smallest L2 error, where we break when we stumble
538 * upon a matching with zero error.
539 *
540 * As points in \a _polygon may be have a weight greater 1 we have to match it to
541 * multiple points in \a _newpolygon. Eventually, these multiple points are combined
542 * for their center of weight, which is the only thing follow-up function see of
543 * these multiple points. Hence, we actually modify \a _newpolygon in the process
544 * such that the returned IndexList_t indicates a bijective mapping in the end.
545 *
546 * \sa recurseMatchings() for going through all matchings
547 *
548 * \param _polygon here, we have indices 0,1,2,...
549 * \param _newpolygon and here we need to find the correct indices
550 * \return list of indices: first in \a _polygon goes to first index for \a _newpolygon
551 */
552SphericalPointDistribution::IndexList_t SphericalPointDistribution::findBestMatching(
553 const WeightedPolygon_t &_polygon,
554 Polygon_t &_newpolygon
555 )
556{
557 MatchingControlStructure MCS;
558 MCS.foundflag = false;
559 MCS.bestL2 = std::numeric_limits<double>::max();
560 // transform lists into arrays
561 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
562 iter != _polygon.end(); ++iter) {
563 MCS.oldpoints.push_back(iter->first);
564 MCS.weights.push_back(iter->second);
565 }
566 MCS.newpoints.insert(MCS.newpoints.begin(), _newpolygon.begin(),_newpolygon.end() );
567
568 // search for bestmatching combinatorially
569 {
570 // translate polygon into vector to enable index addressing
571 IndexList_t indices(_newpolygon.size());
572 std::generate(indices.begin(), indices.end(), UniqueNumber);
573 IndexTupleList_t matching;
574
575 // walk through all matchings
576 WeightsArray_t remainingweights = MCS.weights;
577 unsigned int placesleft = std::accumulate(remainingweights.begin(), remainingweights.end(), 0);
578 recurseMatchings(MCS, matching, indices, remainingweights, remainingweights.begin(), placesleft);
579 }
580 if (MCS.foundflag)
581 LOG(3, "Found a best matching beneath L1 threshold of " << L1THRESHOLD);
582 else {
583 if (MCS.bestL2 < warn_amplitude)
584 LOG(3, "Picking matching is " << MCS.bestmatching << " with best L2 error of "
585 << MCS.bestL2);
586 else if (MCS.bestL2 < L2THRESHOLD)
587 ELOG(2, "Picking matching is " << MCS.bestmatching
588 << " with rather large L2 error of " << MCS.bestL2);
589 else
590 ASSERT(0, "findBestMatching() - matching "+toString(MCS.bestmatching)
591 +" has L2 error of "+toString(MCS.bestL2)+" that is too large.");
592 }
593
594 // combine multiple points and create simple IndexList from IndexTupleList
595 const SphericalPointDistribution::IndexList_t IndexList =
596 joinPoints(_newpolygon, MCS.newpoints, MCS.bestmatching);
597
598 return IndexList;
599}
600
601SphericalPointDistribution::IndexList_t SphericalPointDistribution::joinPoints(
602 Polygon_t &_newpolygon,
603 const VectorArray_t &_newpoints,
604 const IndexTupleList_t &_bestmatching
605 )
606{
607 // combine all multiple points
608 IndexList_t IndexList;
609 IndexArray_t removalpoints;
610 unsigned int UniqueIndex = _newpolygon.size(); // all indices up to size are used right now
611 VectorArray_t newCenters;
612 newCenters.reserve(_bestmatching.size());
613 for (IndexTupleList_t::const_iterator tupleiter = _bestmatching.begin();
614 tupleiter != _bestmatching.end(); ++tupleiter) {
615 ASSERT (tupleiter->size() > 0,
616 "findBestMatching() - encountered tuple in bestmatching with size 0.");
617 if (tupleiter->size() == 1) {
618 // add point and index
619 IndexList.push_back(*tupleiter->begin());
620 } else {
621 // combine into weighted and normalized center
622 Vector Center = calculateCenter(_newpoints, *tupleiter);
623 Center.Normalize();
624 _newpolygon.push_back(Center);
625 LOG(5, "DEBUG: Combining " << tupleiter->size() << " points to weighted center "
626 << Center << " with new index " << UniqueIndex);
627 // mark for removal
628 removalpoints.insert(removalpoints.end(), tupleiter->begin(), tupleiter->end());
629 // add new index
630 IndexList.push_back(UniqueIndex++);
631 }
632 }
633 // IndexList is now our new bestmatching (that is bijective)
634 LOG(4, "DEBUG: Our new bijective IndexList reads as " << IndexList);
635
636 // modifying _newpolygon: remove all points in removalpoints, add those in newCenters
637 Polygon_t allnewpoints = _newpolygon;
638 {
639 _newpolygon.clear();
640 std::sort(removalpoints.begin(), removalpoints.end());
641 size_t i = 0;
642 IndexArray_t::const_iterator removeiter = removalpoints.begin();
643 for (Polygon_t::iterator iter = allnewpoints.begin();
644 iter != allnewpoints.end(); ++iter, ++i) {
645 if ((removeiter != removalpoints.end()) && (i == *removeiter)) {
646 // don't add, go to next remove index
647 ++removeiter;
648 } else {
649 // otherwise add points
650 _newpolygon.push_back(*iter);
651 }
652 }
653 }
654 LOG(4, "DEBUG: The polygon with recentered points removed is " << _newpolygon);
655
656 // map IndexList to new shrinked _newpolygon
657 typedef std::set<unsigned int> IndexSet_t;
658 IndexSet_t SortedIndexList(IndexList.begin(), IndexList.end());
659 IndexList.clear();
660 {
661 size_t offset = 0;
662 IndexSet_t::const_iterator listiter = SortedIndexList.begin();
663 IndexArray_t::const_iterator removeiter = removalpoints.begin();
664 for (size_t i = 0; i < allnewpoints.size(); ++i) {
665 if ((removeiter != removalpoints.end()) && (i == *removeiter)) {
666 ++offset;
667 ++removeiter;
668 } else if ((listiter != SortedIndexList.end()) && (i == *listiter)) {
669 IndexList.push_back(*listiter - offset);
670 ++listiter;
671 }
672 }
673 }
674 LOG(4, "DEBUG: Our new bijective IndexList corrected for removed points reads as "
675 << IndexList);
676
677 return IndexList;
678}
679
680SphericalPointDistribution::Rotation_t SphericalPointDistribution::findPlaneAligningRotation(
681 const PolygonWithIndices &_referencepositions,
682 const PolygonWithIndices &_currentpositions
683 )
684{
685 bool dontcheck = false;
686 // initialize to no rotation
687 Rotation_t Rotation;
688 Rotation.first.Zero();
689 Rotation.first[0] = 1.;
690 Rotation.second = 0.;
691
692 // calculate center of triangle/line/point consisting of first points of matching
693 Vector oldCenter;
694 Vector newCenter;
695 calculateOldAndNewCenters(
696 oldCenter, newCenter,
697 _referencepositions, _currentpositions);
698
699 if ((!oldCenter.IsZero()) && (!newCenter.IsZero())) {
700 LOG(4, "DEBUG: oldCenter is " << oldCenter << ", newCenter is " << newCenter);
701 oldCenter.Normalize();
702 newCenter.Normalize();
703 if (!oldCenter.IsEqualTo(newCenter)) {
704 // calculate rotation axis and angle
705 Rotation.first = oldCenter;
706 Rotation.first.VectorProduct(newCenter);
707 Rotation.second = oldCenter.Angle(newCenter); // /(M_PI/2.);
708 } else {
709 // no rotation required anymore
710 }
711 } else {
712 LOG(4, "DEBUG: oldCenter is " << oldCenter << ", newCenter is " << newCenter);
713 if ((oldCenter.IsZero()) && (newCenter.IsZero())) {
714 // either oldCenter or newCenter (or both) is directly at origin
715 if (_currentpositions.indices.size() == 2) {
716 // line case
717 Vector oldPosition = _currentpositions.polygon[*_currentpositions.indices.begin()];
718 Vector newPosition = _referencepositions.polygon[0];
719 // check whether we need to rotate at all
720 if (!oldPosition.IsEqualTo(newPosition)) {
721 Rotation.first = oldPosition;
722 Rotation.first.VectorProduct(newPosition);
723 // orientation will fix the sign here eventually
724 Rotation.second = oldPosition.Angle(newPosition);
725 } else {
726 // no rotation required anymore
727 }
728 } else {
729 // triangle case
730 // both triangles/planes have same center, hence get axis by
731 // VectorProduct of Normals
732 Plane newplane(_referencepositions.polygon[0], _referencepositions.polygon[1], _referencepositions.polygon[2]);
733 VectorArray_t vectors;
734 for (IndexList_t::const_iterator iter = _currentpositions.indices.begin();
735 iter != _currentpositions.indices.end(); ++iter)
736 vectors.push_back(_currentpositions.polygon[*iter]);
737 Plane oldplane(vectors[0], vectors[1], vectors[2]);
738 Vector oldPosition = oldplane.getNormal();
739 Vector newPosition = newplane.getNormal();
740 // check whether we need to rotate at all
741 if (!oldPosition.IsEqualTo(newPosition)) {
742 Rotation.first = oldPosition;
743 Rotation.first.VectorProduct(newPosition);
744 Rotation.first.Normalize();
745
746 // construct reference vector to determine direction of rotation
747 const double sign = determineSignOfRotation(oldPosition, newPosition, Rotation.first);
748 Rotation.second = sign * oldPosition.Angle(newPosition);
749 LOG(5, "DEBUG: Rotating plane normals by " << Rotation.second
750 << " around axis " << Rotation.first);
751 } else {
752 // else do nothing
753 }
754 }
755 } else {
756 // TODO: we can't do anything here, but this case needs to be dealt with when
757 // we have no ideal geometries anymore
758 if ((oldCenter-newCenter).Norm() > warn_amplitude)
759 ELOG(2, "oldCenter is " << oldCenter << ", yet newCenter is " << newCenter);
760 // else they are considered close enough
761 dontcheck = true;
762 }
763 }
764
765#ifndef NDEBUG
766 // check: rotation brings newCenter onto oldCenter position
767 if (!dontcheck) {
768 Line Axis(zeroVec, Rotation.first);
769 Vector test = Axis.rotateVector(newCenter, Rotation.second);
770 LOG(4, "CHECK: rotated newCenter is " << test
771 << ", oldCenter is " << oldCenter);
772 ASSERT( (test - oldCenter).NormSquared() < std::numeric_limits<double>::epsilon()*1e4,
773 "matchSphericalPointDistributions() - rotation does not work as expected by "
774 +toString((test - oldCenter).NormSquared())+".");
775 }
776#endif
777
778 return Rotation;
779}
780
781SphericalPointDistribution::Rotation_t SphericalPointDistribution::findPointAligningRotation(
782 const PolygonWithIndices &remainingold,
783 const PolygonWithIndices &remainingnew)
784{
785 // initialize rotation to zero
786 Rotation_t Rotation;
787 Rotation.first.Zero();
788 Rotation.first[0] = 1.;
789 Rotation.second = 0.;
790
791 // recalculate center
792 Vector oldCenter;
793 Vector newCenter;
794 calculateOldAndNewCenters(
795 oldCenter, newCenter,
796 remainingold, remainingnew);
797
798 Vector oldPosition = remainingnew.polygon[*remainingnew.indices.begin()];
799 Vector newPosition = remainingold.polygon[0];
800 LOG(6, "DEBUG: oldPosition is " << oldPosition << " (length: "
801 << oldPosition.Norm() << ") and newPosition is " << newPosition << " length(: "
802 << newPosition.Norm() << ")");
803 if (!oldPosition.IsEqualTo(newPosition)) {
804 if ((!oldCenter.IsZero()) && (!newCenter.IsZero())) {
805 // we rotate at oldCenter and around the radial direction, which is again given
806 // by oldCenter.
807 Rotation.first = oldCenter;
808 Rotation.first.Normalize(); // note weighted sum of normalized weight is not normalized
809 LOG(6, "DEBUG: Using oldCenter " << oldCenter << " as rotation center and "
810 << Rotation.first << " as axis.");
811 oldPosition -= oldCenter;
812 newPosition -= oldCenter;
813 oldPosition = (oldPosition - oldPosition.Projection(Rotation.first));
814 newPosition = (newPosition - newPosition.Projection(Rotation.first));
815 LOG(6, "DEBUG: Positions after projection are " << oldPosition << " and " << newPosition);
816 } else {
817 if (remainingnew.indices.size() == 2) {
818 // line situation
819 try {
820 Plane oldplane(oldPosition, oldCenter, newPosition);
821 Rotation.first = oldplane.getNormal();
822 LOG(6, "DEBUG: Plane is " << oldplane << " and normal is " << Rotation.first);
823 } catch (LinearDependenceException &e) {
824 LOG(6, "DEBUG: Vectors defining plane are linearly dependent.");
825 // oldPosition and newPosition are on a line, just flip when not equal
826 if (!oldPosition.IsEqualTo(newPosition)) {
827 Rotation.first.Zero();
828 Rotation.first.GetOneNormalVector(oldPosition);
829 LOG(6, "DEBUG: For flipping we use Rotation.first " << Rotation.first);
830 assert( Rotation.first.ScalarProduct(oldPosition) < std::numeric_limits<double>::epsilon()*1e4);
831 // Rotation.second = M_PI;
832 } else {
833 LOG(6, "DEBUG: oldPosition and newPosition are equivalent.");
834 }
835 }
836 } else {
837 // triangle situation
838 Plane oldplane(remainingold.polygon[0], remainingold.polygon[1], remainingold.polygon[2]);
839 Rotation.first = oldplane.getNormal();
840 LOG(6, "DEBUG: oldPlane is " << oldplane << " and normal is " << Rotation.first);
841 oldPosition.ProjectOntoPlane(Rotation.first);
842 LOG(6, "DEBUG: Positions after projection are " << oldPosition << " and " << newPosition);
843 }
844 }
845 // construct reference vector to determine direction of rotation
846 const double sign = determineSignOfRotation(oldPosition, newPosition, Rotation.first);
847 Rotation.second = sign * oldPosition.Angle(newPosition);
848 } else {
849 LOG(6, "DEBUG: oldPosition and newPosition are equivalent, hence no orientating rotation.");
850 }
851
852 return Rotation;
853}
854
855
856SphericalPointDistribution::Polygon_t
857SphericalPointDistribution::matchSphericalPointDistributions(
858 const SphericalPointDistribution::WeightedPolygon_t &_polygon,
859 SphericalPointDistribution::Polygon_t &_newpolygon
860 )
861{
862 SphericalPointDistribution::Polygon_t remainingpoints;
863
864 LOG(2, "INFO: Matching old polygon " << _polygon
865 << " with new polygon " << _newpolygon);
866
867 if (_polygon.size() == _newpolygon.size()) {
868 // same number of points desired as are present? Do nothing
869 LOG(2, "INFO: There are no vacant points to return.");
870 return remainingpoints;
871 }
872
873 if (_polygon.size() > 0) {
874 IndexList_t bestmatching = findBestMatching(_polygon, _newpolygon);
875 LOG(2, "INFO: Best matching is " << bestmatching);
876
877 const size_t NumberIds = std::min(bestmatching.size(), (size_t)3);
878 // create old set
879 PolygonWithIndices oldSet;
880 oldSet.indices.resize(NumberIds, -1);
881 std::generate(oldSet.indices.begin(), oldSet.indices.end(), UniqueNumber);
882 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
883 iter != _polygon.end(); ++iter)
884 oldSet.polygon.push_back(iter->first);
885
886 // _newpolygon has changed, so now convert to array with matched indices
887 PolygonWithIndices newSet;
888 SphericalPointDistribution::IndexList_t::const_iterator beginiter = bestmatching.begin();
889 SphericalPointDistribution::IndexList_t::const_iterator enditer = bestmatching.begin();
890 std::advance(enditer, NumberIds);
891 newSet.indices.resize(NumberIds, -1);
892 std::copy(beginiter, enditer, newSet.indices.begin());
893 std::copy(_newpolygon.begin(),_newpolygon.end(), std::back_inserter(newSet.polygon));
894
895 // determine rotation angles to align the two point distributions with
896 // respect to bestmatching:
897 // we use the center between the three first matching points
898 /// the first rotation brings these two centers to coincide
899 PolygonWithIndices rotatednewSet = newSet;
900 {
901 Rotation_t Rotation = findPlaneAligningRotation(oldSet, newSet);
902 LOG(5, "DEBUG: Rotating coordinate system by " << Rotation.second
903 << " around axis " << Rotation.first);
904 Line Axis(zeroVec, Rotation.first);
905
906 // apply rotation angle to bring newCenter to oldCenter
907 for (VectorArray_t::iterator iter = rotatednewSet.polygon.begin();
908 iter != rotatednewSet.polygon.end(); ++iter) {
909 Vector &current = *iter;
910 LOG(6, "DEBUG: Original point is " << current);
911 current = Axis.rotateVector(current, Rotation.second);
912 LOG(6, "DEBUG: Rotated point is " << current);
913 }
914
915#ifndef NDEBUG
916 // check: rotated "newCenter" should now equal oldCenter
917 {
918 Vector oldCenter;
919 Vector rotatednewCenter;
920 calculateOldAndNewCenters(
921 oldCenter, rotatednewCenter,
922 oldSet, rotatednewSet);
923 oldCenter.Normalize();
924 rotatednewCenter.Normalize();
925 // check whether centers are anti-parallel (factor -1)
926 // then we have the "non-unique poles" situation: points lie on great circle
927 // and both poles are valid solution
928 if (fabs(oldCenter.ScalarProduct(rotatednewCenter) + 1.)
929 < std::numeric_limits<double>::epsilon()*1e4)
930 rotatednewCenter *= -1.;
931 LOG(4, "CHECK: rotatednewCenter is " << rotatednewCenter
932 << ", oldCenter is " << oldCenter);
933 const double difference = (rotatednewCenter - oldCenter).NormSquared();
934 ASSERT( difference < std::numeric_limits<double>::epsilon()*1e4,
935 "matchSphericalPointDistributions() - rotation does not work as expected by "
936 +toString(difference)+".");
937 }
938#endif
939 }
940 /// the second (orientation) rotation aligns the planes such that the
941 /// points themselves coincide
942 if (bestmatching.size() > 1) {
943 Rotation_t Rotation = findPointAligningRotation(oldSet, rotatednewSet);
944
945 // construct RotationAxis and two points on its plane, defining the angle
946 Rotation.first.Normalize();
947 const Line RotationAxis(zeroVec, Rotation.first);
948
949 LOG(5, "DEBUG: Rotating around self is " << Rotation.second
950 << " around axis " << RotationAxis);
951
952#ifndef NDEBUG
953 // check: first bestmatching in rotated_newpolygon and remainingnew
954 // should now equal
955 {
956 const IndexList_t::const_iterator iter = bestmatching.begin();
957
958 // check whether both old and newPosition are at same distance to oldCenter
959 Vector oldCenter = calculateCenter(oldSet);
960 const double distance = fabs(
961 (oldSet.polygon[0] - oldCenter).NormSquared()
962 - (rotatednewSet.polygon[*iter] - oldCenter).NormSquared()
963 );
964 LOG(4, "CHECK: Squared distance between oldPosition and newPosition "
965 << " with respect to oldCenter " << oldCenter << " is " << distance);
966// ASSERT( distance < warn_amplitude,
967// "matchSphericalPointDistributions() - old and newPosition's squared distance to oldCenter differs by "
968// +toString(distance));
969
970 Vector rotatednew = RotationAxis.rotateVector(
971 rotatednewSet.polygon[*iter],
972 Rotation.second);
973 LOG(4, "CHECK: rotated first new bestmatching is " << rotatednew
974 << " while old was " << oldSet.polygon[0]);
975 const double difference = (rotatednew - oldSet.polygon[0]).NormSquared();
976 ASSERT( difference < distance+1e-8,
977 "matchSphericalPointDistributions() - orientation rotation ends up off by "
978 +toString(difference)+", more than "
979 +toString(distance+1e-8)+".");
980 }
981#endif
982
983 for (VectorArray_t::iterator iter = rotatednewSet.polygon.begin();
984 iter != rotatednewSet.polygon.end(); ++iter) {
985 Vector &current = *iter;
986 LOG(6, "DEBUG: Original point is " << current);
987 current = RotationAxis.rotateVector(current, Rotation.second);
988 LOG(6, "DEBUG: Rotated point is " << current);
989 }
990 }
991
992 // remove all points in matching and return remaining ones
993 SphericalPointDistribution::Polygon_t remainingpoints =
994 removeMatchingPoints(rotatednewSet);
995 LOG(2, "INFO: Remaining points are " << remainingpoints);
996 return remainingpoints;
997 } else
998 return _newpolygon;
999}
Note: See TracBrowser for help on using the repository browser.