source: src/Fragmentation/Exporters/SphericalPointDistribution.cpp@ 6cb1cd

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 6cb1cd was 6cb1cd, checked in by Frederik Heber <heber@…>, 8 years ago

Removing SphericalPointDistribution::getSimplePolygon() to allow for easy rebasing of very old branch on top.

  • Property mode set to 100644
File size: 11.3 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
60// static instances
61const double SphericalPointDistribution::SQRT_3(sqrt(3.0));
62
63DistanceArray_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
83struct 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 */
100std::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
134SphericalPointDistribution::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 */
168SphericalPointDistribution::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
190struct 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 */
205void 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
248SphericalPointDistribution::Polygon_t
249SphericalPointDistribution::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}
Note: See TracBrowser for help on using the repository browser.