source: src/Fragmentation/Exporters/SphericalPointDistribution.cpp@ 6aa6b7

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

Dropped quaternion rotation for simple arbitrary rotation axis and angle.

  • with newCenter, oldCenter and the cross product we have all we need: a rotation axis and an angle. We don't need to burden ourselves with those stupid, absolutely not working quaternions.
  • removeMatchingPoints() now works on an array.
  • Orientation rotation was wrong way round, added check.
  • TESTFIX: removed QuaternionTest from SphericalPointDistributionTest, marked FragmentMolecule-cycle and StoreSaturatedFragment regression tests as XFAIL.
  • Property mode set to 100644
File size: 14.3 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/math/quaternion.hpp>
46#include <cmath>
47#include <functional>
48#include <iterator>
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;}
86 int operator()() {return current++;}
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) {
108 LOG(3, "INFO: Matching is " << _Matching);
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 }
129 } else
130 ELOG(3, "calculateErrorOfMatching() - Given matching's size is less than 2.");
131 LOG(3, "INFO: Resulting errors for matching (L1, L2): "
132 << errors.first << "," << errors.second << ".");
133
134 return errors;
135}
136
137SphericalPointDistribution::Polygon_t removeMatchingPoints(
138 const VectorArray_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());
145 LOG(4, "DEBUG: sorted matching is " << indices);
146 IndexArray_t remainingindices(_points.size(), -1);
147 std::generate(remainingindices.begin(), remainingindices.end(), UniqueNumber);
148 IndexArray_t::iterator remainiter = std::set_difference(
149 remainingindices.begin(), remainingindices.end(),
150 indices.begin(), indices.end(),
151 remainingindices.begin());
152 remainingindices.erase(remainiter, remainingindices.end());
153 LOG(4, "DEBUG: remaining indices are " << remainingindices);
154 for (IndexArray_t::const_iterator iter = remainingindices.begin();
155 iter != remainingindices.end(); ++iter) {
156 remainingpoints.push_back(_points[*iter]);
157 }
158
159 return remainingpoints;
160}
161
162struct MatchingControlStructure {
163 bool foundflag;
164 double bestL2;
165 IndexList_t bestmatching;
166 VectorArray_t oldpoints;
167 VectorArray_t newpoints;
168};
169
170/** Recursive function to go through all possible matchings.
171 *
172 * \param _MCS structure holding global information to the recursion
173 * \param _matching current matching being build up
174 * \param _indices contains still available indices
175 * \param _matchingsize
176 */
177void recurseMatchings(
178 MatchingControlStructure &_MCS,
179 IndexList_t &_matching,
180 IndexList_t _indices,
181 unsigned int _matchingsize)
182{
183 LOG(4, "DEBUG: Recursing with current matching " << _matching
184 << ", remaining indices " << _indices
185 << ", and sought size " << _matching.size()+_matchingsize);
186 //!> threshold for L1 error below which matching is immediately acceptable
187 const double L1THRESHOLD = 1e-2;
188 if (!_MCS.foundflag) {
189 LOG(4, "DEBUG: Current matching has size " << _matching.size() << ", places left " << _matchingsize);
190 if (_matchingsize > 0) {
191 // go through all indices
192 for (IndexList_t::iterator iter = _indices.begin();
193 (iter != _indices.end()) && (!_MCS.foundflag);) {
194 // add index to matching
195 _matching.push_back(*iter);
196 LOG(5, "DEBUG: Adding " << *iter << " to matching.");
197 // remove index but keep iterator to position (is the next to erase element)
198 IndexList_t::iterator backupiter = _indices.erase(iter);
199 // recurse with decreased _matchingsize
200 recurseMatchings(_MCS, _matching, _indices, _matchingsize-1);
201 // re-add chosen index and reset index to new position
202 _indices.insert(backupiter, _matching.back());
203 iter = backupiter;
204 // remove index from _matching to make space for the next one
205 _matching.pop_back();
206 }
207 // gone through all indices then exit recursion
208 if (_matching.empty())
209 _MCS.foundflag = true;
210 } else {
211 LOG(3, "INFO: Found matching " << _matching);
212 // calculate errors
213 std::pair<double, double> errors = calculateErrorOfMatching(
214 _MCS.oldpoints, _MCS.newpoints, _matching);
215 if (errors.first < L1THRESHOLD) {
216 _MCS.bestmatching = _matching;
217 _MCS.foundflag = true;
218 } else if (_MCS.bestL2 > errors.second) {
219 _MCS.bestmatching = _matching;
220 _MCS.bestL2 = errors.second;
221 }
222 }
223 }
224}
225
226/** Rotates a given polygon around x, y, and z axis by the given angles.
227 *
228 * \param _polygon polygon whose points to rotate
229 * \param _q quaternion specifying the rotation of the coordinate system
230 */
231SphericalPointDistribution::Polygon_t rotatePolygon(
232 const SphericalPointDistribution::Polygon_t &_polygon,
233 const boost::math::quaternion<double> &_q)
234{
235 SphericalPointDistribution::Polygon_t rotated_polygon = _polygon;
236 boost::math::quaternion<double> q_inverse =
237 boost::math::conj(_q)/(boost::math::norm(_q));
238
239 // apply rotation angles
240 for (SphericalPointDistribution::Polygon_t::iterator iter = rotated_polygon.begin();
241 iter != rotated_polygon.end(); ++iter) {
242 Vector &current = *iter;
243 boost::math::quaternion<double> p(0, current[0], current[1], current[2]);
244 p = _q * p * q_inverse;
245 LOG(5, "DEBUG: Rotated point is " << p);
246 // i have no idea why but first component comes up with wrong sign
247 current[0] = -p.R_component_2();
248 current[1] = p.R_component_3();
249 current[2] = p.R_component_4();
250 }
251
252 return rotated_polygon;
253}
254
255
256SphericalPointDistribution::Polygon_t
257SphericalPointDistribution::matchSphericalPointDistributions(
258 const SphericalPointDistribution::Polygon_t &_polygon,
259 const SphericalPointDistribution::Polygon_t &_newpolygon
260 )
261{
262 SphericalPointDistribution::Polygon_t remainingpoints;
263 VectorArray_t remainingold(_polygon.begin(), _polygon.end());
264 VectorArray_t remainingnew(_newpolygon.begin(), _newpolygon.end());
265 LOG(2, "INFO: Matching old polygon " << _polygon
266 << " with new polygon " << _newpolygon);
267
268 if (_polygon.size() > 0) {
269 MatchingControlStructure MCS;
270 MCS.foundflag = false;
271 MCS.bestL2 = std::numeric_limits<double>::max();
272 MCS.oldpoints.insert(MCS.oldpoints.begin(), _polygon.begin(),_polygon.end() );
273 MCS.newpoints.insert(MCS.newpoints.begin(), _newpolygon.begin(),_newpolygon.end() );
274
275 // search for bestmatching combinatorially
276 {
277 // translate polygon into vector to enable index addressing
278 IndexList_t indices(_newpolygon.size());
279 std::generate(indices.begin(), indices.end(), UniqueNumber);
280 IndexList_t matching;
281
282 // walk through all matchings
283 const unsigned int matchingsize = _polygon.size();
284 ASSERT( matchingsize <= indices.size(),
285 "SphericalPointDistribution::matchSphericalPointDistributions() - not enough new points to choose for matching to old ones.");
286 recurseMatchings(MCS, matching, indices, matchingsize);
287 }
288 LOG(2, "INFO: Best matching is " << MCS.bestmatching);
289
290 // determine rotation angles to align the two point distributions with
291 // respect to bestmatching
292 VectorArray_t rotated_newpolygon = remainingnew;
293 Vector oldCenter;
294 {
295 // calculate center of triangle/line/point consisting of first points of matching
296 Vector newCenter;
297 IndexList_t::const_iterator iter = MCS.bestmatching.begin();
298 unsigned int i = 0;
299 for (; (i<3) && (i<MCS.bestmatching.size()); ++i, ++iter) {
300 oldCenter += remainingold[i];
301 newCenter += remainingnew[*iter];
302 }
303 oldCenter *= 1./(double)i;
304 newCenter *= 1./(double)i;
305 LOG(4, "DEBUG: oldCenter is " << oldCenter << ", newCenter is " << newCenter);
306
307 if ((oldCenter - newCenter).NormSquared() > std::numeric_limits<double>::epsilon()*1e4) {
308 // setup quaternion
309 Vector RotationAxis = oldCenter;
310 RotationAxis.VectorProduct(newCenter);
311 Line Axis(zeroVec, RotationAxis);
312 RotationAxis.Normalize();
313 const double RotationAngle = oldCenter.Angle(newCenter); // /(M_PI/2.);
314 LOG(5, "DEBUG: Rotate coordinate system by " << RotationAngle
315 << " around axis " << RotationAxis);
316
317 // apply rotation angles
318 for (VectorArray_t::iterator iter = rotated_newpolygon.begin();
319 iter != rotated_newpolygon.end(); ++iter) {
320 Vector &current = *iter;
321 LOG(5, "DEBUG: Original point is " << current);
322 current = Axis.rotateVector(current, RotationAngle);
323 LOG(5, "DEBUG: Rotated point is " << current);
324 }
325 }
326 }
327 // rotate triangle/line/point around itself to match orientation
328 if (MCS.bestmatching.size() > 1) {
329 if (oldCenter.NormSquared() > std::numeric_limits<double>::epsilon()*1e4) {
330 // construct RotationAxis and two points on its plane, defining the angle
331 const Line RotationAxis(zeroVec, oldCenter);
332 Vector oldPosition(rotated_newpolygon[*MCS.bestmatching.begin()]);
333 oldPosition.ProjectOntoPlane(RotationAxis.getDirection());
334 Vector newPosition(remainingold[*MCS.bestmatching.begin()]);
335 newPosition.ProjectOntoPlane(RotationAxis.getDirection());
336
337 // construct reference vector to determine direction of rotation
338 Vector dreiBein(oldPosition);
339 dreiBein.VectorProduct(oldCenter);
340 dreiBein.Normalize();
341 const double sign =
342 (dreiBein.ScalarProduct(newPosition) < 0.) ? -1. : +1.;
343 LOG(6, "DEBUG: oldCenter on plane is " << oldPosition
344 << ", newCenter in plane is " << newPosition
345 << ", and dreiBein is " << dreiBein);
346 const double RotationAngle = sign * oldPosition.Angle(newPosition);
347 LOG(5, "DEBUG: Rotating around self is " << RotationAngle
348 << " around axis " << RotationAxis);
349
350#ifndef NDEBUG
351 // check: first bestmatching in rotated_newpolygon and remainingnew
352 // should now equal
353 {
354 const IndexList_t::const_iterator iter = MCS.bestmatching.begin();
355 Vector rotatednew = RotationAxis.rotateVector(
356 rotated_newpolygon[*iter],
357 RotationAngle);
358 LOG(4, "CHECK: rotated first new bestmatching is " << rotatednew
359 << " while old was " << remainingold[*iter]);
360 ASSERT( (rotatednew - remainingold[*iter]).Norm()
361 < std::numeric_limits<double>::epsilon()*1e4,
362 "matchSphericalPointDistributions() - orientation rotation does not work as expected.");
363 }
364#endif
365
366 for (VectorArray_t::iterator iter = rotated_newpolygon.begin();
367 iter != rotated_newpolygon.end(); ++iter) {
368 Vector &current = *iter;
369 LOG(6, "DEBUG: Original point is " << current);
370 current = RotationAxis.rotateVector(current, RotationAngle);
371 LOG(6, "DEBUG: Rotated point is " << current);
372 }
373 }
374 }
375
376 // remove all points in matching and return remaining ones
377 SphericalPointDistribution::Polygon_t remainingpoints =
378 removeMatchingPoints(rotated_newpolygon, MCS.bestmatching);
379 LOG(2, "INFO: Remaining points are " << remainingpoints);
380 return remainingpoints;
381 } else
382 return _newpolygon;
383}
384
385
Note: See TracBrowser for help on using the repository browser.