Ignore:
Timestamp:
Sep 12, 2016, 11:48:37 PM (9 years ago)
Author:
Frederik Heber <heber@…>
Branches:
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
Children:
6393ff
Parents:
0983e6
git-author:
Frederik Heber <heber@…> (07/09/14 22:08:37)
git-committer:
Frederik Heber <heber@…> (09/12/16 23:48:37)
Message:

Added calculation of center of minimum distance by bisection.

  • this will give us a unique a definite point independent of the (rotational) position of the point set on the unit sphere.
  • added unit test.
  • TESTFIX: Marked SphericalPointDistributionUnitTest as XFAIL.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/Fragmentation/Exporters/SphericalPointDistribution.cpp

    r0983e6 r3678eb  
    4343
    4444#include <algorithm>
    45 #include <boost/math/quaternion.hpp>
     45#include <boost/assign.hpp>
    4646#include <cmath>
    4747#include <functional>
     
    5858#include "LinearAlgebra/Vector.hpp"
    5959
     60using namespace boost::assign;
     61
    6062// static entities
    6163const double SphericalPointDistribution::SQRT_3(sqrt(3.0));
     
    8486 */
    8587inline
    86 Vector calculateCenter(
     88Vector calculateGeographicMidpoint(
    8789    const SphericalPointDistribution::VectorArray_t &_positions,
    8890    const SphericalPointDistribution::IndexList_t &_indices)
     
    9799
    98100  return Center;
     101}
     102
     103inline
     104double calculateMinimumDistance(
     105    const Vector &_center,
     106    const SphericalPointDistribution::VectorArray_t &_points,
     107    const SphericalPointDistribution::IndexList_t & _indices)
     108{
     109  double MinimumDistance = 0.;
     110  for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
     111      iter != _indices.end(); ++iter) {
     112    const double angle = _center.Angle(_points[*iter]);
     113    MinimumDistance += angle*angle;
     114  }
     115  return sqrt(MinimumDistance);
     116}
     117
     118/** Calculates the center of minimum distance for a given set of points \a _points.
     119 *
     120 * According to http://www.geomidpoint.com/calculation.html this goes a follows:
     121 * -# Let CurrentPoint be the geographic midpoint found in Method A. this is used as the starting point for the search.
     122 * -# Let MinimumDistance be the sum total of all distances from the current point to all locations in 'Your Places'.
     123 * -# Find the total distance between each location in 'Your Places' and all other locations in 'Your Places'. If any one of these locations has a new smallest distance then that location becomes the new CurrentPoint and MinimumDistance.
     124 * -# Let TestDistance be PI/2 radians (6225 miles or 10018 km).
     125 * -# Find the total distance between each of 8 test points and all locations in 'Your Places'. The test points are arranged in a circular pattern around the CurrentPoint at a distance of TestDistance to the north, northeast, east, southeast, south, southwest, west and northwest.
     126 * -# If any of these 8 points has a new smallest distance then that point becomes the new CurrentPoint and MinimumDistance and go back to step 5 using that point.
     127 * -# If none of the 8 test points has a new smallest distance then divide TestDistance by 2 and go back to step 5 using the same point.
     128 * -# Repeat steps 5 to 7 until no new smallest distance can be found or until TestDistance is less than 0.00000002 radians.
     129 *
     130 * \param _points set of points
     131 * \return Center of minimum distance for all these points, is always of length 1
     132 */
     133Vector SphericalPointDistribution::calculateCenterOfMinimumDistance(
     134    const SphericalPointDistribution::VectorArray_t &_positions,
     135    const SphericalPointDistribution::IndexList_t &_indices)
     136{
     137  ASSERT( _positions.size() >= _indices.size(),
     138      "calculateCenterOfMinimumDistance() - less positions than indices given.");
     139  Vector center(1.,0.,0.);
     140
     141  /// first treat some special cases
     142  // no positions given: return x axis vector (NOT zero!)
     143  {
     144    if (_indices.empty())
     145      return center;
     146    // one position given: return it directly
     147    if (_positions.size() == (size_t)1)
     148      return _positions[0];
     149    // two positions on a line given: return closest point to (1.,0.,0.)
     150    if (fabs(_positions[0].ScalarProduct(_positions[1]) + 1.)
     151        < std::numeric_limits<double>::epsilon()*1e4) {
     152      Vector candidate;
     153      if (_positions[0].ScalarProduct(center) > _positions[1].ScalarProduct(center))
     154        candidate = _positions[0];
     155      else
     156        candidate = _positions[1];
     157      // non-uniqueness: all positions on great circle, normal to given line are valid
     158      // so, we just pick one because returning a unique point is topmost priority
     159      Vector normal;
     160      normal.GetOneNormalVector(candidate);
     161      Vector othernormal = candidate;
     162      othernormal.VectorProduct(normal);
     163      // now both normal and othernormal describe the plane containing the great circle
     164      Plane greatcircle(normal, zeroVec, othernormal);
     165      // check which axis is contained and pick the one not
     166      if (greatcircle.isContained(center)) {
     167        center = Vector(0.,1.,0.);
     168        if (greatcircle.isContained(center))
     169          center = Vector(0.,0.,1.);
     170        // now we are done cause a plane cannot contain all three axis vectors
     171      }
     172      center = greatcircle.getClosestPoint(candidate);
     173      // assure length of 1
     174      center.Normalize();
     175    }
     176  }
     177
     178  // start with geographic midpoint
     179  center = calculateGeographicMidpoint(_positions, _indices);
     180  if (!center.IsZero()) {
     181    center.Normalize();
     182    LOG(4, "DEBUG: Starting with geographical midpoint of " << _positions << " under indices "
     183        << _indices << " is " << center);
     184  } else {
     185    // any point is good actually
     186    center = _positions[0];
     187    LOG(4, "DEBUG: Starting with first position " << center);
     188  }
     189
     190  // calculate initial MinimumDistance
     191  double MinimumDistance = calculateMinimumDistance(center, _positions, _indices);
     192  LOG(5, "DEBUG: MinimumDistance to this center is " << MinimumDistance);
     193
     194  // check all present points whether they may serve as a better center
     195  for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
     196      iter != _indices.end(); ++iter) {
     197    const Vector &centerCandidate = _positions[*iter];
     198    const double candidateDistance = calculateMinimumDistance(centerCandidate, _positions, _indices);
     199    if (candidateDistance < MinimumDistance) {
     200      MinimumDistance = candidateDistance;
     201      center = centerCandidate;
     202      LOG(5, "DEBUG: new MinimumDistance to current test point " << MinimumDistance
     203          << " is " << center);
     204    }
     205  }
     206  LOG(5, "DEBUG: new MinimumDistance to center " << center << " is " << MinimumDistance);
     207
     208  // now iterate over TestDistance
     209  double TestDistance = Vector(1.,0.,0.).Angle(Vector(0.,1.,0.));
     210//  LOG(6, "DEBUG: initial TestDistance is " << TestDistance);
     211
     212  const double threshold = sqrt(std::numeric_limits<double>::epsilon());
     213  // check each of eight test points at N, NE, E, SE, S, SW, W, NW
     214  typedef std::vector<double> angles_t;
     215  angles_t testangles;
     216  testangles += 0./180.*M_PI, 45./180.*M_PI, 90./180.*M_PI, 135./180.*M_PI,
     217      180./180.*M_PI, 225./180.*M_PI, 270./180.*M_PI, 315./180.*M_PI;
     218  while (TestDistance > threshold) {
     219    Vector OneNormal;
     220    OneNormal.GetOneNormalVector(center);
     221    Line RotationAxis(zeroVec, OneNormal);
     222    Vector North = RotationAxis.rotateVector(center,TestDistance);
     223    Line CompassRose(zeroVec, center);
     224    bool updatedflag = false;
     225    for (angles_t::const_iterator angleiter = testangles.begin();
     226        angleiter != testangles.end(); ++angleiter) {
     227      Vector centerCandidate = CompassRose.rotateVector(North, *angleiter);
     228//      centerCandidate.Normalize();
     229      const double candidateDistance = calculateMinimumDistance(centerCandidate, _positions, _indices);
     230      if (candidateDistance < MinimumDistance) {
     231        MinimumDistance = candidateDistance;
     232        center = centerCandidate;
     233        updatedflag = true;
     234        LOG(5, "DEBUG: new MinimumDistance to test point at " << *angleiter/M_PI*180.
     235            << "° is " << MinimumDistance);
     236      }
     237    }
     238
     239    // if no new point, decrease TestDistance
     240    if (!updatedflag) {
     241      TestDistance *= 0.5;
     242//      LOG(6, "DEBUG: TestDistance is now " << TestDistance);
     243    }
     244  }
     245  LOG(4, "DEBUG: Final MinimumDistance to center " << center << " is " << MinimumDistance);
     246
     247  return center;
     248}
     249
     250Vector calculateCenterOfMinimumDistance(
     251    const SphericalPointDistribution::PolygonWithIndices &_points)
     252{
     253  return SphericalPointDistribution::calculateCenterOfMinimumDistance(_points.polygon, _points.indices);
     254}
     255
     256/** Calculate the center of a given set of points in \a _positions but only
     257 * for those indicated by \a _indices.
     258 *
     259 */
     260inline
     261Vector calculateCenter(
     262    const SphericalPointDistribution::VectorArray_t &_positions,
     263    const SphericalPointDistribution::IndexList_t &_indices)
     264{
     265//  Vector Center;
     266//  Center.Zero();
     267//  for (SphericalPointDistribution::IndexList_t::const_iterator iter = _indices.begin();
     268//      iter != _indices.end(); ++iter)
     269//    Center += _positions[*iter];
     270//  if (!_indices.empty())
     271//    Center *= 1./(double)_indices.size();
     272//
     273//  return Center;
     274  return SphericalPointDistribution::calculateCenterOfMinimumDistance(_positions, _indices);
    99275}
    100276
     
    749925            oldCenter, rotatednewCenter,
    750926            oldSet, rotatednewSet);
    751         // NOTE: Center must not necessarily lie on the sphere with norm 1, hence, we
    752         // have to normalize it just as before, as oldCenter and newCenter lengths may differ.
    753         if ((!oldCenter.IsZero()) && (!rotatednewCenter.IsZero())) {
    754           oldCenter.Normalize();
    755           rotatednewCenter.Normalize();
    756           LOG(4, "CHECK: rotatednewCenter is " << rotatednewCenter
    757               << ", oldCenter is " << oldCenter);
    758           const double difference = (rotatednewCenter - oldCenter).NormSquared();
    759           ASSERT( difference < std::numeric_limits<double>::epsilon()*1e4,
    760               "matchSphericalPointDistributions() - rotation does not work as expected by "
    761               +toString(difference)+".");
    762         }
     927        oldCenter.Normalize();
     928        rotatednewCenter.Normalize();
     929        // check whether centers are anti-parallel (factor -1)
     930        // then we have the "non-unique poles" situation: points lie on great circle
     931        // and both poles are valid solution
     932        if (fabs(oldCenter.ScalarProduct(rotatednewCenter) + 1.)
     933            < std::numeric_limits<double>::epsilon()*1e4)
     934          rotatednewCenter *= -1.;
     935        LOG(4, "CHECK: rotatednewCenter is " << rotatednewCenter
     936            << ", oldCenter is " << oldCenter);
     937        const double difference = (rotatednewCenter - oldCenter).NormSquared();
     938        ASSERT( difference < std::numeric_limits<double>::epsilon()*1e4,
     939            "matchSphericalPointDistributions() - rotation does not work as expected by "
     940            +toString(difference)+".");
    763941      }
    764942#endif
Note: See TracChangeset for help on using the changeset viewer.