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 |
|
---|
55 | typedef std::list<unsigned int> IndexList_t;
|
---|
56 | typedef std::vector<unsigned int> IndexArray_t;
|
---|
57 | typedef std::vector<Vector> VectorArray_t;
|
---|
58 | typedef std::vector<double> DistanceArray_t;
|
---|
59 |
|
---|
60 | // static instances
|
---|
61 | const double SphericalPointDistribution::SQRT_3(sqrt(3.0));
|
---|
62 |
|
---|
63 | DistanceArray_t calculatePairwiseDistances(
|
---|
64 | const std::vector<Vector> &_returnpolygon,
|
---|
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 = (_returnpolygon[*firstiter] - _returnpolygon[*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
|
---|
83 | struct 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 returnpolygon (fewer or equal to \a _new)
|
---|
96 | * \param _new second set of returnpolygon
|
---|
97 | * \param _Matching matching between the two sets
|
---|
98 | * \return pair with L1 and squared L2 error
|
---|
99 | */
|
---|
100 | std::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 | // convert matching into two vectors to calculate distance among another
|
---|
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 | }
|
---|
130 |
|
---|
131 | return errors;
|
---|
132 | }
|
---|
133 |
|
---|
134 | SphericalPointDistribution::Polygon_t removeMatchingPoints(
|
---|
135 | const SphericalPointDistribution::Polygon_t &_returnpolygon,
|
---|
136 | const IndexList_t &_matchingindices
|
---|
137 | )
|
---|
138 | {
|
---|
139 | SphericalPointDistribution::Polygon_t remainingreturnpolygon;
|
---|
140 | IndexArray_t indices(_matchingindices.begin(), _matchingindices.end());
|
---|
141 | std::sort(indices.begin(), indices.end());
|
---|
142 | IndexArray_t::const_iterator valueiter = indices.begin();
|
---|
143 | SphericalPointDistribution::Polygon_t::const_iterator pointiter =
|
---|
144 | _returnpolygon.begin();
|
---|
145 | for (unsigned int i=0; i< _returnpolygon.size(); ++i, ++pointiter) {
|
---|
146 | // skip all those in values
|
---|
147 | if (*valueiter == i)
|
---|
148 | ++valueiter;
|
---|
149 | else
|
---|
150 | remainingreturnpolygon.push_back(*pointiter);
|
---|
151 | }
|
---|
152 |
|
---|
153 | return remainingreturnpolygon;
|
---|
154 | }
|
---|
155 |
|
---|
156 | /** Rotates a given polygon around x, y, and z axis by the given angles.
|
---|
157 | *
|
---|
158 | * Essentially, we concentrate on the three returnpolygon of the polygon to rotate
|
---|
159 | * to the correct position. First, we rotate its center via \a angles,
|
---|
160 | * then we rotate the "triangle" around itself/\a _RotationAxis by
|
---|
161 | * \a _RotationAngle.
|
---|
162 | *
|
---|
163 | * \param _polygon polygon whose returnpolygon to rotate
|
---|
164 | * \param _angles vector with rotation angles for x,y,z axis
|
---|
165 | * \param _RotationAxis
|
---|
166 | * \param _RotationAngle
|
---|
167 | */
|
---|
168 | SphericalPointDistribution::Polygon_t rotatePolygon(
|
---|
169 | const SphericalPointDistribution::Polygon_t &_polygon,
|
---|
170 | const std::vector<double> &_angles,
|
---|
171 | const Line &_RotationAxis,
|
---|
172 | const double _RotationAngle)
|
---|
173 | {
|
---|
174 | SphericalPointDistribution::Polygon_t rotated_polygon = _polygon;
|
---|
175 | RealSpaceMatrix rotation;
|
---|
176 | ASSERT( _angles.size() == 3,
|
---|
177 | "rotatePolygon() - not exactly "+toString(3)+" angles given.");
|
---|
178 | rotation.setRotation(_angles[0] * M_PI/180., _angles[1] * M_PI/180., _angles[2] * M_PI/180.);
|
---|
179 |
|
---|
180 | // apply rotation angles
|
---|
181 | for (SphericalPointDistribution::Polygon_t::iterator iter = rotated_polygon.begin();
|
---|
182 | iter != rotated_polygon.end(); ++iter) {
|
---|
183 | *iter = rotation * (*iter);
|
---|
184 | _RotationAxis.rotateVector(*iter, _RotationAngle);
|
---|
185 | }
|
---|
186 |
|
---|
187 | return rotated_polygon;
|
---|
188 | }
|
---|
189 |
|
---|
190 | struct MatchingControlStructure {
|
---|
191 | bool foundflag;
|
---|
192 | double bestL2;
|
---|
193 | IndexList_t bestmatching;
|
---|
194 | VectorArray_t oldreturnpolygon;
|
---|
195 | VectorArray_t newreturnpolygon;
|
---|
196 | };
|
---|
197 |
|
---|
198 | /** Recursive function to go through all possible matchings.
|
---|
199 | *
|
---|
200 | * \param _MCS structure holding global information to the recursion
|
---|
201 | * \param _matching current matching being build up
|
---|
202 | * \param _indices contains still available indices
|
---|
203 | * \param _matchingsize
|
---|
204 | */
|
---|
205 | void recurseMatchings(
|
---|
206 | MatchingControlStructure &_MCS,
|
---|
207 | IndexList_t &_matching,
|
---|
208 | IndexList_t _indices,
|
---|
209 | unsigned int _matchingsize)
|
---|
210 | {
|
---|
211 | //!> threshold for L1 error below which matching is immediately acceptable
|
---|
212 | const double L1THRESHOLD = 1e-2;
|
---|
213 | if (!_MCS.foundflag) {
|
---|
214 | if (_matching.size() < _matchingsize) {
|
---|
215 | // go through all indices
|
---|
216 | for (IndexList_t::iterator iter = _indices.begin();
|
---|
217 | iter != _indices.end();) {
|
---|
218 | // add index to matching
|
---|
219 | _matching.push_back(*iter);
|
---|
220 | // remove index but keep iterator to position (is the next to erase element)
|
---|
221 | IndexList_t::iterator backupiter = _indices.erase(iter);
|
---|
222 | // recurse with decreased _matchingsize
|
---|
223 | recurseMatchings(_MCS, _matching, _indices, _matchingsize-1);
|
---|
224 | // re-add chosen index and reset index to new position
|
---|
225 | _indices.insert(backupiter, _matching.back());
|
---|
226 | iter = backupiter;
|
---|
227 | // remove index from _matching to make space for the next one
|
---|
228 | _matching.pop_back();
|
---|
229 | }
|
---|
230 | // gone through all indices then exit recursion
|
---|
231 | _MCS.foundflag = true;
|
---|
232 | } else {
|
---|
233 | // calculate errors
|
---|
234 | std::pair<double, double> errors = calculateErrorOfMatching(
|
---|
235 | _MCS.oldreturnpolygon, _MCS.newreturnpolygon, _matching);
|
---|
236 | if (errors.first < L1THRESHOLD) {
|
---|
237 | _MCS.bestmatching = _matching;
|
---|
238 | _MCS.foundflag = true;
|
---|
239 | }
|
---|
240 | if (_MCS.bestL2 > errors.second) {
|
---|
241 | _MCS.bestmatching = _matching;
|
---|
242 | _MCS.bestL2 = errors.second;
|
---|
243 | }
|
---|
244 | }
|
---|
245 | }
|
---|
246 | }
|
---|
247 |
|
---|
248 | SphericalPointDistribution::Polygon_t
|
---|
249 | SphericalPointDistribution::matchSphericalPointDistributions(
|
---|
250 | const SphericalPointDistribution::Polygon_t &_polygon,
|
---|
251 | const SphericalPointDistribution::Polygon_t &_newpolygon
|
---|
252 | )
|
---|
253 | {
|
---|
254 | SphericalPointDistribution::Polygon_t remainingreturnpolygon;
|
---|
255 | VectorArray_t remainingold(_polygon.begin(), _polygon.end());
|
---|
256 | VectorArray_t remainingnew(_newpolygon.begin(), _newpolygon.end());
|
---|
257 |
|
---|
258 | if (_polygon.size() > 0) {
|
---|
259 | MatchingControlStructure MCS;
|
---|
260 | MCS.foundflag = false;
|
---|
261 | MCS.bestL2 = std::numeric_limits<double>::max();
|
---|
262 | MCS.oldreturnpolygon.insert(MCS.oldreturnpolygon.begin(), _polygon.begin(),_polygon.end() );
|
---|
263 | MCS.newreturnpolygon.insert(MCS.newreturnpolygon.begin(), _newpolygon.begin(),_newpolygon.end() );
|
---|
264 |
|
---|
265 | // search for bestmatching combinatorially
|
---|
266 | {
|
---|
267 | // translate polygon into vector to enable index addressing
|
---|
268 | IndexList_t indices(_newpolygon.size());
|
---|
269 | std::generate(indices.begin(), indices.end(), UniqueNumber);
|
---|
270 | IndexList_t matching;
|
---|
271 |
|
---|
272 | // walk through all matchings
|
---|
273 | const unsigned int matchingsize = _polygon.size();
|
---|
274 | ASSERT( matchingsize <= indices.size(),
|
---|
275 | "SphericalPointDistribution::matchSphericalPointDistributions() - not enough new returnpolygon to choose for matching to old ones.");
|
---|
276 | recurseMatchings(MCS, matching, indices, matchingsize);
|
---|
277 | }
|
---|
278 |
|
---|
279 | // determine rotation angles to align the two point distributions with
|
---|
280 | // respect to bestmatching
|
---|
281 | std::vector<double> angles(3);
|
---|
282 | Vector newCenter;
|
---|
283 | {
|
---|
284 | // calculate center of triangle/line/point consisting of first returnpolygon of matching
|
---|
285 | Vector oldCenter;
|
---|
286 | IndexList_t::const_iterator iter = MCS.bestmatching.begin();
|
---|
287 | unsigned int i = 0;
|
---|
288 | for (; (i<3) && (i<MCS.bestmatching.size()); ++i, ++iter) {
|
---|
289 | oldCenter += remainingold[i];
|
---|
290 | newCenter += remainingnew[*iter];
|
---|
291 | }
|
---|
292 | oldCenter *= 1./(double)i;
|
---|
293 | newCenter *= 1./(double)i;
|
---|
294 |
|
---|
295 | Vector direction(0.,0.,0.);
|
---|
296 | for(size_t i=0;i<NDIM;++i) {
|
---|
297 | // create new rotation axis
|
---|
298 | direction[i] = 1.;
|
---|
299 | const Line axis (zeroVec, direction);
|
---|
300 | // calculate rotation angle for this axis
|
---|
301 | const double alpha = direction.Angle(oldCenter) - direction.Angle(newCenter);
|
---|
302 | // perform rotation
|
---|
303 | axis.rotateVector(newCenter, alpha);
|
---|
304 | // store angle
|
---|
305 | angles[i] = alpha;
|
---|
306 | // reset direction component for next iteration
|
---|
307 | direction[i] = 0.;
|
---|
308 | }
|
---|
309 | }
|
---|
310 | LOG(3, "INFO: (x,y,z) angles are" << angles);
|
---|
311 | const Line RotationAxis(zeroVec, newCenter);
|
---|
312 | const double RotationAngle =
|
---|
313 | newCenter.Angle(remainingold[0])
|
---|
314 | - newCenter.Angle(remainingnew[*MCS.bestmatching.begin()]);
|
---|
315 | LOG(3, "INFO: Rotate around self is " << RotationAngle
|
---|
316 | << " around axis " << RotationAxis);
|
---|
317 |
|
---|
318 | // rotate _newpolygon
|
---|
319 | SphericalPointDistribution::Polygon_t rotated_newpolygon =
|
---|
320 | rotatePolygon(_newpolygon, angles, RotationAxis, RotationAngle);
|
---|
321 | LOG(3, "INFO: Rotated new polygon is " << rotated_newpolygon);
|
---|
322 |
|
---|
323 | // remove all returnpolygon in matching and return remaining ones
|
---|
324 | return removeMatchingPoints(rotated_newpolygon, MCS.bestmatching);
|
---|
325 | } else
|
---|
326 | return _newpolygon;
|
---|
327 | }
|
---|