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

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

Implemented rotations via boost::quaternions.

  • Property mode set to 100644
File size: 13.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>
[2d50a2]45#include <boost/math/quaternion.hpp>
[0d4daf]46#include <cmath>
[0d5ca7]47#include <functional>
48#include <iterator>
[0d4daf]49#include <limits>
50#include <list>
51#include <vector>
52#include <map>
53
54#include "LinearAlgebra/Line.hpp"
55#include "LinearAlgebra/RealSpaceMatrix.hpp"
56#include "LinearAlgebra/Vector.hpp"
57
58typedef std::list<unsigned int> IndexList_t;
59typedef std::vector<unsigned int> IndexArray_t;
60typedef std::vector<Vector> VectorArray_t;
61typedef std::vector<double> DistanceArray_t;
62
63DistanceArray_t calculatePairwiseDistances(
64 const std::vector<Vector> &_points,
65 const IndexList_t &_indices
66 )
67{
68 DistanceArray_t result;
69 for (IndexList_t::const_iterator firstiter = _indices.begin();
70 firstiter != _indices.end(); ++firstiter) {
71 for (IndexList_t::const_iterator seconditer = firstiter;
72 seconditer != _indices.end(); ++seconditer) {
73 if (firstiter == seconditer)
74 continue;
75 const double distance = (_points[*firstiter] - _points[*seconditer]).NormSquared();
76 result.push_back(distance);
77 }
78 }
79 return result;
80}
81
82// class generator: taken from www.cplusplus.com example std::generate
83struct c_unique {
84 int current;
85 c_unique() {current=0;}
[0d5ca7]86 int operator()() {return current++;}
[0d4daf]87} UniqueNumber;
88
89/** Returns squared L2 error of the given \a _Matching.
90 *
91 * We compare the pair-wise distances of each associated matching
92 * and check whether these distances each match between \a _old and
93 * \a _new.
94 *
95 * \param _old first set of points (fewer or equal to \a _new)
96 * \param _new second set of points
97 * \param _Matching matching between the two sets
98 * \return pair with L1 and squared L2 error
99 */
100std::pair<double, double> calculateErrorOfMatching(
101 const std::vector<Vector> &_old,
102 const std::vector<Vector> &_new,
103 const IndexList_t &_Matching)
104{
105 std::pair<double, double> errors( std::make_pair( 0., 0. ) );
106
107 if (_Matching.size() > 1) {
[90426a]108 LOG(3, "INFO: Matching is " << _Matching);
[0d4daf]109
110 // calculate all pair-wise distances
111 IndexList_t keys(_Matching.size());
112 std::generate (keys.begin(), keys.end(), UniqueNumber);
113 const DistanceArray_t firstdistances = calculatePairwiseDistances(_old, keys);
114 const DistanceArray_t seconddistances = calculatePairwiseDistances(_new, _Matching);
115
116 ASSERT( firstdistances.size() == seconddistances.size(),
117 "calculateL2ErrorOfMatching() - mismatch in pair-wise distance array sizes.");
118 DistanceArray_t::const_iterator firstiter = firstdistances.begin();
119 DistanceArray_t::const_iterator seconditer = seconddistances.begin();
120 for (;(firstiter != firstdistances.end()) && (seconditer != seconddistances.end());
121 ++firstiter, ++seconditer) {
122 const double gap = *firstiter - *seconditer;
123 // L1 error
124 if (errors.first < gap)
125 errors.first = gap;
126 // L2 error
127 errors.second += gap*gap;
128 }
[90426a]129 } else
[0d5ca7]130 ELOG(3, "calculateErrorOfMatching() - Given matching's size is less than 2.");
[90426a]131 LOG(3, "INFO: Resulting errors for matching (L1, L2): "
132 << errors.first << "," << errors.second << ".");
[0d4daf]133
134 return errors;
135}
136
137SphericalPointDistribution::Polygon_t removeMatchingPoints(
138 const SphericalPointDistribution::Polygon_t &_points,
139 const IndexList_t &_matchingindices
140 )
141{
142 SphericalPointDistribution::Polygon_t remainingpoints;
143 IndexArray_t indices(_matchingindices.begin(), _matchingindices.end());
144 std::sort(indices.begin(), indices.end());
[90426a]145 LOG(4, "DEBUG: sorted matching is " << indices);
[0d4daf]146 IndexArray_t::const_iterator valueiter = indices.begin();
147 SphericalPointDistribution::Polygon_t::const_iterator pointiter =
148 _points.begin();
149 for (unsigned int i=0; i< _points.size(); ++i, ++pointiter) {
150 // skip all those in values
151 if (*valueiter == i)
152 ++valueiter;
153 else
154 remainingpoints.push_back(*pointiter);
155 }
[90426a]156 LOG(4, "DEBUG: remaining indices are " << remainingpoints);
[0d4daf]157
158 return remainingpoints;
159}
160
161struct MatchingControlStructure {
162 bool foundflag;
163 double bestL2;
164 IndexList_t bestmatching;
165 VectorArray_t oldpoints;
166 VectorArray_t newpoints;
167};
168
169/** Recursive function to go through all possible matchings.
170 *
171 * \param _MCS structure holding global information to the recursion
172 * \param _matching current matching being build up
173 * \param _indices contains still available indices
174 * \param _matchingsize
175 */
176void recurseMatchings(
177 MatchingControlStructure &_MCS,
178 IndexList_t &_matching,
179 IndexList_t _indices,
180 unsigned int _matchingsize)
181{
[90426a]182 LOG(4, "DEBUG: Recursing with current matching " << _matching
183 << ", remaining indices " << _indices
[0d5ca7]184 << ", and sought size " << _matching.size()+_matchingsize);
[0d4daf]185 //!> threshold for L1 error below which matching is immediately acceptable
186 const double L1THRESHOLD = 1e-2;
187 if (!_MCS.foundflag) {
[0d5ca7]188 LOG(4, "DEBUG: Current matching has size " << _matching.size() << ", places left " << _matchingsize);
189 if (_matchingsize > 0) {
[0d4daf]190 // go through all indices
191 for (IndexList_t::iterator iter = _indices.begin();
[0d5ca7]192 (iter != _indices.end()) && (!_MCS.foundflag);) {
[0d4daf]193 // add index to matching
194 _matching.push_back(*iter);
[0d5ca7]195 LOG(5, "DEBUG: Adding " << *iter << " to matching.");
[0d4daf]196 // remove index but keep iterator to position (is the next to erase element)
197 IndexList_t::iterator backupiter = _indices.erase(iter);
198 // recurse with decreased _matchingsize
199 recurseMatchings(_MCS, _matching, _indices, _matchingsize-1);
200 // re-add chosen index and reset index to new position
201 _indices.insert(backupiter, _matching.back());
202 iter = backupiter;
203 // remove index from _matching to make space for the next one
204 _matching.pop_back();
205 }
206 // gone through all indices then exit recursion
[0d5ca7]207 if (_matching.empty())
208 _MCS.foundflag = true;
[0d4daf]209 } else {
[90426a]210 LOG(3, "INFO: Found matching " << _matching);
[0d4daf]211 // calculate errors
212 std::pair<double, double> errors = calculateErrorOfMatching(
213 _MCS.oldpoints, _MCS.newpoints, _matching);
214 if (errors.first < L1THRESHOLD) {
215 _MCS.bestmatching = _matching;
216 _MCS.foundflag = true;
[0d5ca7]217 } else if (_MCS.bestL2 > errors.second) {
[0d4daf]218 _MCS.bestmatching = _matching;
219 _MCS.bestL2 = errors.second;
220 }
221 }
222 }
223}
224
[0d5ca7]225/** Rotates a given polygon around x, y, and z axis by the given angles.
226 *
227 * \param _polygon polygon whose points to rotate
[2d50a2]228 * \param _q quaternion specifying the rotation of the coordinate system
[0d5ca7]229 */
230SphericalPointDistribution::Polygon_t rotatePolygon(
231 const SphericalPointDistribution::Polygon_t &_polygon,
[2d50a2]232 const boost::math::quaternion<double> &_q)
[0d5ca7]233{
234 SphericalPointDistribution::Polygon_t rotated_polygon = _polygon;
[2d50a2]235 boost::math::quaternion<double> q_inverse =
236 boost::math::conj(_q)/(boost::math::norm(_q));
[0d5ca7]237
238 // apply rotation angles
239 for (SphericalPointDistribution::Polygon_t::iterator iter = rotated_polygon.begin();
240 iter != rotated_polygon.end(); ++iter) {
[2d50a2]241 Vector &current = *iter;
242 boost::math::quaternion<double> p(0, current[0], current[1], current[2]);
243 p = _q * p * q_inverse;
244 LOG(5, "DEBUG: Rotated point is " << p);
245 // i have no idea why but first component comes up with wrong sign
246 current[0] = -p.R_component_2();
247 current[1] = p.R_component_3();
248 current[2] = p.R_component_4();
[0d5ca7]249 }
250
251 return rotated_polygon;
252}
253
254
[0d4daf]255SphericalPointDistribution::Polygon_t
256SphericalPointDistribution::matchSphericalPointDistributions(
257 const SphericalPointDistribution::Polygon_t &_polygon,
258 const SphericalPointDistribution::Polygon_t &_newpolygon
259 )
260{
261 SphericalPointDistribution::Polygon_t remainingpoints;
262 VectorArray_t remainingold(_polygon.begin(), _polygon.end());
263 VectorArray_t remainingnew(_newpolygon.begin(), _newpolygon.end());
[0d5ca7]264 LOG(2, "INFO: Matching old polygon " << _polygon
[90426a]265 << " with new polygon " << _newpolygon);
[0d4daf]266
267 if (_polygon.size() > 0) {
268 MatchingControlStructure MCS;
269 MCS.foundflag = false;
270 MCS.bestL2 = std::numeric_limits<double>::max();
271 MCS.oldpoints.insert(MCS.oldpoints.begin(), _polygon.begin(),_polygon.end() );
272 MCS.newpoints.insert(MCS.newpoints.begin(), _newpolygon.begin(),_newpolygon.end() );
273
274 // search for bestmatching combinatorially
275 {
276 // translate polygon into vector to enable index addressing
277 IndexList_t indices(_newpolygon.size());
278 std::generate(indices.begin(), indices.end(), UniqueNumber);
279 IndexList_t matching;
280
281 // walk through all matchings
282 const unsigned int matchingsize = _polygon.size();
283 ASSERT( matchingsize <= indices.size(),
284 "SphericalPointDistribution::matchSphericalPointDistributions() - not enough new points to choose for matching to old ones.");
285 recurseMatchings(MCS, matching, indices, matchingsize);
286 }
[0d5ca7]287 LOG(2, "INFO: Best matching is " << MCS.bestmatching);
[0d4daf]288
289 // determine rotation angles to align the two point distributions with
290 // respect to bestmatching
[2d50a2]291 SphericalPointDistribution::Polygon_t rotated_newpolygon;
[0d5ca7]292 Vector oldCenter;
[0d4daf]293 {
294 // calculate center of triangle/line/point consisting of first points of matching
[2d50a2]295 Vector newCenter;
[0d4daf]296 IndexList_t::const_iterator iter = MCS.bestmatching.begin();
297 unsigned int i = 0;
298 for (; (i<3) && (i<MCS.bestmatching.size()); ++i, ++iter) {
299 oldCenter += remainingold[i];
300 newCenter += remainingnew[*iter];
301 }
302 oldCenter *= 1./(double)i;
303 newCenter *= 1./(double)i;
[0d5ca7]304 LOG(4, "DEBUG: oldCenter is " << oldCenter << ", newCenter is " << newCenter);
305
[2d50a2]306 if ((oldCenter - newCenter).NormSquared() > std::numeric_limits<double>::epsilon()*1e4) {
307 // setup quaternion
308 Vector RotationAxis = newCenter;
309 RotationAxis.VectorProduct(oldCenter);
310 RotationAxis.Normalize();
311 const double RotationAngle = oldCenter.Angle(newCenter)/(M_PI/2.);
312// RotationAxis.Angle(oldCenter) - RotationAxis.Angle(newCenter);
313 boost::math::quaternion<double> q
314 (RotationAngle, RotationAxis[0], RotationAxis[1], RotationAxis[2]);
315 LOG(5, "DEBUG: RotationAxis is " << RotationAxis
316 << ", RotationAngle is " << RotationAngle);
317 LOG(5, "DEBUG: Quaternion describing rotation is " << q);
318#ifndef NDEBUG
319 {
320 // check that rotation works in DEBUG mode
321 boost::math::quaternion<double> p(0., newCenter[0], newCenter[1], newCenter[2]);
322 boost::math::quaternion<double> q_inverse =
323 boost::math::conj(q)/(boost::math::norm(q));
324 p = q * p * q_inverse;
325 boost::math::quaternion<double> identity(1,0,0,0);
326 ASSERT( boost::math::norm(q*q_inverse - identity) < std::numeric_limits<double>::epsilon()*1e4,
327 "matchSphericalPointDistributions() - quaternion does not rotate newCenter "
328 +toString(q*q_inverse)+" into oldCenter "+toString(identity)+".");
329 boost::math::quaternion<double> comparison(0., -oldCenter[0], oldCenter[1], oldCenter[2]);
330 ASSERT( boost::math::norm(p - comparison) < std::numeric_limits<double>::epsilon()*1e4,
331 "matchSphericalPointDistributions() - quaternion does not rotate newCenter "
332 +toString(p)+" into oldCenter "+toString(comparison)+".");
333 }
334#endif
[0d5ca7]335
[2d50a2]336 // rotate spherical distribution
337 rotated_newpolygon = rotatePolygon(_newpolygon, q);
338 LOG(5, "DEBUG: Rotated new polygon is " << rotated_newpolygon);
339 } else {
340 rotated_newpolygon = _newpolygon;
341 }
342 }
343 // rotate triangle/line/point around itself to match orientation
[0d5ca7]344 const Line RotationAxis(zeroVec, oldCenter);
[0d4daf]345 const double RotationAngle =
[0d5ca7]346 oldCenter.Angle(remainingold[0])
347 - oldCenter.Angle(remainingnew[*MCS.bestmatching.begin()]);
348 LOG(5, "DEBUG: Rotate around self is " << RotationAngle
[90426a]349 << " around axis " << RotationAxis);
[0d4daf]350
[0d5ca7]351 for (SphericalPointDistribution::Polygon_t::iterator iter = rotated_newpolygon.begin();
352 iter != rotated_newpolygon.end(); ++iter) {
353 RotationAxis.rotateVector(*iter, RotationAngle);
354 }
[0d4daf]355
356 // remove all points in matching and return remaining ones
[0d5ca7]357 SphericalPointDistribution::Polygon_t remainingpoints =
358 removeMatchingPoints(rotated_newpolygon, MCS.bestmatching);
359 LOG(2, "INFO: Remaining points are " << remainingpoints);
360 return remainingpoints;
[0d4daf]361 } else
362 return _newpolygon;
363}
364
365
Note: See TracBrowser for help on using the repository browser.