[f54930] | 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"
|
---|
[64cafb2] | 40 | #include "CodePatterns/IteratorAdaptors.hpp"
|
---|
[0c42f2] | 41 | #include "CodePatterns/Log.hpp"
|
---|
[64cafb2] | 42 | #include "CodePatterns/toString.hpp"
|
---|
[f54930] | 43 |
|
---|
| 44 | #include <algorithm>
|
---|
[f9d85f] | 45 | #include <boost/math/quaternion.hpp>
|
---|
[64cafb2] | 46 | #include <cmath>
|
---|
[946948] | 47 | #include <functional>
|
---|
| 48 | #include <iterator>
|
---|
[64cafb2] | 49 | #include <limits>
|
---|
| 50 | #include <list>
|
---|
[f54930] | 51 | #include <vector>
|
---|
[64cafb2] | 52 | #include <map>
|
---|
[f54930] | 53 |
|
---|
| 54 | #include "LinearAlgebra/Line.hpp"
|
---|
| 55 | #include "LinearAlgebra/RealSpaceMatrix.hpp"
|
---|
| 56 | #include "LinearAlgebra/Vector.hpp"
|
---|
| 57 |
|
---|
[64cafb2] | 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 |
|
---|
[0c42f2] | 63 | // static instances
|
---|
| 64 | const double SphericalPointDistribution::SQRT_3(sqrt(3.0));
|
---|
| 65 |
|
---|
[64cafb2] | 66 | DistanceArray_t calculatePairwiseDistances(
|
---|
[0c42f2] | 67 | const std::vector<Vector> &_returnpolygon,
|
---|
[64cafb2] | 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;
|
---|
[0c42f2] | 78 | const double distance = (_returnpolygon[*firstiter] - _returnpolygon[*seconditer]).NormSquared();
|
---|
[64cafb2] | 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;}
|
---|
[946948] | 89 | int operator()() {return current++;}
|
---|
[64cafb2] | 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 | *
|
---|
[0c42f2] | 98 | * \param _old first set of returnpolygon (fewer or equal to \a _new)
|
---|
| 99 | * \param _new second set of returnpolygon
|
---|
[64cafb2] | 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) {
|
---|
[7e81ca] | 111 | LOG(3, "INFO: Matching is " << _Matching);
|
---|
[64cafb2] | 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 | }
|
---|
[7e81ca] | 132 | } else
|
---|
[946948] | 133 | ELOG(3, "calculateErrorOfMatching() - Given matching's size is less than 2.");
|
---|
[7e81ca] | 134 | LOG(3, "INFO: Resulting errors for matching (L1, L2): "
|
---|
| 135 | << errors.first << "," << errors.second << ".");
|
---|
[64cafb2] | 136 |
|
---|
| 137 | return errors;
|
---|
| 138 | }
|
---|
| 139 |
|
---|
| 140 | SphericalPointDistribution::Polygon_t removeMatchingPoints(
|
---|
[0c42f2] | 141 | const SphericalPointDistribution::Polygon_t &_returnpolygon,
|
---|
[64cafb2] | 142 | const IndexList_t &_matchingindices
|
---|
| 143 | )
|
---|
| 144 | {
|
---|
[0c42f2] | 145 | SphericalPointDistribution::Polygon_t remainingreturnpolygon;
|
---|
[64cafb2] | 146 | IndexArray_t indices(_matchingindices.begin(), _matchingindices.end());
|
---|
| 147 | std::sort(indices.begin(), indices.end());
|
---|
[7e81ca] | 148 | LOG(4, "DEBUG: sorted matching is " << indices);
|
---|
[64cafb2] | 149 | IndexArray_t::const_iterator valueiter = indices.begin();
|
---|
| 150 | SphericalPointDistribution::Polygon_t::const_iterator pointiter =
|
---|
[0c42f2] | 151 | _returnpolygon.begin();
|
---|
| 152 | for (unsigned int i=0; i< _returnpolygon.size(); ++i, ++pointiter) {
|
---|
[64cafb2] | 153 | // skip all those in values
|
---|
| 154 | if (*valueiter == i)
|
---|
| 155 | ++valueiter;
|
---|
| 156 | else
|
---|
[0c42f2] | 157 | remainingreturnpolygon.push_back(*pointiter);
|
---|
[64cafb2] | 158 | }
|
---|
[7e81ca] | 159 | LOG(4, "DEBUG: remaining indices are " << remainingreturnpolygon);
|
---|
[64cafb2] | 160 |
|
---|
[0c42f2] | 161 | return remainingreturnpolygon;
|
---|
[64cafb2] | 162 | }
|
---|
| 163 |
|
---|
| 164 | struct MatchingControlStructure {
|
---|
| 165 | bool foundflag;
|
---|
| 166 | double bestL2;
|
---|
| 167 | IndexList_t bestmatching;
|
---|
[0c42f2] | 168 | VectorArray_t oldreturnpolygon;
|
---|
| 169 | VectorArray_t newreturnpolygon;
|
---|
[64cafb2] | 170 | };
|
---|
| 171 |
|
---|
| 172 | /** Recursive function to go through all possible matchings.
|
---|
| 173 | *
|
---|
| 174 | * \param _MCS structure holding global information to the recursion
|
---|
| 175 | * \param _matching current matching being build up
|
---|
| 176 | * \param _indices contains still available indices
|
---|
| 177 | * \param _matchingsize
|
---|
| 178 | */
|
---|
| 179 | void recurseMatchings(
|
---|
| 180 | MatchingControlStructure &_MCS,
|
---|
| 181 | IndexList_t &_matching,
|
---|
| 182 | IndexList_t _indices,
|
---|
| 183 | unsigned int _matchingsize)
|
---|
[f54930] | 184 | {
|
---|
[7e81ca] | 185 | LOG(4, "DEBUG: Recursing with current matching " << _matching
|
---|
| 186 | << ", remaining indices " << _indices
|
---|
[946948] | 187 | << ", and sought size " << _matching.size()+_matchingsize);
|
---|
[64cafb2] | 188 | //!> threshold for L1 error below which matching is immediately acceptable
|
---|
| 189 | const double L1THRESHOLD = 1e-2;
|
---|
| 190 | if (!_MCS.foundflag) {
|
---|
[946948] | 191 | LOG(4, "DEBUG: Current matching has size " << _matching.size() << ", places left " << _matchingsize);
|
---|
| 192 | if (_matchingsize > 0) {
|
---|
[64cafb2] | 193 | // go through all indices
|
---|
| 194 | for (IndexList_t::iterator iter = _indices.begin();
|
---|
[946948] | 195 | (iter != _indices.end()) && (!_MCS.foundflag);) {
|
---|
[64cafb2] | 196 | // add index to matching
|
---|
| 197 | _matching.push_back(*iter);
|
---|
[946948] | 198 | LOG(5, "DEBUG: Adding " << *iter << " to matching.");
|
---|
[64cafb2] | 199 | // remove index but keep iterator to position (is the next to erase element)
|
---|
| 200 | IndexList_t::iterator backupiter = _indices.erase(iter);
|
---|
| 201 | // recurse with decreased _matchingsize
|
---|
| 202 | recurseMatchings(_MCS, _matching, _indices, _matchingsize-1);
|
---|
| 203 | // re-add chosen index and reset index to new position
|
---|
| 204 | _indices.insert(backupiter, _matching.back());
|
---|
| 205 | iter = backupiter;
|
---|
| 206 | // remove index from _matching to make space for the next one
|
---|
| 207 | _matching.pop_back();
|
---|
| 208 | }
|
---|
| 209 | // gone through all indices then exit recursion
|
---|
[946948] | 210 | if (_matching.empty())
|
---|
| 211 | _MCS.foundflag = true;
|
---|
[64cafb2] | 212 | } else {
|
---|
[7e81ca] | 213 | LOG(3, "INFO: Found matching " << _matching);
|
---|
[64cafb2] | 214 | // calculate errors
|
---|
| 215 | std::pair<double, double> errors = calculateErrorOfMatching(
|
---|
[0c42f2] | 216 | _MCS.oldreturnpolygon, _MCS.newreturnpolygon, _matching);
|
---|
[64cafb2] | 217 | if (errors.first < L1THRESHOLD) {
|
---|
| 218 | _MCS.bestmatching = _matching;
|
---|
| 219 | _MCS.foundflag = true;
|
---|
[946948] | 220 | } else if (_MCS.bestL2 > errors.second) {
|
---|
[64cafb2] | 221 | _MCS.bestmatching = _matching;
|
---|
| 222 | _MCS.bestL2 = errors.second;
|
---|
| 223 | }
|
---|
| 224 | }
|
---|
[f54930] | 225 | }
|
---|
| 226 | }
|
---|
| 227 |
|
---|
[946948] | 228 | /** Rotates a given polygon around x, y, and z axis by the given angles.
|
---|
| 229 | *
|
---|
| 230 | * \param _polygon polygon whose points to rotate
|
---|
[f9d85f] | 231 | * \param _q quaternion specifying the rotation of the coordinate system
|
---|
[946948] | 232 | */
|
---|
| 233 | SphericalPointDistribution::Polygon_t rotatePolygon(
|
---|
| 234 | const SphericalPointDistribution::Polygon_t &_polygon,
|
---|
[f9d85f] | 235 | const boost::math::quaternion<double> &_q)
|
---|
[946948] | 236 | {
|
---|
| 237 | SphericalPointDistribution::Polygon_t rotated_polygon = _polygon;
|
---|
[f9d85f] | 238 | boost::math::quaternion<double> q_inverse =
|
---|
| 239 | boost::math::conj(_q)/(boost::math::norm(_q));
|
---|
[946948] | 240 |
|
---|
| 241 | // apply rotation angles
|
---|
| 242 | for (SphericalPointDistribution::Polygon_t::iterator iter = rotated_polygon.begin();
|
---|
| 243 | iter != rotated_polygon.end(); ++iter) {
|
---|
[f9d85f] | 244 | Vector ¤t = *iter;
|
---|
| 245 | boost::math::quaternion<double> p(0, current[0], current[1], current[2]);
|
---|
| 246 | p = _q * p * q_inverse;
|
---|
| 247 | LOG(5, "DEBUG: Rotated point is " << p);
|
---|
| 248 | // i have no idea why but first component comes up with wrong sign
|
---|
| 249 | current[0] = -p.R_component_2();
|
---|
| 250 | current[1] = p.R_component_3();
|
---|
| 251 | current[2] = p.R_component_4();
|
---|
[946948] | 252 | }
|
---|
| 253 |
|
---|
| 254 | return rotated_polygon;
|
---|
| 255 | }
|
---|
| 256 |
|
---|
| 257 |
|
---|
[64cafb2] | 258 | SphericalPointDistribution::Polygon_t
|
---|
| 259 | SphericalPointDistribution::matchSphericalPointDistributions(
|
---|
| 260 | const SphericalPointDistribution::Polygon_t &_polygon,
|
---|
| 261 | const SphericalPointDistribution::Polygon_t &_newpolygon
|
---|
| 262 | )
|
---|
| 263 | {
|
---|
[0c42f2] | 264 | SphericalPointDistribution::Polygon_t remainingreturnpolygon;
|
---|
[64cafb2] | 265 | VectorArray_t remainingold(_polygon.begin(), _polygon.end());
|
---|
| 266 | VectorArray_t remainingnew(_newpolygon.begin(), _newpolygon.end());
|
---|
[946948] | 267 | LOG(2, "INFO: Matching old polygon " << _polygon
|
---|
[7e81ca] | 268 | << " with new polygon " << _newpolygon);
|
---|
[64cafb2] | 269 |
|
---|
| 270 | if (_polygon.size() > 0) {
|
---|
| 271 | MatchingControlStructure MCS;
|
---|
| 272 | MCS.foundflag = false;
|
---|
| 273 | MCS.bestL2 = std::numeric_limits<double>::max();
|
---|
[0c42f2] | 274 | MCS.oldreturnpolygon.insert(MCS.oldreturnpolygon.begin(), _polygon.begin(),_polygon.end() );
|
---|
| 275 | MCS.newreturnpolygon.insert(MCS.newreturnpolygon.begin(), _newpolygon.begin(),_newpolygon.end() );
|
---|
[64cafb2] | 276 |
|
---|
| 277 | // search for bestmatching combinatorially
|
---|
| 278 | {
|
---|
| 279 | // translate polygon into vector to enable index addressing
|
---|
| 280 | IndexList_t indices(_newpolygon.size());
|
---|
| 281 | std::generate(indices.begin(), indices.end(), UniqueNumber);
|
---|
| 282 | IndexList_t matching;
|
---|
| 283 |
|
---|
| 284 | // walk through all matchings
|
---|
| 285 | const unsigned int matchingsize = _polygon.size();
|
---|
| 286 | ASSERT( matchingsize <= indices.size(),
|
---|
[0c42f2] | 287 | "SphericalPointDistribution::matchSphericalPointDistributions() - not enough new returnpolygon to choose for matching to old ones.");
|
---|
[64cafb2] | 288 | recurseMatchings(MCS, matching, indices, matchingsize);
|
---|
| 289 | }
|
---|
[946948] | 290 | LOG(2, "INFO: Best matching is " << MCS.bestmatching);
|
---|
[64cafb2] | 291 |
|
---|
| 292 | // determine rotation angles to align the two point distributions with
|
---|
| 293 | // respect to bestmatching
|
---|
[f9d85f] | 294 | SphericalPointDistribution::Polygon_t rotated_newpolygon;
|
---|
[946948] | 295 | Vector oldCenter;
|
---|
[64cafb2] | 296 | {
|
---|
[946948] | 297 | // calculate center of triangle/line/point consisting of first points of matching
|
---|
[f9d85f] | 298 | Vector newCenter;
|
---|
[64cafb2] | 299 | IndexList_t::const_iterator iter = MCS.bestmatching.begin();
|
---|
| 300 | unsigned int i = 0;
|
---|
| 301 | for (; (i<3) && (i<MCS.bestmatching.size()); ++i, ++iter) {
|
---|
| 302 | oldCenter += remainingold[i];
|
---|
| 303 | newCenter += remainingnew[*iter];
|
---|
| 304 | }
|
---|
| 305 | oldCenter *= 1./(double)i;
|
---|
| 306 | newCenter *= 1./(double)i;
|
---|
[946948] | 307 | LOG(4, "DEBUG: oldCenter is " << oldCenter << ", newCenter is " << newCenter);
|
---|
| 308 |
|
---|
[f9d85f] | 309 | if ((oldCenter - newCenter).NormSquared() > std::numeric_limits<double>::epsilon()*1e4) {
|
---|
| 310 | // setup quaternion
|
---|
| 311 | Vector RotationAxis = newCenter;
|
---|
| 312 | RotationAxis.VectorProduct(oldCenter);
|
---|
| 313 | RotationAxis.Normalize();
|
---|
| 314 | const double RotationAngle = oldCenter.Angle(newCenter)/(M_PI/2.);
|
---|
| 315 | // RotationAxis.Angle(oldCenter) - RotationAxis.Angle(newCenter);
|
---|
| 316 | boost::math::quaternion<double> q
|
---|
| 317 | (RotationAngle, RotationAxis[0], RotationAxis[1], RotationAxis[2]);
|
---|
| 318 | LOG(5, "DEBUG: RotationAxis is " << RotationAxis
|
---|
| 319 | << ", RotationAngle is " << RotationAngle);
|
---|
| 320 | LOG(5, "DEBUG: Quaternion describing rotation is " << q);
|
---|
| 321 | #ifndef NDEBUG
|
---|
| 322 | {
|
---|
| 323 | // check that rotation works in DEBUG mode
|
---|
| 324 | boost::math::quaternion<double> p(0., newCenter[0], newCenter[1], newCenter[2]);
|
---|
| 325 | boost::math::quaternion<double> q_inverse =
|
---|
| 326 | boost::math::conj(q)/(boost::math::norm(q));
|
---|
| 327 | p = q * p * q_inverse;
|
---|
| 328 | boost::math::quaternion<double> identity(1,0,0,0);
|
---|
| 329 | ASSERT( boost::math::norm(q*q_inverse - identity) < std::numeric_limits<double>::epsilon()*1e4,
|
---|
| 330 | "matchSphericalPointDistributions() - quaternion does not rotate newCenter "
|
---|
| 331 | +toString(q*q_inverse)+" into oldCenter "+toString(identity)+".");
|
---|
| 332 | boost::math::quaternion<double> comparison(0., -oldCenter[0], oldCenter[1], oldCenter[2]);
|
---|
| 333 | ASSERT( boost::math::norm(p - comparison) < std::numeric_limits<double>::epsilon()*1e4,
|
---|
| 334 | "matchSphericalPointDistributions() - quaternion does not rotate newCenter "
|
---|
| 335 | +toString(p)+" into oldCenter "+toString(comparison)+".");
|
---|
| 336 | }
|
---|
| 337 | #endif
|
---|
[946948] | 338 |
|
---|
[f9d85f] | 339 | // rotate spherical distribution
|
---|
| 340 | rotated_newpolygon = rotatePolygon(_newpolygon, q);
|
---|
| 341 | LOG(5, "DEBUG: Rotated new polygon is " << rotated_newpolygon);
|
---|
| 342 | } else {
|
---|
| 343 | rotated_newpolygon = _newpolygon;
|
---|
| 344 | }
|
---|
| 345 | }
|
---|
| 346 | // rotate triangle/line/point around itself to match orientation
|
---|
[946948] | 347 | const Line RotationAxis(zeroVec, oldCenter);
|
---|
[64cafb2] | 348 | const double RotationAngle =
|
---|
[946948] | 349 | oldCenter.Angle(remainingold[0])
|
---|
| 350 | - oldCenter.Angle(remainingnew[*MCS.bestmatching.begin()]);
|
---|
| 351 | LOG(5, "DEBUG: Rotate around self is " << RotationAngle
|
---|
[6cb1cd] | 352 | << " around axis " << RotationAxis);
|
---|
[64cafb2] | 353 |
|
---|
[946948] | 354 | for (SphericalPointDistribution::Polygon_t::iterator iter = rotated_newpolygon.begin();
|
---|
| 355 | iter != rotated_newpolygon.end(); ++iter) {
|
---|
| 356 | RotationAxis.rotateVector(*iter, RotationAngle);
|
---|
| 357 | }
|
---|
[64cafb2] | 358 |
|
---|
[946948] | 359 | // remove all points in matching and return remaining ones
|
---|
| 360 | SphericalPointDistribution::Polygon_t remainingpoints =
|
---|
| 361 | removeMatchingPoints(rotated_newpolygon, MCS.bestmatching);
|
---|
| 362 | LOG(2, "INFO: Remaining points are " << remainingpoints);
|
---|
| 363 | return remainingpoints;
|
---|
[64cafb2] | 364 | } else
|
---|
| 365 | return _newpolygon;
|
---|
| 366 | }
|
---|