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