source: src/Fragmentation/Exporters/SphericalPointDistribution.cpp@ 90426a

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

Added Logging to SphericalPointDistribution for debugging.

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