source: src/Fragmentation/Exporters/SphericalPointDistribution.cpp@ 2ccdf4

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 2ccdf4 was 2d8c4e, checked in by Frederik Heber <heber@…>, 9 years ago

Removed all IsZero() checking and special cases for the triangle idea.

  • Property mode set to 100644
File size: 35.9 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#ifndef NDEBUG
686 bool dontcheck = false;
687#endif
688 // initialize to no rotation
689 Rotation_t Rotation;
690 Rotation.first.Zero();
691 Rotation.first[0] = 1.;
692 Rotation.second = 0.;
693
694 // calculate center of triangle/line/point consisting of first points of matching
695 Vector oldCenter;
696 Vector newCenter;
697 calculateOldAndNewCenters(
698 oldCenter, newCenter,
699 _referencepositions, _currentpositions);
700
701 ASSERT( !oldCenter.IsZero() && !newCenter.IsZero(),
702 "findPlaneAligningRotation() - either old "+toString(oldCenter)
703 +" or new center "+toString(newCenter)+" are zero.");
704 LOG(4, "DEBUG: oldCenter is " << oldCenter << ", newCenter is " << newCenter);
705 if (!oldCenter.IsEqualTo(newCenter)) {
706 // calculate rotation axis and angle
707 Rotation.first = oldCenter;
708 Rotation.first.VectorProduct(newCenter);
709 Rotation.first.Normalize();
710 // construct reference vector to determine direction of rotation
711 const double sign = determineSignOfRotation(newCenter, oldCenter, Rotation.first);
712 Rotation.second = sign * oldCenter.Angle(newCenter);
713 } else {
714 // no rotation required anymore
715 }
716
717#ifndef NDEBUG
718 // check: rotation brings newCenter onto oldCenter position
719 if (!dontcheck) {
720 Line Axis(zeroVec, Rotation.first);
721 Vector test = Axis.rotateVector(newCenter, Rotation.second);
722 LOG(4, "CHECK: rotated newCenter is " << test
723 << ", oldCenter is " << oldCenter);
724 ASSERT( (test - oldCenter).NormSquared() < std::numeric_limits<double>::epsilon()*1e4,
725 "matchSphericalPointDistributions() - rotation does not work as expected by "
726 +toString((test - oldCenter).NormSquared())+".");
727 }
728#endif
729
730 return Rotation;
731}
732
733SphericalPointDistribution::Rotation_t SphericalPointDistribution::findPointAligningRotation(
734 const PolygonWithIndices &remainingold,
735 const PolygonWithIndices &remainingnew)
736{
737 // initialize rotation to zero
738 Rotation_t Rotation;
739 Rotation.first.Zero();
740 Rotation.first[0] = 1.;
741 Rotation.second = 0.;
742
743 // recalculate center
744 Vector oldCenter;
745 Vector newCenter;
746 calculateOldAndNewCenters(
747 oldCenter, newCenter,
748 remainingold, remainingnew);
749
750 Vector oldPosition = remainingnew.polygon[*remainingnew.indices.begin()];
751 Vector newPosition = remainingold.polygon[0];
752 LOG(6, "DEBUG: oldPosition is " << oldPosition << " (length: "
753 << oldPosition.Norm() << ") and newPosition is " << newPosition << " length(: "
754 << newPosition.Norm() << ")");
755
756 if (!oldPosition.IsEqualTo(newPosition)) {
757 // we rotate at oldCenter and around the radial direction, which is again given
758 // by oldCenter.
759 Rotation.first = oldCenter;
760 Rotation.first.Normalize(); // note weighted sum of normalized weight is not normalized
761 LOG(6, "DEBUG: Using oldCenter " << oldCenter << " as rotation center and "
762 << Rotation.first << " as axis.");
763 oldPosition -= oldCenter;
764 newPosition -= oldCenter;
765 oldPosition = (oldPosition - oldPosition.Projection(Rotation.first));
766 newPosition = (newPosition - newPosition.Projection(Rotation.first));
767 LOG(6, "DEBUG: Positions after projection are " << oldPosition << " and " << newPosition);
768
769 // construct reference vector to determine direction of rotation
770 const double sign = determineSignOfRotation(oldPosition, newPosition, Rotation.first);
771 Rotation.second = sign * oldPosition.Angle(newPosition);
772 } else {
773 LOG(6, "DEBUG: oldPosition and newPosition are equivalent, hence no orientating rotation.");
774 }
775
776 return Rotation;
777}
778
779
780SphericalPointDistribution::Polygon_t
781SphericalPointDistribution::matchSphericalPointDistributions(
782 const SphericalPointDistribution::WeightedPolygon_t &_polygon,
783 SphericalPointDistribution::Polygon_t &_newpolygon
784 )
785{
786 SphericalPointDistribution::Polygon_t remainingpoints;
787
788 LOG(2, "INFO: Matching old polygon " << _polygon
789 << " with new polygon " << _newpolygon);
790
791 if (_polygon.size() == _newpolygon.size()) {
792 // same number of points desired as are present? Do nothing
793 LOG(2, "INFO: There are no vacant points to return.");
794 return remainingpoints;
795 }
796
797 if (_polygon.size() > 0) {
798 IndexList_t bestmatching = findBestMatching(_polygon, _newpolygon);
799 LOG(2, "INFO: Best matching is " << bestmatching);
800
801 const size_t NumberIds = std::min(bestmatching.size(), (size_t)3);
802 // create old set
803 PolygonWithIndices oldSet;
804 oldSet.indices.resize(NumberIds, -1);
805 std::generate(oldSet.indices.begin(), oldSet.indices.end(), UniqueNumber);
806 for (WeightedPolygon_t::const_iterator iter = _polygon.begin();
807 iter != _polygon.end(); ++iter)
808 oldSet.polygon.push_back(iter->first);
809
810 // _newpolygon has changed, so now convert to array with matched indices
811 PolygonWithIndices newSet;
812 SphericalPointDistribution::IndexList_t::const_iterator beginiter = bestmatching.begin();
813 SphericalPointDistribution::IndexList_t::const_iterator enditer = bestmatching.begin();
814 std::advance(enditer, NumberIds);
815 newSet.indices.resize(NumberIds, -1);
816 std::copy(beginiter, enditer, newSet.indices.begin());
817 std::copy(_newpolygon.begin(),_newpolygon.end(), std::back_inserter(newSet.polygon));
818
819 // determine rotation angles to align the two point distributions with
820 // respect to bestmatching:
821 // we use the center between the three first matching points
822 /// the first rotation brings these two centers to coincide
823 PolygonWithIndices rotatednewSet = newSet;
824 {
825 Rotation_t Rotation = findPlaneAligningRotation(oldSet, newSet);
826 LOG(5, "DEBUG: Rotating coordinate system by " << Rotation.second
827 << " around axis " << Rotation.first);
828 Line Axis(zeroVec, Rotation.first);
829
830 // apply rotation angle to bring newCenter to oldCenter
831 for (VectorArray_t::iterator iter = rotatednewSet.polygon.begin();
832 iter != rotatednewSet.polygon.end(); ++iter) {
833 Vector &current = *iter;
834 LOG(6, "DEBUG: Original point is " << current);
835 current = Axis.rotateVector(current, Rotation.second);
836 LOG(6, "DEBUG: Rotated point is " << current);
837 }
838
839#ifndef NDEBUG
840 // check: rotated "newCenter" should now equal oldCenter
841 // we don't check in case of two points as these lie on a great circle
842 // and the center cannot stably be recalculated. We may reactivate this
843 // when we calculate centers only once
844 if (oldSet.indices.size() > 2) {
845 Vector oldCenter;
846 Vector rotatednewCenter;
847 calculateOldAndNewCenters(
848 oldCenter, rotatednewCenter,
849 oldSet, rotatednewSet);
850 oldCenter.Normalize();
851 rotatednewCenter.Normalize();
852 // check whether centers are anti-parallel (factor -1)
853 // then we have the "non-unique poles" situation: points lie on great circle
854 // and both poles are valid solution
855 if (fabs(oldCenter.ScalarProduct(rotatednewCenter) + 1.)
856 < std::numeric_limits<double>::epsilon()*1e4)
857 rotatednewCenter *= -1.;
858 LOG(4, "CHECK: rotatednewCenter is " << rotatednewCenter
859 << ", oldCenter is " << oldCenter);
860 const double difference = (rotatednewCenter - oldCenter).NormSquared();
861 ASSERT( difference < std::numeric_limits<double>::epsilon()*1e4,
862 "matchSphericalPointDistributions() - rotation does not work as expected by "
863 +toString(difference)+".");
864 }
865#endif
866 }
867 /// the second (orientation) rotation aligns the planes such that the
868 /// points themselves coincide
869 if (bestmatching.size() > 1) {
870 Rotation_t Rotation = findPointAligningRotation(oldSet, rotatednewSet);
871
872 // construct RotationAxis and two points on its plane, defining the angle
873 Rotation.first.Normalize();
874 const Line RotationAxis(zeroVec, Rotation.first);
875
876 LOG(5, "DEBUG: Rotating around self is " << Rotation.second
877 << " around axis " << RotationAxis);
878
879#ifndef NDEBUG
880 // check: first bestmatching in rotated_newpolygon and remainingnew
881 // should now equal
882 {
883 const IndexList_t::const_iterator iter = bestmatching.begin();
884
885 // check whether both old and newPosition are at same distance to oldCenter
886 Vector oldCenter = calculateCenter(oldSet);
887 const double distance = fabs(
888 (oldSet.polygon[0] - oldCenter).NormSquared()
889 - (rotatednewSet.polygon[*iter] - oldCenter).NormSquared()
890 );
891 LOG(4, "CHECK: Squared distance between oldPosition and newPosition "
892 << " with respect to oldCenter " << oldCenter << " is " << distance);
893// ASSERT( distance < warn_amplitude,
894// "matchSphericalPointDistributions() - old and newPosition's squared distance to oldCenter differs by "
895// +toString(distance));
896
897 Vector rotatednew = RotationAxis.rotateVector(
898 rotatednewSet.polygon[*iter],
899 Rotation.second);
900 LOG(4, "CHECK: rotated first new bestmatching is " << rotatednew
901 << " while old was " << oldSet.polygon[0]);
902 const double difference = (rotatednew - oldSet.polygon[0]).NormSquared();
903 ASSERT( difference < distance+1e-8,
904 "matchSphericalPointDistributions() - orientation rotation ends up off by "
905 +toString(difference)+", more than "
906 +toString(distance+1e-8)+".");
907 }
908#endif
909
910 for (VectorArray_t::iterator iter = rotatednewSet.polygon.begin();
911 iter != rotatednewSet.polygon.end(); ++iter) {
912 Vector &current = *iter;
913 LOG(6, "DEBUG: Original point is " << current);
914 current = RotationAxis.rotateVector(current, Rotation.second);
915 LOG(6, "DEBUG: Rotated point is " << current);
916 }
917 }
918
919 // remove all points in matching and return remaining ones
920 SphericalPointDistribution::Polygon_t remainingpoints =
921 removeMatchingPoints(rotatednewSet);
922 LOG(2, "INFO: Remaining points are " << remainingpoints);
923 return remainingpoints;
924 } else
925 return _newpolygon;
926}
Note: See TracBrowser for help on using the repository browser.