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

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

recurseMatching() now takes connections into account.

  • matchSphericalPointDistribution() replaced by getRemainingPoints() as that describes what it does. match...() sounds symmetrical which the function is no longer as connection is associated with former _newpolygon.
  • SphericalPointDistribution now has internal points and adjacency, initialized by initSelf().
  • findBestMatching() and getRemainingPoints() are no longer static functions.
  • all unit tests are working again, including the .._multiple() that tests for joint points due to bond degree greater than 1.
  • the huge case switch in SaturatedFragment::saturateAtom() now resides in initSelf().
  • Property mode set to 100644
File size: 38.4 KB
RevLine 
[0d4daf]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"
[90426a]41#include "CodePatterns/Log.hpp"
[0d4daf]42#include "CodePatterns/toString.hpp"
43
44#include <algorithm>
[a2f8a9]45#include <boost/assign.hpp>
[0d4daf]46#include <cmath>
[0d5ca7]47#include <functional>
48#include <iterator>
[0d4daf]49#include <limits>
50#include <list>
[23c605]51#include <numeric>
[0d4daf]52#include <vector>
53#include <map>
54
55#include "LinearAlgebra/Line.hpp"
[3da643]56#include "LinearAlgebra/Plane.hpp"
[0d4daf]57#include "LinearAlgebra/RealSpaceMatrix.hpp"
58#include "LinearAlgebra/Vector.hpp"
59
[a2f8a9]60using namespace boost::assign;
61
[3da643]62// static entities
63const double SphericalPointDistribution::warn_amplitude = 1e-2;
[23c605]64const double SphericalPointDistribution::L1THRESHOLD = 1e-2;
65const double SphericalPointDistribution::L2THRESHOLD = 2e-1;
[3da643]66
[0d4daf]67typedef std::vector<double> DistanceArray_t;
68
[1ae9aa]69// class generator: taken from www.cplusplus.com example std::generate
70struct c_unique {
[23c605]71 unsigned int current;
[1ae9aa]72 c_unique() {current=0;}
[23c605]73 unsigned int operator()() {return current++;}
[1ae9aa]74} UniqueNumber;
75
[23c605]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;
[0d4daf]81
[1ae9aa]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
[a2f8a9]87Vector calculateGeographicMidpoint(
[1ae9aa]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}
[0d4daf]101
[a2f8a9]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
[1cde4e8]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
[23c605]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
[1ae9aa]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);
[23c605]348 ASSERT( !dreiBein.IsZero(), "determineSignOfRotation() - dreiBein is zero.");
[1ae9aa]349 dreiBein.Normalize();
350 const double sign =
351 (dreiBein.ScalarProduct(_newPosition) < 0.) ? -1. : +1.;
352 LOG(6, "DEBUG: oldCenter on plane is " << _oldPosition
[23c605]353 << ", newCenter on plane is " << _newPosition
[1ae9aa]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,
[1cde4e8]365 const SphericalPointDistribution::PolygonWithIndices &_referencepositions,
366 const SphericalPointDistribution::PolygonWithIndices &_currentpositions)
[1ae9aa]367{
[1cde4e8]368 _oldCenter = calculateCenter(_referencepositions.polygon, _referencepositions.indices);
[1ae9aa]369 // C++11 defines a copy_n function ...
[1cde4e8]370 _newCenter = calculateCenter( _currentpositions.polygon, _currentpositions.indices);
[1ae9aa]371}
[0d4daf]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 */
[3da643]383std::pair<double, double> SphericalPointDistribution::calculateErrorOfMatching(
[23c605]384 const VectorArray_t &_old,
385 const VectorArray_t &_new,
386 const IndexTupleList_t &_Matching)
[0d4daf]387{
388 std::pair<double, double> errors( std::make_pair( 0., 0. ) );
389
390 if (_Matching.size() > 1) {
[23c605]391 LOG(5, "INFO: Matching is " << _Matching);
[0d4daf]392
393 // calculate all pair-wise distances
[23c605]394 IndexTupleList_t keys(_old.size(), IndexList_t() );
395 std::generate (keys.begin(), keys.end(), UniqueNumberList);
396
[0d4daf]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) {
[23c605]406 const double gap = fabs(*firstiter - *seconditer);
[0d4daf]407 // L1 error
408 if (errors.first < gap)
409 errors.first = gap;
410 // L2 error
411 errors.second += gap*gap;
412 }
[23c605]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): "
[90426a]425 << errors.first << "," << errors.second << ".");
[0d4daf]426
427 return errors;
428}
429
[3da643]430SphericalPointDistribution::Polygon_t SphericalPointDistribution::removeMatchingPoints(
[1cde4e8]431 const PolygonWithIndices &_points
[0d4daf]432 )
433{
434 SphericalPointDistribution::Polygon_t remainingpoints;
[1cde4e8]435 IndexArray_t indices(_points.indices.begin(), _points.indices.end());
[0d4daf]436 std::sort(indices.begin(), indices.end());
[90426a]437 LOG(4, "DEBUG: sorted matching is " << indices);
[1cde4e8]438 IndexArray_t remainingindices(_points.polygon.size(), -1);
[bb011f]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) {
[1cde4e8]448 remainingpoints.push_back(_points.polygon[*iter]);
[0d4daf]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
[23c605]459 * \param _remainingweights current weights to fill (each weight a place)
460 * \param _remainiter iterator over the weights, indicating the current position we match
[0d4daf]461 * \param _matchingsize
462 */
[3da643]463void SphericalPointDistribution::recurseMatchings(
[0d4daf]464 MatchingControlStructure &_MCS,
[23c605]465 IndexTupleList_t &_matching,
[0d4daf]466 IndexList_t _indices,
[23c605]467 WeightsArray_t &_remainingweights,
468 WeightsArray_t::iterator _remainiter,
469 const unsigned int _matchingsize
470 )
[0d4daf]471{
[23c605]472 LOG(5, "DEBUG: Recursing with current matching " << _matching
[90426a]473 << ", remaining indices " << _indices
[23c605]474 << ", and remaining weights " << _matchingsize);
[0d4daf]475 if (!_MCS.foundflag) {
[23c605]476 LOG(5, "DEBUG: Current matching has size " << _matching.size() << ", places left " << _matchingsize);
[0d5ca7]477 if (_matchingsize > 0) {
[0d4daf]478 // go through all indices
479 for (IndexList_t::iterator iter = _indices.begin();
[0d5ca7]480 (iter != _indices.end()) && (!_MCS.foundflag);) {
[e6ca85]481
[23c605]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 }
[e6ca85]492
493 // advance in matching to current bin to fill in
[23c605]494 const size_t OldIndex = std::distance(_remainingweights.begin(), _remainiter);
495 while (_matching.size() <= OldIndex) { // add empty lists of new bin is opened
496 LOG(6, "DEBUG: Extending _matching.");
497 _matching.push_back( IndexList_t() );
498 }
499 IndexTupleList_t::iterator filliniter = _matching.begin();
500 std::advance(filliniter, OldIndex);
[e6ca85]501
502 // check whether connection between bins' indices and candidate is satisfied
503 {
504 adjacency_t::const_iterator finder = _MCS.adjacency.find(*iter);
505 ASSERT( finder != _MCS.adjacency.end(),
506 "recurseMatchings() - "+toString(*iter)+" is not in adjacency list.");
507 if ((!filliniter->empty())
508 && (finder->second.find(*filliniter->begin()) == finder->second.end())) {
509 LOG(5, "DEBUG; Skipping index " << *iter
510 << " as is not connected to current set." << *filliniter << ".");
511 ++iter; // note that for loop does not contain incrementor
512 continue;
513 }
514 }
515
[0d4daf]516 // add index to matching
[23c605]517 filliniter->push_back(*iter);
518 --(*_remainiter);
519 LOG(6, "DEBUG: Adding " << *iter << " to matching at " << OldIndex << ".");
[0d4daf]520 // remove index but keep iterator to position (is the next to erase element)
521 IndexList_t::iterator backupiter = _indices.erase(iter);
522 // recurse with decreased _matchingsize
[23c605]523 recurseMatchings(_MCS, _matching, _indices, _remainingweights, _remainiter, _matchingsize-1);
[0d4daf]524 // re-add chosen index and reset index to new position
[23c605]525 _indices.insert(backupiter, filliniter->back());
[0d4daf]526 iter = backupiter;
527 // remove index from _matching to make space for the next one
[23c605]528 filliniter->pop_back();
529 ++(*_remainiter);
[0d4daf]530 }
531 // gone through all indices then exit recursion
[0d5ca7]532 if (_matching.empty())
533 _MCS.foundflag = true;
[0d4daf]534 } else {
[23c605]535 LOG(4, "INFO: Found matching " << _matching);
[0d4daf]536 // calculate errors
537 std::pair<double, double> errors = calculateErrorOfMatching(
538 _MCS.oldpoints, _MCS.newpoints, _matching);
539 if (errors.first < L1THRESHOLD) {
540 _MCS.bestmatching = _matching;
541 _MCS.foundflag = true;
[0d5ca7]542 } else if (_MCS.bestL2 > errors.second) {
[0d4daf]543 _MCS.bestmatching = _matching;
544 _MCS.bestL2 = errors.second;
545 }
546 }
547 }
548}
549
[e6ca85]550SphericalPointDistribution::MatchingControlStructure::MatchingControlStructure(
551 const adjacency_t &_adjacency,
552 const VectorArray_t &_oldpoints,
553 const VectorArray_t &_newpoints,
554 const WeightsArray_t &_weights
555 ) :
556 foundflag(false),
557 bestL2(std::numeric_limits<double>::max()),
558 adjacency(_adjacency),
559 oldpoints(_oldpoints),
560 newpoints(_newpoints),
561 weights(_weights)
562{}
563
[3da643]564/** Finds combinatorially the best matching between points in \a _polygon
565 * and \a _newpolygon.
566 *
567 * We find the matching with the smallest L2 error, where we break when we stumble
568 * upon a matching with zero error.
569 *
[1ae9aa]570 * As points in \a _polygon may be have a weight greater 1 we have to match it to
571 * multiple points in \a _newpolygon. Eventually, these multiple points are combined
572 * for their center of weight, which is the only thing follow-up function see of
573 * these multiple points. Hence, we actually modify \a _newpolygon in the process
574 * such that the returned IndexList_t indicates a bijective mapping in the end.
575 *
[3da643]576 * \sa recurseMatchings() for going through all matchings
577 *
578 * \param _polygon here, we have indices 0,1,2,...
579 * \param _newpolygon and here we need to find the correct indices
580 * \return list of indices: first in \a _polygon goes to first index for \a _newpolygon
581 */
582SphericalPointDistribution::IndexList_t SphericalPointDistribution::findBestMatching(
[e6ca85]583 const WeightedPolygon_t &_polygon
[3da643]584 )
[0d5ca7]585{
[23c605]586 // transform lists into arrays
[e6ca85]587 VectorArray_t oldpoints;
588 VectorArray_t newpoints;
589 WeightsArray_t weights;
[260540]590 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
[23c605]591 iter != _polygon.end(); ++iter) {
[e6ca85]592 oldpoints.push_back(iter->first);
593 weights.push_back(iter->second);
[23c605]594 }
[e6ca85]595 newpoints.insert(newpoints.begin(), points.begin(), points.end() );
596 MatchingControlStructure MCS(adjacency, oldpoints, newpoints, weights);
[3da643]597
598 // search for bestmatching combinatorially
599 {
600 // translate polygon into vector to enable index addressing
[e6ca85]601 IndexList_t indices(points.size());
[3da643]602 std::generate(indices.begin(), indices.end(), UniqueNumber);
[23c605]603 IndexTupleList_t matching;
[3da643]604
605 // walk through all matchings
[23c605]606 WeightsArray_t remainingweights = MCS.weights;
607 unsigned int placesleft = std::accumulate(remainingweights.begin(), remainingweights.end(), 0);
608 recurseMatchings(MCS, matching, indices, remainingweights, remainingweights.begin(), placesleft);
609 }
610 if (MCS.foundflag)
611 LOG(3, "Found a best matching beneath L1 threshold of " << L1THRESHOLD);
612 else {
613 if (MCS.bestL2 < warn_amplitude)
614 LOG(3, "Picking matching is " << MCS.bestmatching << " with best L2 error of "
615 << MCS.bestL2);
616 else if (MCS.bestL2 < L2THRESHOLD)
617 ELOG(2, "Picking matching is " << MCS.bestmatching
618 << " with rather large L2 error of " << MCS.bestL2);
619 else
620 ASSERT(0, "findBestMatching() - matching "+toString(MCS.bestmatching)
621 +" has L2 error of "+toString(MCS.bestL2)+" that is too large.");
[0d5ca7]622 }
623
[1ae9aa]624 // combine multiple points and create simple IndexList from IndexTupleList
625 const SphericalPointDistribution::IndexList_t IndexList =
[e6ca85]626 joinPoints(points, MCS.newpoints, MCS.bestmatching);
[3da643]627
[1ae9aa]628 return IndexList;
[3da643]629}
630
[1ae9aa]631SphericalPointDistribution::IndexList_t SphericalPointDistribution::joinPoints(
632 Polygon_t &_newpolygon,
633 const VectorArray_t &_newpoints,
634 const IndexTupleList_t &_bestmatching
635 )
[3da643]636{
[1ae9aa]637 // combine all multiple points
638 IndexList_t IndexList;
639 IndexArray_t removalpoints;
640 unsigned int UniqueIndex = _newpolygon.size(); // all indices up to size are used right now
641 VectorArray_t newCenters;
642 newCenters.reserve(_bestmatching.size());
643 for (IndexTupleList_t::const_iterator tupleiter = _bestmatching.begin();
644 tupleiter != _bestmatching.end(); ++tupleiter) {
645 ASSERT (tupleiter->size() > 0,
646 "findBestMatching() - encountered tuple in bestmatching with size 0.");
647 if (tupleiter->size() == 1) {
648 // add point and index
649 IndexList.push_back(*tupleiter->begin());
650 } else {
651 // combine into weighted and normalized center
652 Vector Center = calculateCenter(_newpoints, *tupleiter);
653 Center.Normalize();
654 _newpolygon.push_back(Center);
[23c605]655 LOG(5, "DEBUG: Combining " << tupleiter->size() << " points to weighted center "
[1ae9aa]656 << Center << " with new index " << UniqueIndex);
657 // mark for removal
658 removalpoints.insert(removalpoints.end(), tupleiter->begin(), tupleiter->end());
659 // add new index
660 IndexList.push_back(UniqueIndex++);
661 }
662 }
663 // IndexList is now our new bestmatching (that is bijective)
664 LOG(4, "DEBUG: Our new bijective IndexList reads as " << IndexList);
665
666 // modifying _newpolygon: remove all points in removalpoints, add those in newCenters
667 Polygon_t allnewpoints = _newpolygon;
668 {
669 _newpolygon.clear();
670 std::sort(removalpoints.begin(), removalpoints.end());
671 size_t i = 0;
672 IndexArray_t::const_iterator removeiter = removalpoints.begin();
673 for (Polygon_t::iterator iter = allnewpoints.begin();
674 iter != allnewpoints.end(); ++iter, ++i) {
675 if ((removeiter != removalpoints.end()) && (i == *removeiter)) {
676 // don't add, go to next remove index
677 ++removeiter;
678 } else {
679 // otherwise add points
680 _newpolygon.push_back(*iter);
681 }
682 }
683 }
684 LOG(4, "DEBUG: The polygon with recentered points removed is " << _newpolygon);
685
686 // map IndexList to new shrinked _newpolygon
687 typedef std::set<unsigned int> IndexSet_t;
688 IndexSet_t SortedIndexList(IndexList.begin(), IndexList.end());
689 IndexList.clear();
690 {
691 size_t offset = 0;
692 IndexSet_t::const_iterator listiter = SortedIndexList.begin();
693 IndexArray_t::const_iterator removeiter = removalpoints.begin();
694 for (size_t i = 0; i < allnewpoints.size(); ++i) {
695 if ((removeiter != removalpoints.end()) && (i == *removeiter)) {
696 ++offset;
697 ++removeiter;
698 } else if ((listiter != SortedIndexList.end()) && (i == *listiter)) {
699 IndexList.push_back(*listiter - offset);
700 ++listiter;
701 }
702 }
703 }
704 LOG(4, "DEBUG: Our new bijective IndexList corrected for removed points reads as "
705 << IndexList);
706
707 return IndexList;
[3da643]708}
709
710SphericalPointDistribution::Rotation_t SphericalPointDistribution::findPlaneAligningRotation(
[1cde4e8]711 const PolygonWithIndices &_referencepositions,
712 const PolygonWithIndices &_currentpositions
[3da643]713 )
714{
715 bool dontcheck = false;
716 // initialize to no rotation
717 Rotation_t Rotation;
718 Rotation.first.Zero();
719 Rotation.first[0] = 1.;
720 Rotation.second = 0.;
721
722 // calculate center of triangle/line/point consisting of first points of matching
723 Vector oldCenter;
724 Vector newCenter;
725 calculateOldAndNewCenters(
726 oldCenter, newCenter,
[1cde4e8]727 _referencepositions, _currentpositions);
[3da643]728
[0b517b]729 ASSERT( !oldCenter.IsZero() && !newCenter.IsZero(),
730 "findPlaneAligningRotation() - either old "+toString(oldCenter)
731 +" or new center "+toString(newCenter)+" are zero.");
732 LOG(4, "DEBUG: oldCenter is " << oldCenter << ", newCenter is " << newCenter);
733 if (!oldCenter.IsEqualTo(newCenter)) {
734 // calculate rotation axis and angle
735 Rotation.first = oldCenter;
736 Rotation.first.VectorProduct(newCenter);
737 Rotation.first.Normalize();
738 // construct reference vector to determine direction of rotation
739 const double sign = determineSignOfRotation(newCenter, oldCenter, Rotation.first);
740 Rotation.second = sign * oldCenter.Angle(newCenter);
[3da643]741 } else {
[0b517b]742 // no rotation required anymore
[3da643]743 }
744
745#ifndef NDEBUG
746 // check: rotation brings newCenter onto oldCenter position
747 if (!dontcheck) {
748 Line Axis(zeroVec, Rotation.first);
749 Vector test = Axis.rotateVector(newCenter, Rotation.second);
750 LOG(4, "CHECK: rotated newCenter is " << test
751 << ", oldCenter is " << oldCenter);
752 ASSERT( (test - oldCenter).NormSquared() < std::numeric_limits<double>::epsilon()*1e4,
753 "matchSphericalPointDistributions() - rotation does not work as expected by "
754 +toString((test - oldCenter).NormSquared())+".");
755 }
756#endif
757
758 return Rotation;
759}
760
761SphericalPointDistribution::Rotation_t SphericalPointDistribution::findPointAligningRotation(
[1cde4e8]762 const PolygonWithIndices &remainingold,
763 const PolygonWithIndices &remainingnew)
[3da643]764{
765 // initialize rotation to zero
766 Rotation_t Rotation;
767 Rotation.first.Zero();
768 Rotation.first[0] = 1.;
769 Rotation.second = 0.;
770
771 // recalculate center
772 Vector oldCenter;
773 Vector newCenter;
774 calculateOldAndNewCenters(
775 oldCenter, newCenter,
[1cde4e8]776 remainingold, remainingnew);
[3da643]777
[1cde4e8]778 Vector oldPosition = remainingnew.polygon[*remainingnew.indices.begin()];
779 Vector newPosition = remainingold.polygon[0];
780 LOG(6, "DEBUG: oldPosition is " << oldPosition << " (length: "
781 << oldPosition.Norm() << ") and newPosition is " << newPosition << " length(: "
782 << newPosition.Norm() << ")");
[0b517b]783
[3da643]784 if (!oldPosition.IsEqualTo(newPosition)) {
[0b517b]785 // we rotate at oldCenter and around the radial direction, which is again given
786 // by oldCenter.
787 Rotation.first = oldCenter;
788 Rotation.first.Normalize(); // note weighted sum of normalized weight is not normalized
789 LOG(6, "DEBUG: Using oldCenter " << oldCenter << " as rotation center and "
790 << Rotation.first << " as axis.");
791 oldPosition -= oldCenter;
792 newPosition -= oldCenter;
793 oldPosition = (oldPosition - oldPosition.Projection(Rotation.first));
794 newPosition = (newPosition - newPosition.Projection(Rotation.first));
795 LOG(6, "DEBUG: Positions after projection are " << oldPosition << " and " << newPosition);
796
[3da643]797 // construct reference vector to determine direction of rotation
798 const double sign = determineSignOfRotation(oldPosition, newPosition, Rotation.first);
799 Rotation.second = sign * oldPosition.Angle(newPosition);
800 } else {
801 LOG(6, "DEBUG: oldPosition and newPosition are equivalent, hence no orientating rotation.");
802 }
803
804 return Rotation;
[0d5ca7]805}
806
[e6ca85]807void SphericalPointDistribution::initSelf(const int _NumberOfPoints)
808{
809 switch (_NumberOfPoints)
810 {
811 case 0:
812 points = get<0>();
813 adjacency = getConnections<0>();
814 break;
815 case 1:
816 points = get<1>();
817 adjacency = getConnections<1>();
818 break;
819 case 2:
820 points = get<2>();
821 adjacency = getConnections<2>();
822 break;
823 case 3:
824 points = get<3>();
825 adjacency = getConnections<3>();
826 break;
827 case 4:
828 points = get<4>();
829 adjacency = getConnections<4>();
830 break;
831 case 5:
832 points = get<5>();
833 adjacency = getConnections<5>();
834 break;
835 case 6:
836 points = get<6>();
837 adjacency = getConnections<6>();
838 break;
839 case 7:
840 points = get<7>();
841 adjacency = getConnections<7>();
842 break;
843 case 8:
844 points = get<8>();
845 adjacency = getConnections<8>();
846 break;
847 case 9:
848 points = get<9>();
849 adjacency = getConnections<9>();
850 break;
851 case 10:
852 points = get<10>();
853 adjacency = getConnections<10>();
854 break;
855 case 11:
856 points = get<11>();
857 adjacency = getConnections<11>();
858 break;
859 case 12:
860 points = get<12>();
861 adjacency = getConnections<12>();
862 break;
863 case 14:
864 points = get<14>();
865 adjacency = getConnections<14>();
866 break;
867 default:
868 ASSERT(0, "SphericalPointDistribution::initSelf() - cannot deal with the case "
869 +toString(_NumberOfPoints)+".");
870 }
871 LOG(3, "DEBUG: Ideal polygon is " << points);
872}
[0d5ca7]873
[0d4daf]874SphericalPointDistribution::Polygon_t
[e6ca85]875SphericalPointDistribution::getRemainingPoints(
876 const WeightedPolygon_t &_polygon,
877 const int _N)
[0d4daf]878{
879 SphericalPointDistribution::Polygon_t remainingpoints;
[1cde4e8]880
[e6ca85]881 // initialze to given number of points
882 initSelf(_N);
[0d5ca7]883 LOG(2, "INFO: Matching old polygon " << _polygon
[e6ca85]884 << " with new polygon " << points);
[0d4daf]885
[e6ca85]886 // check whether any points will remain vacant
887 int RemainingPoints = _N;
888 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
889 iter != _polygon.end(); ++iter)
890 RemainingPoints -= iter->second;
891 if (RemainingPoints == 0)
[3da643]892 return remainingpoints;
[0d4daf]893
[e6ca85]894 if (_N > 0) {
895 IndexList_t bestmatching = findBestMatching(_polygon);
[3da643]896 LOG(2, "INFO: Best matching is " << bestmatching);
[0d4daf]897
[1cde4e8]898 const size_t NumberIds = std::min(bestmatching.size(), (size_t)3);
899 // create old set
900 PolygonWithIndices oldSet;
901 oldSet.indices.resize(NumberIds, -1);
902 std::generate(oldSet.indices.begin(), oldSet.indices.end(), UniqueNumber);
903 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
904 iter != _polygon.end(); ++iter)
905 oldSet.polygon.push_back(iter->first);
906
907 // _newpolygon has changed, so now convert to array with matched indices
908 PolygonWithIndices newSet;
909 SphericalPointDistribution::IndexList_t::const_iterator beginiter = bestmatching.begin();
910 SphericalPointDistribution::IndexList_t::const_iterator enditer = bestmatching.begin();
911 std::advance(enditer, NumberIds);
912 newSet.indices.resize(NumberIds, -1);
913 std::copy(beginiter, enditer, newSet.indices.begin());
[e6ca85]914 std::copy(points.begin(),points.end(), std::back_inserter(newSet.polygon));
[23c605]915
[0d4daf]916 // determine rotation angles to align the two point distributions with
[3da643]917 // respect to bestmatching:
918 // we use the center between the three first matching points
919 /// the first rotation brings these two centers to coincide
[1cde4e8]920 PolygonWithIndices rotatednewSet = newSet;
[0d4daf]921 {
[1cde4e8]922 Rotation_t Rotation = findPlaneAligningRotation(oldSet, newSet);
[3da643]923 LOG(5, "DEBUG: Rotating coordinate system by " << Rotation.second
924 << " around axis " << Rotation.first);
925 Line Axis(zeroVec, Rotation.first);
926
927 // apply rotation angle to bring newCenter to oldCenter
[1cde4e8]928 for (VectorArray_t::iterator iter = rotatednewSet.polygon.begin();
929 iter != rotatednewSet.polygon.end(); ++iter) {
[3da643]930 Vector &current = *iter;
931 LOG(6, "DEBUG: Original point is " << current);
932 current = Axis.rotateVector(current, Rotation.second);
933 LOG(6, "DEBUG: Rotated point is " << current);
[0d4daf]934 }
[3da643]935
936#ifndef NDEBUG
937 // check: rotated "newCenter" should now equal oldCenter
[0b517b]938 // we don't check in case of two points as these lie on a great circle
939 // and the center cannot stably be recalculated. We may reactivate this
940 // when we calculate centers only once
941 if (oldSet.indices.size() > 2) {
[3da643]942 Vector oldCenter;
943 Vector rotatednewCenter;
944 calculateOldAndNewCenters(
945 oldCenter, rotatednewCenter,
[1cde4e8]946 oldSet, rotatednewSet);
[a2f8a9]947 oldCenter.Normalize();
948 rotatednewCenter.Normalize();
949 // check whether centers are anti-parallel (factor -1)
950 // then we have the "non-unique poles" situation: points lie on great circle
951 // and both poles are valid solution
952 if (fabs(oldCenter.ScalarProduct(rotatednewCenter) + 1.)
953 < std::numeric_limits<double>::epsilon()*1e4)
954 rotatednewCenter *= -1.;
955 LOG(4, "CHECK: rotatednewCenter is " << rotatednewCenter
956 << ", oldCenter is " << oldCenter);
957 const double difference = (rotatednewCenter - oldCenter).NormSquared();
958 ASSERT( difference < std::numeric_limits<double>::epsilon()*1e4,
959 "matchSphericalPointDistributions() - rotation does not work as expected by "
960 +toString(difference)+".");
[bb011f]961 }
[3da643]962#endif
[bb011f]963 }
[3da643]964 /// the second (orientation) rotation aligns the planes such that the
965 /// points themselves coincide
966 if (bestmatching.size() > 1) {
[1cde4e8]967 Rotation_t Rotation = findPointAligningRotation(oldSet, rotatednewSet);
[3da643]968
969 // construct RotationAxis and two points on its plane, defining the angle
970 Rotation.first.Normalize();
971 const Line RotationAxis(zeroVec, Rotation.first);
972
973 LOG(5, "DEBUG: Rotating around self is " << Rotation.second
974 << " around axis " << RotationAxis);
[bb011f]975
[2d50a2]976#ifndef NDEBUG
[3da643]977 // check: first bestmatching in rotated_newpolygon and remainingnew
978 // should now equal
979 {
980 const IndexList_t::const_iterator iter = bestmatching.begin();
[1cde4e8]981
982 // check whether both old and newPosition are at same distance to oldCenter
983 Vector oldCenter = calculateCenter(oldSet);
984 const double distance = fabs(
985 (oldSet.polygon[0] - oldCenter).NormSquared()
986 - (rotatednewSet.polygon[*iter] - oldCenter).NormSquared()
987 );
988 LOG(4, "CHECK: Squared distance between oldPosition and newPosition "
989 << " with respect to oldCenter " << oldCenter << " is " << distance);
990// ASSERT( distance < warn_amplitude,
991// "matchSphericalPointDistributions() - old and newPosition's squared distance to oldCenter differs by "
992// +toString(distance));
993
[3da643]994 Vector rotatednew = RotationAxis.rotateVector(
[1cde4e8]995 rotatednewSet.polygon[*iter],
[3da643]996 Rotation.second);
997 LOG(4, "CHECK: rotated first new bestmatching is " << rotatednew
[1cde4e8]998 << " while old was " << oldSet.polygon[0]);
999 const double difference = (rotatednew - oldSet.polygon[0]).NormSquared();
1000 ASSERT( difference < distance+1e-8,
1001 "matchSphericalPointDistributions() - orientation rotation ends up off by "
1002 +toString(difference)+", more than "
1003 +toString(distance+1e-8)+".");
[3da643]1004 }
[2d50a2]1005#endif
[0d5ca7]1006
[1cde4e8]1007 for (VectorArray_t::iterator iter = rotatednewSet.polygon.begin();
1008 iter != rotatednewSet.polygon.end(); ++iter) {
[3da643]1009 Vector &current = *iter;
1010 LOG(6, "DEBUG: Original point is " << current);
1011 current = RotationAxis.rotateVector(current, Rotation.second);
1012 LOG(6, "DEBUG: Rotated point is " << current);
[2d50a2]1013 }
1014 }
[0d4daf]1015
1016 // remove all points in matching and return remaining ones
[0d5ca7]1017 SphericalPointDistribution::Polygon_t remainingpoints =
[1cde4e8]1018 removeMatchingPoints(rotatednewSet);
[0d5ca7]1019 LOG(2, "INFO: Remaining points are " << remainingpoints);
1020 return remainingpoints;
[0d4daf]1021 } else
[e6ca85]1022 return points;
[0d4daf]1023}
1024
1025
Note: See TracBrowser for help on using the repository browser.