LSSTApplications  16.0-1-gce273f5+15,16.0-1-gf77f410+8,16.0-10-g230e10e+8,16.0-10-g5a5abec+4,16.0-10-gc1446dd+8,16.0-11-g5cf5345,16.0-12-g1dc09ba+2,16.0-12-g726f8f3+6,16.0-13-g4c33ca5+8,16.0-13-g5f6c0b1+8,16.0-13-gd9b1b71+8,16.0-14-g71e547a+4,16.0-17-g0bdc215,16.0-17-g6a7bfb3b+8,16.0-18-g95848a16+2,16.0-2-g0febb12+12,16.0-2-g839ba83+46,16.0-2-g9d5294e+35,16.0-3-g404ea43+7,16.0-3-gbc759ec+6,16.0-3-gcfd6c53+33,16.0-4-g03cf288+24,16.0-4-g13a27c5+10,16.0-4-g2cc461c+3,16.0-4-g5f3a788+11,16.0-4-g8a0f11a+30,16.0-4-ga3eb747+1,16.0-43-gaa65a4573+4,16.0-5-g1991253+8,16.0-5-g865efd9+8,16.0-5-gb3f8a4b+40,16.0-5-gd0f1235+4,16.0-6-g316b399+8,16.0-6-gf0acd13+27,16.0-6-gf9cb114+9,16.0-7-ga8e1655+4,16.0-8-g23bbf3f+1,16.0-8-g4dec96c+21,16.0-8-gfd407c0,w.2018.39
LSSTDataManagementBasePackage
SpherePoint.cc
Go to the documentation of this file.
1 /*
2  * Developed for the LSST Data Management System.
3  * This product includes software developed by the LSST Project
4  * (https://www.lsst.org).
5  * See the COPYRIGHT file at the top-level directory of this distribution
6  * for details of code ownership.
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program. If not, see <https://www.gnu.org/licenses/>.
20  */
21 
22 #include <cmath>
23 #include <string>
24 #include <sstream>
25 
26 #include "Eigen/Geometry"
27 
28 #include "lsst/geom/SpherePoint.h"
29 #include "lsst/geom/sphgeomUtils.h"
30 #include "lsst/pex/exceptions.h"
31 
33 using namespace std;
34 
35 namespace lsst {
36 
37 namespace geom {
39 namespace {
53 Angle haversine(Angle const& deltaLon, Angle const& deltaLat, double cosLat1, double cosLat2) {
54  double const sinLat = sin(deltaLat / 2.0);
55  double const sinLon = sin(deltaLon / 2.0);
56  double const havDDelta = sinLat * sinLat;
57  double const havDAlpha = sinLon * sinLon;
58  double const havD = havDDelta + cosLat1 * cosLat2 * havDAlpha;
59  double const sinDHalf = sqrt(havD);
60  return (2.0 * asin(sinDHalf)) * radians;
61 }
62 } // end namespace
63 
65  : SpherePoint(longitude * units, latitude * units) {}
66 
68  : _longitude(longitude.wrap().asRadians()), _latitude(latitude.asRadians()) {
69  if (fabs(_latitude) > HALFPI) {
70  throw pexExcept::InvalidParameterError("Angle " + to_string(latitude.asDegrees()) +
71  " is not a valid latitude.");
72  }
73 }
74 
76  // sphgeom Vector3d has its own normalization,
77  // but its behavior is not documented for non-finite values
78  double norm = vector.getNorm();
79  if (norm <= 0.0) {
80  stringstream buffer;
81  buffer << "Vector " << vector << " has zero norm and cannot be normalized.";
82  throw pexExcept::InvalidParameterError(buffer.str());
83  }
84  // To avoid unexpected behavior from mixing finite elements and infinite norm
85  if (!isfinite(norm)) {
86  norm = NAN;
87  }
88  auto unitVector =
89  sphgeom::UnitVector3d::fromNormalized(vector.x() / norm, vector.y() / norm, vector.z() / norm);
90  _set(unitVector);
91 }
92 
94  : SpherePoint(lonLat.getLon().asRadians(), lonLat.getLat().asRadians(), radians) {}
95 
96 void SpherePoint::_set(sphgeom::UnitVector3d const& unitVector) {
97  _latitude = asin(unitVector.z());
98  if (!atPole()) {
99  // Need to convert to Angle, Angle::wrap, and convert back to radians
100  // to handle _longitude = -1e-16 without code duplication
101  _longitude = (atan2(unitVector.y(), unitVector.x()) * radians).wrap().asRadians();
102  } else {
103  _longitude = 0;
104  }
105 }
106 
107 SpherePoint::SpherePoint() noexcept : _longitude(nan("")), _latitude(nan("")) {}
108 
109 SpherePoint::SpherePoint(SpherePoint const& other) noexcept = default;
110 
111 SpherePoint::SpherePoint(SpherePoint&& other) noexcept = default;
112 
113 SpherePoint& SpherePoint::operator=(SpherePoint const& other) noexcept = default;
114 
115 SpherePoint& SpherePoint::operator=(SpherePoint&& other) noexcept = default;
116 
117 SpherePoint::operator sphgeom::LonLat() const noexcept {
118  return sphgeom::LonLat::fromRadians(getLongitude().asRadians(), getLatitude().asRadians());
119 }
120 
121 SpherePoint::~SpherePoint() noexcept = default;
122 
124  return sphgeom::UnitVector3d::fromNormalized(cos(_longitude) * cos(_latitude),
125  sin(_longitude) * cos(_latitude), sin(_latitude));
126 }
127 
129  return Point2D(getLongitude().asAngularUnits(unit), getLatitude().asAngularUnits(unit));
130 }
131 
132 Angle SpherePoint::operator[](size_t index) const {
133  switch (index) {
134  case 0:
135  return getLongitude();
136  case 1:
137  return getLatitude();
138  default:
139  throw pexExcept::OutOfRangeError("Index " + to_string(index) + " must be 0 or 1.");
140  }
141 }
142 
143 bool SpherePoint::isFinite() const noexcept { return isfinite(_longitude) && isfinite(_latitude); }
144 
145 bool SpherePoint::operator==(SpherePoint const& other) const noexcept {
146  // Deliberate override of Style Guide 5-12
147  // Approximate FP comparison would make object equality intransitive
148  return _longitude == other._longitude && _latitude == other._latitude;
149 }
150 
151 bool SpherePoint::operator!=(SpherePoint const& other) const noexcept { return !(*this == other); }
152 
154  Angle const deltaLon = other.getLongitude() - this->getLongitude();
155 
156  double const sinDelta1 = sin(getLatitude().asRadians());
157  double const sinDelta2 = sin(other.getLatitude().asRadians());
158  double const cosDelta1 = cos(getLatitude().asRadians());
159  double const cosDelta2 = cos(other.getLatitude().asRadians());
160 
161  // Adapted from http://www.movable-type.co.uk/scripts/latlong.html
162  double const y = sin(deltaLon) * cosDelta2;
163  double const x = cosDelta1 * sinDelta2 - sinDelta1 * cosDelta2 * cos(deltaLon);
164  return (90.0 * degrees - atan2(y, x) * radians).wrap();
165 }
166 
167 Angle SpherePoint::separation(SpherePoint const& other) const noexcept {
168  return haversine(getLongitude() - other.getLongitude(), getLatitude() - other.getLatitude(),
169  cos(getLatitude().asRadians()), cos(other.getLatitude().asRadians()));
170 }
171 
172 SpherePoint SpherePoint::rotated(SpherePoint const& axis, Angle const& amount) const noexcept {
173  auto const rotation = Eigen::AngleAxisd(amount.asRadians(), asEigen(axis.getVector())).matrix();
174  auto const x = asEigen(getVector());
175  auto const xprime = rotation * x;
176  return SpherePoint(sphgeom::Vector3d(xprime[0], xprime[1], xprime[2]));
177 }
178 
179 SpherePoint SpherePoint::offset(Angle const& bearing, Angle const& amount) const {
180  double const phi = bearing.asRadians();
181 
182  // let v = vector in the direction bearing points (tangent to surface of sphere)
183  // To do the rotation, use rotated() method.
184  // - must provide an axis of rotation: take the cross product r x v to get that axis (pole)
185 
186  auto r = getVector();
187 
188  // Get the vector v:
189  // let u = unit vector lying on a parallel of declination
190  // let w = unit vector along line of longitude = r x u
191  // the vector v must satisfy the following:
192  // r . v = 0
193  // u . v = cos(phi)
194  // w . v = sin(phi)
195 
196  // v is a linear combination of u and w
197  // v = cos(phi)*u + sin(phi)*w
198  sphgeom::Vector3d const u(-sin(_longitude), cos(_longitude), 0.0);
199  auto w = r.cross(u);
200  auto v = cos(phi) * u + sin(phi) * w;
201 
202  // take r x v to get the axis
203  SpherePoint axis = SpherePoint(r.cross(v));
204 
205  return rotated(axis, amount);
206 }
207 
209  geom::Angle const alpha1 = this->getLongitude();
210  geom::Angle const delta1 = this->getLatitude();
211  geom::Angle const alpha2 = other.getLongitude();
212  geom::Angle const delta2 = other.getLatitude();
213 
214  // Compute the projection of "other" on a tangent plane centered at this point
215  double const sinDelta1 = std::sin(delta1);
216  double const cosDelta1 = std::cos(delta1);
217  double const sinDelta2 = std::sin(delta2);
218  double const cosDelta2 = std::cos(delta2);
219  double const cosAlphaDiff = std::cos(alpha2 - alpha1);
220  double const sinAlphaDiff = std::sin(alpha2 - alpha1);
221 
222  double const div = cosDelta1 * cosAlphaDiff * cosDelta2 + sinDelta1 * sinDelta2;
223  double const xi = cosDelta1 * sinAlphaDiff / div;
224  double const eta = (cosDelta1 * cosAlphaDiff * sinDelta2 - sinDelta1 * cosDelta2) / div;
225 
226  return std::make_pair(xi * geom::radians, eta * geom::radians);
227 }
228 
230  if (coords.size() == 0) {
231  throw LSST_EXCEPT(pex::exceptions::LengthError, "No coordinates provided to average");
232  }
233  sphgeom::Vector3d sum(0, 0, 0);
234  sphgeom::Vector3d corr(0, 0, 0); // Kahan summation correction
235  for (auto const& sp : coords) {
236  auto const point = sp.getVector();
237  // Kahan summation
238  auto const add = point - corr;
239  auto const temp = sum + add;
240  corr = (temp - sum) - add;
241  sum = temp;
242  }
243  sum /= static_cast<double>(coords.size());
244  return SpherePoint(sum);
245 }
246 
248  // Can't provide atomic guarantee anyway for I/O, so ok to be sloppy.
249  auto oldFlags = os.setf(ostream::fixed);
250  auto oldPrecision = os.precision(6);
251 
252  os << "(" << point.getLongitude().asDegrees() << ", ";
253  os.setf(ostream::showpos);
254  os << point.getLatitude().asDegrees() << ")";
255 
256  os.flags(oldFlags);
257  os.precision(oldPrecision);
258  return os;
259 }
260 
261 } // namespace geom
262 } // namespace lsst
bool operator==(SpherePoint const &other) const noexcept
true if two points have the same longitude and latitude.
Definition: SpherePoint.cc:145
T setf(T... args)
bool isFinite() const noexcept
true if this point is a well-defined position.
Definition: SpherePoint.cc:143
std::pair< Angle, Angle > getTangentPlaneOffset(SpherePoint const &other) const
Get the offset from a tangent plane centered at this point to another point.
Definition: SpherePoint.cc:208
table::Key< lsst::geom::Angle > latitude
Definition: VisitInfo.cc:170
Angle bearingTo(SpherePoint const &other) const
Orientation at this point of the great circle arc to another point.
Definition: SpherePoint.cc:153
constexpr double asRadians() const noexcept
Return an Angle&#39;s value in radians.
Definition: Angle.h:163
constexpr double asDegrees() const noexcept
Return an Angle&#39;s value in degrees.
Definition: Angle.h:166
Point2D getPosition(AngleUnit unit) const noexcept
Return longitude, latitude as a Point2D object.
Definition: SpherePoint.cc:128
Reports attempts to exceed implementation-defined length limits for some classes. ...
Definition: Runtime.h:76
T to_string(T... args)
int y
Definition: SpanSet.cc:49
T norm(const T &x)
Definition: Integrate.h:194
STL namespace.
T precision(T... args)
Angle getLongitude() const noexcept
The longitude of this point.
Definition: SpherePoint.h:178
SpherePoint rotated(SpherePoint const &axis, Angle const &amount) const noexcept
Return a point rotated from this one around an axis.
Definition: SpherePoint.cc:172
sphgeom::UnitVector3d getVector() const noexcept
A unit vector representation of this point.
Definition: SpherePoint.cc:123
Vector3d is a vector in ℝ³ with components stored in double precision.
Definition: Vector3d.h:44
double sin(Angle const &a)
Definition: Angle.h:102
def wrap(ctrl)
Definition: wrap.py:248
AngleUnit constexpr radians
constant with units of radians
Definition: Angle.h:105
A class representing an angle.
Definition: Angle.h:124
double y() const
Definition: Vector3d.h:68
Angle operator[](size_t index) const
Longitude and latitude by index.
Definition: SpherePoint.cc:132
std::ostream & operator<<(std::ostream &os, SpherePoint const &point)
Print the value of a point to a stream.
Definition: SpherePoint.cc:247
Point< double, 2 > Point2D
Definition: Point.h:324
double cos(Angle const &a)
Definition: Angle.h:103
T atan2(T... args)
T sin(T... args)
T flags(T... args)
SpherePoint() noexcept
Construct a SpherePoint with "nan" for longitude and latitude.
Definition: SpherePoint.cc:107
double x() const
Definition: Vector3d.h:66
AngleUnit constexpr degrees
constant with units of degrees
Definition: Angle.h:106
A base class for image defects.
Definition: cameraGeom.dox:3
Angle separation(SpherePoint const &other) const noexcept
Angular distance between two points.
Definition: SpherePoint.cc:167
Angle getLatitude() const noexcept
The latitude of this point.
Definition: SpherePoint.h:190
T str(T... args)
T make_pair(T... args)
T isfinite(T... args)
SpherePoint offset(Angle const &bearing, Angle const &amount) const
Return a point offset from this one along a great circle.
Definition: SpherePoint.cc:179
T cos(T... args)
T fabs(T... args)
double x
T div(T... args)
Eigen::Vector3d asEigen(sphgeom::Vector3d const &vector) noexcept
Definition: sphgeomUtils.h:36
table::Key< lsst::geom::Angle > longitude
Definition: VisitInfo.cc:171
double w
Definition: CoaddPsf.cc:69
T asin(T... args)
T size(T... args)
#define LSST_EXCEPT(type,...)
Create an exception with a given type.
Definition: Exception.h:48
Reports attempts to access elements outside a valid range of indices.
Definition: Runtime.h:89
STL class.
static LonLat fromRadians(double lon, double lat)
Definition: LonLat.h:55
SpherePoint & operator=(SpherePoint const &other) noexcept
Overwrite this object with the value of another SpherePoint.
Point in an unspecified spherical coordinate system.
Definition: SpherePoint.h:57
LonLat represents a spherical coordinate (longitude/latitude angle) pair.
Definition: LonLat.h:48
double constexpr HALFPI
Definition: Angle.h:41
bool atPole() const noexcept
true if this point is either coordinate pole.
Definition: SpherePoint.h:237
double z() const
Definition: Vector3d.h:70
Reports invalid arguments.
Definition: Runtime.h:66
lsst::geom::SpherePoint SpherePoint
Definition: misc.h:35
ItemVariant const * other
Definition: Schema.cc:55
lsst::geom::Angle Angle
Definition: misc.h:33
UnitVector3d is a unit vector in ℝ³ with components stored in double precision.
Definition: UnitVector3d.h:55
bool operator!=(SpherePoint const &other) const noexcept
false if two points represent the same position.
Definition: SpherePoint.cc:151
T sqrt(T... args)
STL class.
static UnitVector3d fromNormalized(Vector3d const &v)
fromNormalized returns the unit vector equal to v, which is assumed to be normalized.
Definition: UnitVector3d.h:82
A class used to convert scalar POD types such as double to Angle.
Definition: Angle.h:70
std::ostream * os
Definition: Schema.cc:737
SpherePoint averageSpherePoint(std::vector< SpherePoint > const &coords)
Return the average of a list of coordinates.
Definition: SpherePoint.cc:229
double getNorm() const
getNorm returns the L2 norm of this vector.
Definition: Vector3d.h:81