source: src/Fragmentation/Exporters/SphericalPointDistribution.cpp@ f9d85f

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since f9d85f was f9d85f, checked in by Frederik Heber <heber@…>, 8 years ago

Implemented rotations via boost::quaternions.

  • Property mode set to 100644
File size: 13.6 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
63// static instances
64const double SphericalPointDistribution::SQRT_3(sqrt(3.0));
65
66DistanceArray_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
86struct 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 */
103std::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
140SphericalPointDistribution::Polygon_t removeMatchingPoints(
141 const SphericalPointDistribution::Polygon_t &_returnpolygon,
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::const_iterator valueiter = indices.begin();
150 SphericalPointDistribution::Polygon_t::const_iterator pointiter =
151 _returnpolygon.begin();
152 for (unsigned int i=0; i< _returnpolygon.size(); ++i, ++pointiter) {
153 // skip all those in values
154 if (*valueiter == i)
155 ++valueiter;
156 else
157 remainingreturnpolygon.push_back(*pointiter);
158 }
159 LOG(4, "DEBUG: remaining indices are " << remainingreturnpolygon);
160
161 return remainingreturnpolygon;
162}
163
164struct MatchingControlStructure {
165 bool foundflag;
166 double bestL2;
167 IndexList_t bestmatching;
168 VectorArray_t oldreturnpolygon;
169 VectorArray_t newreturnpolygon;
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 */
179void recurseMatchings(
180 MatchingControlStructure &_MCS,
181 IndexList_t &_matching,
182 IndexList_t _indices,
183 unsigned int _matchingsize)
184{
185 LOG(4, "DEBUG: Recursing with current matching " << _matching
186 << ", remaining indices " << _indices
187 << ", and sought size " << _matching.size()+_matchingsize);
188 //!> threshold for L1 error below which matching is immediately acceptable
189 const double L1THRESHOLD = 1e-2;
190 if (!_MCS.foundflag) {
191 LOG(4, "DEBUG: Current matching has size " << _matching.size() << ", places left " << _matchingsize);
192 if (_matchingsize > 0) {
193 // go through all indices
194 for (IndexList_t::iterator iter = _indices.begin();
195 (iter != _indices.end()) && (!_MCS.foundflag);) {
196 // add index to matching
197 _matching.push_back(*iter);
198 LOG(5, "DEBUG: Adding " << *iter << " to matching.");
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
210 if (_matching.empty())
211 _MCS.foundflag = true;
212 } else {
213 LOG(3, "INFO: Found matching " << _matching);
214 // calculate errors
215 std::pair<double, double> errors = calculateErrorOfMatching(
216 _MCS.oldreturnpolygon, _MCS.newreturnpolygon, _matching);
217 if (errors.first < L1THRESHOLD) {
218 _MCS.bestmatching = _matching;
219 _MCS.foundflag = true;
220 } else if (_MCS.bestL2 > errors.second) {
221 _MCS.bestmatching = _matching;
222 _MCS.bestL2 = errors.second;
223 }
224 }
225 }
226}
227
228/** Rotates a given polygon around x, y, and z axis by the given angles.
229 *
230 * \param _polygon polygon whose points to rotate
231 * \param _q quaternion specifying the rotation of the coordinate system
232 */
233SphericalPointDistribution::Polygon_t rotatePolygon(
234 const SphericalPointDistribution::Polygon_t &_polygon,
235 const boost::math::quaternion<double> &_q)
236{
237 SphericalPointDistribution::Polygon_t rotated_polygon = _polygon;
238 boost::math::quaternion<double> q_inverse =
239 boost::math::conj(_q)/(boost::math::norm(_q));
240
241 // apply rotation angles
242 for (SphericalPointDistribution::Polygon_t::iterator iter = rotated_polygon.begin();
243 iter != rotated_polygon.end(); ++iter) {
244 Vector &current = *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();
252 }
253
254 return rotated_polygon;
255}
256
257
258SphericalPointDistribution::Polygon_t
259SphericalPointDistribution::matchSphericalPointDistributions(
260 const SphericalPointDistribution::Polygon_t &_polygon,
261 const SphericalPointDistribution::Polygon_t &_newpolygon
262 )
263{
264 SphericalPointDistribution::Polygon_t remainingreturnpolygon;
265 VectorArray_t remainingold(_polygon.begin(), _polygon.end());
266 VectorArray_t remainingnew(_newpolygon.begin(), _newpolygon.end());
267 LOG(2, "INFO: Matching old polygon " << _polygon
268 << " with new polygon " << _newpolygon);
269
270 if (_polygon.size() > 0) {
271 MatchingControlStructure MCS;
272 MCS.foundflag = false;
273 MCS.bestL2 = std::numeric_limits<double>::max();
274 MCS.oldreturnpolygon.insert(MCS.oldreturnpolygon.begin(), _polygon.begin(),_polygon.end() );
275 MCS.newreturnpolygon.insert(MCS.newreturnpolygon.begin(), _newpolygon.begin(),_newpolygon.end() );
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(),
287 "SphericalPointDistribution::matchSphericalPointDistributions() - not enough new returnpolygon to choose for matching to old ones.");
288 recurseMatchings(MCS, matching, indices, matchingsize);
289 }
290 LOG(2, "INFO: Best matching is " << MCS.bestmatching);
291
292 // determine rotation angles to align the two point distributions with
293 // respect to bestmatching
294 SphericalPointDistribution::Polygon_t rotated_newpolygon;
295 Vector oldCenter;
296 {
297 // calculate center of triangle/line/point consisting of first points of matching
298 Vector newCenter;
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;
307 LOG(4, "DEBUG: oldCenter is " << oldCenter << ", newCenter is " << newCenter);
308
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
338
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
347 const Line RotationAxis(zeroVec, oldCenter);
348 const double RotationAngle =
349 oldCenter.Angle(remainingold[0])
350 - oldCenter.Angle(remainingnew[*MCS.bestmatching.begin()]);
351 LOG(5, "DEBUG: Rotate around self is " << RotationAngle
352 << " around axis " << RotationAxis);
353
354 for (SphericalPointDistribution::Polygon_t::iterator iter = rotated_newpolygon.begin();
355 iter != rotated_newpolygon.end(); ++iter) {
356 RotationAxis.rotateVector(*iter, RotationAngle);
357 }
358
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;
364 } else
365 return _newpolygon;
366}
Note: See TracBrowser for help on using the repository browser.