source: src/Fragmentation/Exporters/SphericalPointDistribution.cpp@ a2f8a9

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